简体   繁体   English

如何为此中间件文件django编写适当的单元测试用例?

[英]How to write a proper unit test case for this middleware file django?

I am working with django and now in a position to write unit test cases for a middleware file, views were easy since I could use a client and check with the response object. 我正在与django一起工作,现在可以为中间件文件编写单元测试用例,视图很容易,因为我可以使用客户端并检查响应对象。 But this has become a little tricky. 但这变得有些棘手。 How do I write test cases for these two conditional statements. 如何为这两个条件语句编写测试用例。

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

Have attached the host_name_from_request method too, 还附加了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])

While checking how to write test cases for middleware, I found this site but I am still not sure about how to go about it in my case. 在检查如何编写中间件测试用例时,我找到了这个站点,但是我仍然不确定在我的情况下该如何做。

I tried something like this 我尝试过这样的事情

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

and it said mock object has no attribute get_host 它说模拟对象没有属性get_host

Try using the RequestFactory class from django.test. 尝试使用django.test中的RequestFactory类。 You can modify the host by passing SERVER_NAME in the kwargs, otherwise it defaults to 'testserver' 您可以通过在kwargs中传递SERVER_NAME来修改主机,否则默认为'testserver'

https://docs.djangoproject.com/en/1.11/topics/testing/advanced/#the-request-factory https://docs.djangoproject.com/zh-CN/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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM