gpt4 book ai didi

python - 如何为此中间件文件 django 编写正确的单元测试用例?

转载 作者:太空宇宙 更新时间:2023-11-03 11:42:08 25 4
gpt4 key购买 nike

我正在使用 django,现在可以为中间件文件编写单元测试用例, View 很容易,因为我可以使用客户端并检查响应对象。但这变得有点棘手。如何为这两个条件语句编写测试用例。

def process_request(self, request):
connection.set_schema_to_public()
hostname = self.hostname_from_request(request)

if hostname == settings.MAIN_SITE_HOST_NAME:
return None
elif hostname == 'tenant.test.com':
request.tenant = request.institute = Institute.objects.get(
domain_url=hostname, schema_name='test')

connection.set_tenant(request.tenant)
return None

也附加了 host_name_from_request 方法,

def hostname_from_request(self, request):
""" Extracts hostname from request. Used for custom requests filtering.
By default removes the request's port and common prefixes.
"""
domain_parts = request.get_host().split('.')
if len(domain_parts) > 3:
return remove_www(request.get_host().split(':')[0])
else:
return (request.get_host().split(':')[0])

在检查如何为中间件编写测试用例时,我发现了this site但我仍然不确定如何处理我的情况。

我试过这样的东西

def test_from_client(self):
self.middleware = InstituteMiddleWare()
self.request = Mock()
self.request.path('/')
self.assertIsNone(self.middleware.process_request(self.request))

它说模拟对象没有属性get_host

最佳答案

尝试使用 django.test 中的 RequestFactory 类。您可以通过在 kwargs 中传递 SERVER_NAME 来修改主机,否则它默认为 'testserver'

https://docs.djangoproject.com/en/1.11/topics/testing/advanced/#the-request-factory

from django.test import RequestFactory
def test_from_client(self):
self.middleware = InstituteMiddleWare()
self.factory = RequestFactory(SERVER_NAME='tenant.test.com')

request = self.factory.get("/")
self.assertIsNone(self.middleware.process_request(request))

关于python - 如何为此中间件文件 django 编写正确的单元测试用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48020838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com