To Create a Request in Django Unit Tests, Retrieving the wsgi_request from the Response is Convenient
Django
2022-03-21 08:57 (3 years ago)

When creating unit tests in Django, there are times when you need a Request (WSGIRequest).
There is something called django.test.RequestFactory, which allows you to create requests. However, creating requests this way can be quite cumbersome, and since the requests created do not pass through the middleware, it can be challenging to use them for view-level tests.
Instead, using the test client to actually make requests to appropriate views is easier. The response returned contains a request property called wsgi_request, which you can use. These requests have also passed through the middleware.
client = self.client_class()
response = client.post(...)
request = response.wsgi_request
Currently unrated
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.
We look forward to discussing your development needs.