70

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 ?

Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
user1003121
  • 1,169
  • 3
  • 9
  • 14

5 Answers5

114

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)
Johan
  • 3,577
  • 1
  • 14
  • 28
Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
49

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
arogachev
  • 33,150
  • 7
  • 114
  • 117
Anton Manevskiy
  • 809
  • 6
  • 14
14

Use RequestFactory to create a dummy request.

Marco Lavagnino
  • 1,140
  • 12
  • 31
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

You mean def getEvents(request, eid) right?

With Django unittest, you can use the from django.test.client import Client to make request.

See here: Test Client

@Secator's answer is prefect as it creates a mock object which is really preferred for a really good unittest. But depending on your purpose, it might be easier to just use Django's test tools.

CppLearner
  • 16,273
  • 32
  • 108
  • 163
0

You can use django test client

from django.test import Client
c = Client()
response = c.post('/login/', {'username': 'john', 'password': 'smith'})
response.status_code
response = c.get('/customer/details/')
response.content

for more details
https://docs.djangoproject.com/en/1.11/topics/testing/tools/#overview-and-a-quick-example

Sarath Ak
  • 7,903
  • 2
  • 47
  • 48