Django internationalization testing - Mocking gettext

I am internationalizing the / i 18n-ing django project. We have one part that works independently and performs background tasks. This is called a rabbit. I want to check if i18n / l10n works for this part. However, our application has not yet been translated and will not be for some time. I want to write unittests before starting the translation.

I would like to make fun of some translations, so that _("anything") returned as a constant string, so I can verify that it is trying to translate something without having to create all the translations.

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

+4
source share
2 answers

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

+1
source

I looked at your solution, and I find it both ingenious and easy to test for i18n support when you don't have translation strings. But I'm afraid that the translation package is something that always works and that we take for granted, therefore, seeing its insides in a highly commented test code will at least make me run away from fear (chuckle).

I think that creating a test application added to INSTALLED_APPS in the test settings, which provides its own translations, is a much cleaner approach. Your tests will be simplified to translation.activate('fr'); self.assertEqual('xxx_anything', gettext('anything'), 'i18n support should be activated.') translation.activate('fr'); self.assertEqual('xxx_anything', gettext('anything'), 'i18n support should be activated.') .

With simple tests, other developers could quickly track and see that the test application package contains the /locale directory, which should immediately document your approach.

+1
source

Source: https://habr.com/ru/post/1343032/


All Articles