How can I see the body of the request that Django's test client makes

379 Views Asked by At

I am writing automated tests in Django and started writing tests for an API endpoint that supports the put method. I am making my put request like so:

response = self.client.put(path, data=json.dumps({"key": "value"})
print(response.request)

As you see, I'm trying to see the details of the request that is being sent. I am particularly interested in seeing what goes into the body of the request. But the object returned by response.request is a dictionary that does not contain the "body" key or anything similar. I think this is a weird feature for the testing framework not to have, seeing as how it could come in handy in many different scenarios. Is there any way I can access the body of the request that I have not yet discovered? Or does the feature really not exist?

2

There are 2 best solutions below

3
mamareza On

You can not get request body like:

response.request.body

because Django uses FakePayload

A wrapper around BytesIO that restricts what can be read since data from the network can't be sought and cannot be read outside of its content length. This makes sure that views can't do anything under the test client that wouldn't work in real life.

0
adzh On

Write custom dispatch() in your API view. The dispatch method takes in the request and ultimately returns the response. Then just print request there or use pdb set_trace() to stop your call there.

def dispatch(self, request, *args, **kwargs):
    print(request)
    print(request.__dict__)
    print(dir(request))
    return super().dispatch(request, *args, **kwargs)`