如何将请求字段传递到Django测试中?

uqzxnwby  于 2023-02-14  发布在  Go
关注(0)|答案(1)|浏览(108)

我有一个功能:

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

其连接到端点/test_end/
我需要编写一个单元测试,但不工作-〉request. device is None
测试如下所示:

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))

怎么解决呢?
我需要将设备到函数传递到请求中

ldioqlga

ldioqlga1#

尝试使用RequestFactory生成请求,然后可以像test_function(request)一样直接调用视图
例如:

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)

相关问题