Background: I'm using the middleware django-multihost (http://effbot.org/zone/django-multihost.htm) to allow my single django app to respond to different hostnames from the same project.  The middleware changes the ROOT_URLCONF (i.e. which urls.py file) based on the Host: HTTP request header.  
This works great, but I want to write some simple integration tests that check that the pages are loading properly.  Here's an example of a basic test that checks if the /trends page loads and that it has the text "Trends for Today" on it:
def test_homepage_loads(self):
    client = Client()
    client.login(username = 'testing', password = 'testing')
    page = client.get("/trends", follow = follow_redirects)
    self.assertEquals(page.status_code, 200)
    self.assertTrue( page.content.find('Trends for Today') > 0 )
Problem is, this always loads using the default ROOT_URLCONF rather than the one the Middleware would invoke.  Doesn't matter if I explicitly put the hostname into the url as in client.get("http://secondarysite/trends").
How can I test on the other virtual sites with the django test client? I'd like to invoke the middleware in the test so I can test that logic. But if I need to I'd do something hacky like set ROOT_URLCONF for the duration of the tests, but I'm not sure how to do that.
Using the Django Client you can set HTTP headers like this:
client.get(url, HTTP_HOST = 'my.host.com')
Basically the get functions take a dict of arguments, which it will use as HTTP headers. To adhere to DRY, you could do something like this in setup() of the unittest class:
self.request_headers = { 'HTTP_HOST': 'foo' }
And in your test method:
client.get(url, **self.request_headers)
Note: I'm not sure if this will work for your problem. This is however the only way I can think of to set the headers.
Another solution I can think of is to set the URLConf on your test class, like this:
class Mytest(TestCase):
    urls = 'my.urlconf'
This would however not test the middleware.
http://docs.djangoproject.com/en/dev/topics/testing/#django.test.client.Client.get:
The extra keyword arguments parameter can be used to specify headers to be sent in the request
So, you might try to override HTTP_HOST header.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With