I work with django and am now able to write unit test cases for a middleware file, the views were easy, since I could use the client and check with the response object. But it got a little harder. How to 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
They also attached the host_name_from_request method,
def hostname_from_request(self, request):
""" Extracts hostname from request. Used for custom requests filtering.
By default removes the request 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])
Checking how to write test cases for middleware, I found this site , but I'm still not sure how to do 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 he said the mock has no get_host attribute
source
share