To Create a Request in Django Unit Tests, Retrieving the wsgi_request from the Response is Convenient

Django
2022-03-21 17:57 (2 years ago) ytyng

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

Comments

Archive

2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011