Django 中间件不修改测试中的请求
Django Middleware does not modify request in tests
我正在尝试为我的自定义中间件创建测试 class。该项目正在使用 Django REST 框架。中间件 class 在服务器 运行ning 时工作正常,但是当我 运行 测试时它的行为并不像我期望的那样。也许我误解了什么,因为我对 Django 测试还很陌生。
my_middleware.py:
class FX:
a = False
b = None
c = ''
def __init__(self) -> None:
pass
def __str__(self):
return 'fx ok'
class MyMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
request.fx = FX()
response = self.get_response(request)
print('done')
return response
views.py:
class TestView(APIView):
def get(self, request, format=None):
print('View ok')
print('FX: ', request.fx)
return Response({'result':'ok'})
tests.py:
class TestMyMiddleware(APITestCase):
@classmethod
def setUpTestData(cls):
pass
def setUp(self):
pass
def test_fx(self):
response = self.client.get(reverse('TestView'), content_type="application/json")
request = response.request
self.assertTrue(hasattr(request, 'fx'))
上面的代码实际上运行是中间件。它从中间件调用打印“完成”,然后打印 'View ok' 并打印 FX 实例。但是 request.fx 在 test_fx 方法中不可用,因此断言失败:
self.assertTrue(hasattr(request, 'fx'))
AssertionError: False is not true
知道我做错了什么吗?
您需要使用 response.wsgi_request
而不是 response.request
从响应访问请求对象。
class TestMyMiddleware(APITestCase):
@classmethod
def setUpTestData(cls):
pass
def setUp(self):
pass
def test_fx(self):
response = self.client.get(reverse('TestView'), content_type="application/json")
request = response.wsgi_request
self.assertTrue(hasattr(request, 'fx'))
我正在尝试为我的自定义中间件创建测试 class。该项目正在使用 Django REST 框架。中间件 class 在服务器 运行ning 时工作正常,但是当我 运行 测试时它的行为并不像我期望的那样。也许我误解了什么,因为我对 Django 测试还很陌生。
my_middleware.py:
class FX:
a = False
b = None
c = ''
def __init__(self) -> None:
pass
def __str__(self):
return 'fx ok'
class MyMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
request.fx = FX()
response = self.get_response(request)
print('done')
return response
views.py:
class TestView(APIView):
def get(self, request, format=None):
print('View ok')
print('FX: ', request.fx)
return Response({'result':'ok'})
tests.py:
class TestMyMiddleware(APITestCase):
@classmethod
def setUpTestData(cls):
pass
def setUp(self):
pass
def test_fx(self):
response = self.client.get(reverse('TestView'), content_type="application/json")
request = response.request
self.assertTrue(hasattr(request, 'fx'))
上面的代码实际上运行是中间件。它从中间件调用打印“完成”,然后打印 'View ok' 并打印 FX 实例。但是 request.fx 在 test_fx 方法中不可用,因此断言失败:
self.assertTrue(hasattr(request, 'fx'))
AssertionError: False is not true
知道我做错了什么吗?
您需要使用 response.wsgi_request
而不是 response.request
从响应访问请求对象。
class TestMyMiddleware(APITestCase):
@classmethod
def setUpTestData(cls):
pass
def setUp(self):
pass
def test_fx(self):
response = self.client.get(reverse('TestView'), content_type="application/json")
request = response.wsgi_request
self.assertTrue(hasattr(request, 'fx'))