如何为这个中间件文件django编写一个合适的单元测试用例?

时间:2017-12-29 10:07:23

标签: python django unit-testing

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

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

1 个答案:

答案 0 :(得分:1)

尝试使用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))