[Fixed]-How to disable translations during unit tests in django?

11👍

I solved this same issue with approach number 4. from @Denilson Sá’s answer. It turns out this does not require any test-specific settings file and can be defined on a per-test basis with a decorator or context manager provided by django (see overriding settings).

It can be used like this:

from django.test import TestCase, override_settings

class MyTest(TestCase):
    @override_settings(LANGUAGE_CODE='en-US', LANGUAGES=(('en', 'English'),))
    def test_mypage(self):
        // ...

The decorator can also be applied to the entire TestCase subclass, or for even more fine-grained control there is also a context manager (see the docs linked above).

Being this rather common for me, I also defined:

english = override_settings(
    LANGUAGE_CODE='en-US',
    LANGUAGES=(('en', 'English'),),
)

So that now I can simply use @english on the test cases requiring it.

👤Davide

14👍

Calling .get() or .post() on the test client will run all the configured middlewares. This means it will also run LocaleMiddleware, which will call translation.get_language_from_request() followed by translation.activate(language).

What this means is that the currently active language is ignored and thrown away when writing tests using the test client. In other words, the following code does not work:

def testFoobar(self):
    c = Client()
    # This will not work.
    translation.deactivate_all()
    # This will not work either.
    translation.activate('en-us')
    # The next call will override the earlier activate/deactivate calls.
    response = c.get("/foobar")

There a few solutions:

  1. Setting the desired language at the session object.
  2. Setting the desired language at a cookie.
  3. Sending HTTP_ACCEPT_LANGUAGE header.
  4. Setting settings.LANGUAGE_CODE

Source (from Django 1.4, but it is mostly unchanged since 1.1 or earlier):

1👍

I would think it would make more sense to just force the language to a known setting for your unit tests. This means you’re testing something which is closer to the real implementation.

To activate a specific language you could do this in your setup:

from django.utils.translation import activate
...
activate('en-en')

Leave a comment