I have a django app that uses a custom middleware module to create a subdomain attribute in all requests. This attribute is assigned a string. Everything works during system testing, but I would like to run automated tests on this attribute so my question is:
When I generate a request during unit testing how do I set request.subdomain to a string value so I can test the code? Do I need to create a custom request and then feed it into the test client? Thanks for your time.
Solution Below
The custom middleware reads the HTTP_HOST string and saves the subdomain in the attribute request.subdomain. My problem was in how to squirt the subdomain request into the client during unit testing. Here’s how:
The test Client object allows you to preset any of the key:value pairs in the request.META dictionary. When running tests if you want to set the host name to a subdomain, do it like so:
host = 'subdomain1.test.com:8000'
c = Client(HTTP_HOST=host)
response = c.get(path='/home')
And the test will execute as if someone typed subdomain1.test.com:8000/home in the browser.
All middlewares work normally during testing. So you can test the whole view (and check if it returns something specific for your request) – it’s functional testing. Or you can create a
MockRequestand pass it directly to your middleware’sprocess_request– it is unit testing. Actually, I’d use both altogether.