Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get request object in django unit testing?

I have a function as

def getEvents(eid, request):     ...... 

Now I want to write unit test for the above function separately (without calling the view). So how should I call the above in TestCase. Is it possible to create request ?

like image 585
user1003121 Avatar asked Apr 23 '12 09:04

user1003121


People also ask

What is request object in Django?

Django uses request and response objects to pass state through the system. When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function.

What is SimpleTestCase?

If your tests make any database queries, use subclasses TransactionTestCase or TestCase . SimpleTestCase. databases. SimpleTestCase disallows database queries by default. This helps to avoid executing write queries which will affect other tests since each SimpleTestCase test isn't run in a transaction.

What is self client in Django?

self. client , is the built-in Django test client. This isn't a real browser, and doesn't even make real requests. It just constructs a Django HttpRequest object and passes it through the request/response process - middleware, URL resolver, view, template - and returns whatever Django produces.


2 Answers

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 Client  client = 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 
like image 37
Anton Manevskiy Avatar answered Sep 24 '22 18:09

Anton Manevskiy


See this solution:

from django.utils import unittest from django.test.client import RequestFactory  class 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) 
like image 133
Mariusz Jamro Avatar answered Sep 22 '22 18:09

Mariusz Jamro