0

I have a function:

def test_function(request):
    return request.device.id

which connected to endpoint /test_end/

I need to write a unittest but not working -> request.device is None

Test looks like this:

from django.test import TestCase
from django.test.client import Client


class Device:
    def __int__(self, _id):
        self.id = _id


class MyTest(TestCase):
    
    def test_device(self):
        client = Client()
        response = client.get("/test_end", device=Device(42))

How to fix it?

I need to pass device to function into request

1 Answers1

1

Try using RequestFactory to generate a request and then you can call the view directly like test_function(request)

For example :

from django.test import RequestFactory
request = self.factory.get('/test_end')
request.device = device() # here replace with the Device object 
response = test_function(request)
print(response)
r_a_k
  • 111
  • 2
  • 8
  • It's worked, but I need to send a request to endpoint, for checking middleware. – Avigdor Paperno Feb 13 '23 at 15:12
  • Ok. Why couldn't you check Middleware seperately like here https://stackoverflow.com/questions/62944755/how-to-unittest-new-style-django-middleware ? – r_a_k Feb 14 '23 at 16:49