Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing django internationalization - Mocking gettext

I'm internationalizing/i18n-ing a django project. We have one part that runs independently and performs background tasks. It's called by rabbitmq. I want to test that the i18n/l10n works for that part. However our app isn't translated yet, and won't be for a while. I want to write the unittests before translation begins.

I'd like to mock some translations, so that _("anything") is returned as a constant string, so that I can test that it's trying to translate things, without me needing to set up all the translations.

I tried using mock, but with mock.patch('django.utils.translations.ugettext_lazy'), my_function_that_just_returns_one_string): didn't work. The _ is imported as from django.utils.translations import ugettext_lazy as _.

like image 395
Amandasaurus Avatar asked Mar 09 '11 16:03

Amandasaurus


2 Answers

You can do the following to replace the ugettext method on the default translation object:

from django.utils.translation.trans_real import get_language, translation

translation(get_language()).ugettext = mock_ugettext
like image 61
robinst Avatar answered Oct 14 '22 07:10

robinst


I couldn't find an existing way to do this. However from reading the Django source code I came up with a hacky, brittle way to do this by looking at the _active DjangoTranslation objects, then wrapping their ugettext methods. I've described it here: http://www.technomancy.org/python/django-i18n-test-translation-by-manually-setting-translations/

like image 32
Amandasaurus Avatar answered Oct 14 '22 08:10

Amandasaurus