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 _
.
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
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/
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