Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default language via settings not respected during testing

Using Django 1.3, Python 2.6

Having a particularly weird problem to track down related to internationalization, and RequestFactory vs. TestClient for testing views.

If I run:

./manage.py test 

All tests run (including the problematic ones) and pass successfully. If I run:

./manage.py test <appname> 

The app's tests will fail, throwing a template rendering exception for templates that use the language code because the language django thinks the request is asking for is not a language we've listed in settings.LANGUAGES. (In this case it has always been 'en-us', the closet matching language we support being 'en')

Here's an example of a test that will fail:

class TemplateServingTestCase(TestCase):
    def setUp(self):
        self.app_dir      = os.path.abspath(os.path.dirname(__file__))
        self.gallery_root = os.path.join(self.app_dir, 'test_gallery')
        self.gallery_url  = '/'
        self.request      = RequestFactory().get('/')

    def test_404_invalid_category(self):
        self.assertRaises(Http404, gallery_page,
            self.request,
            'bad-category',
            self.gallery_root,
            self.gallery_url
        )

This problem will not occur if django's TestClient is used to make a request to a url that calls a particular view. However if that same view is simply called with the result of RequestFactory's get or put methods, it will throw the error above.

It appears as though when using the RequestFactory method, the settings file is not being respected. Am I missing something simple here?

Additional Information

Applicable locale settings

LANGUAGE_CODE = 'en'
LANGUAGES = (
    ('en', 'English'),
    ('de', 'Deutsch'),
    ('es', 'Espanol'),
    ('fr', 'Francaise'),
    ('it', 'Italiano'),
    ('pt-br', 'Portugues (Brasil)'),
)

Active middleware

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'services.middleware.LegacyIntegrationMiddleware',
)
like image 282
kaptainlange Avatar asked Mar 12 '12 19:03

kaptainlange


1 Answers

There are 2 possibilities :

a) You have 'django.middleware.locale.LocaleMiddleware' in settings.MIDDLEWARE_CLASSES.

In this case, the client use settings.LANGUAGE_CODE.

b) You don't.

In that case, you should set the language like that somewhere in your tests.py module:

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

https://code.djangoproject.com/ticket/15143

like image 87
Stan Avatar answered Nov 15 '22 04:11

Stan