[Fixed]-How to override Site.get_current()/request.get_host() in tests

1👍

You can control request.get_host() behaviour by passing HTTP_HOST to client.get() method. You can use SERVER_NAME, as you mentioned, but HTTP_HOST is preferred, because it is used by get_host() as is, and SERVER_NAME is used with respect to SERVER_PORT variable, so you can get “SERVER_NAME:SERVER_PORT” in some non-default port cases.

So your test could look like this:

from django.test import TestCase

class FooTests(TestCase):
    def test_bar(self):
        self.client.get('/', HTTP_HOST='example.com')

If you want to do it in whole test case class, you can override client_class like this:

from django.test import TestCase
from django.test.client import Client


class MyClient(Client):
    HTTP_HOST = 'example.com'

    def get(self, *args, **kwargs):
        kwargs.setdefault('HTTP_HOST', self.HTTP_HOST)
        return super(MyClient, self).get(*args, **kwargs)


class MyTestCase(TestCase):
    client_class = MyClient


class FooTests(MyTestCase):
    def test_foo(self):
        self.client.get('/')

Or you can write a Mixin for TestCase, which will look similar to my previous example.

Finally, you can override django.test.TestCase.client_class. This will work globally, but it looks a bit hacky, so I would not recommend you to do that.

👤vasi1y

Leave a comment