how to get request object in django unit testing? how to get request object in django unit testing? python python

how to get request object in django unit testing?


See this solution:

from django.utils import unittestfrom django.test.client import RequestFactoryclass SimpleTest(unittest.TestCase):    def setUp(self):        # Every test needs access to the request factory.        self.factory = RequestFactory()    def test_details(self):        # Create an instance of a GET request.        request = self.factory.get('/customer/details')        # Test my_view() as if it were deployed at /customer/details        response = my_view(request)        self.assertEqual(response.status_code, 200)


If you are using django test client (from django.test.client import Client) you can access request from response object like this:

from django.test.client import Clientclient = Client()response = client.get(some_url)request = response.wsgi_request

or if you are using django.TestCase(from django.test import TestCase, SimpleTestCase, TransactionTestCase) you can access client instance in any testcase just by typing self.client:

response = self.client.get(some_url)request = response.wsgi_request