def test_users_url(self): with translation.override('en'): self.assertEqual(reverse('users'), '/en/users/') with translation.override('nl'): self.assertEqual(reverse('users'), '/nl/gebruikers/') with translation.override('pt-br'): self.assertEqual(reverse('users'), '/pt-br/usuarios/')
def test_no_prefix_translated(self): with translation.override('en'): self.assertEqual(reverse('no-prefix-translated'), '/translated/') self.assertEqual(reverse('no-prefix-translated-slug', kwargs={'slug': 'yeah'}), '/translated/yeah/') with translation.override('nl'): self.assertEqual(reverse('no-prefix-translated'), '/vertaald/') self.assertEqual(reverse('no-prefix-translated-slug', kwargs={'slug': 'yeah'}), '/vertaald/yeah/') with translation.override('pt-br'): self.assertEqual(reverse('no-prefix-translated'), '/traduzidos/') self.assertEqual(reverse('no-prefix-translated-slug', kwargs={'slug': 'yeah'}), '/traduzidos/yeah/')
def test_regression_3600(self): # Tests for form i18n # # There were some problems with form translations in #3600 class SomeForm(Form): username = CharField(max_length=10, label=ugettext_lazy('Username')) f = SomeForm() self.assertHTMLEqual(f.as_p(), '<p><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>') # Translations are done at rendering time, so multi-lingual apps can define forms) with override('de'): self.assertHTMLEqual(f.as_p(), '<p><label for="id_username">Benutzername:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>') with override('pl', deactivate=True): self.assertHTMLEqual(f.as_p(), '<p><label for="id_username">Nazwa u\u017cytkownika:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>')
def test_i18n_intword(self): test_list = ('100', '1000000', '1200000', '1290000', '1000000000', '2000000000', '6000000000000') result_list = ('100', '1,0 Million', '1,2 Millionen', '1,3 Millionen', '1,0 Milliarde', '2,0 Milliarden', '6,0 Billionen') with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True): with translation.override('de'): self.humanize_tester(test_list, result_list, 'intword')
def test_i18n_intcomma(self): test_list = (100, 1000, 10123, 10311, 1000000, 1234567.25, '100', '1000', '10123', '10311', '1000000', None) result_list = ('100', '1.000', '10.123', '10.311', '1.000.000', '1.234.567,25', '100', '1.000', '10.123', '10.311', '1.000.000', None) with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True): with translation.override('de'): self.humanize_tester(test_list, result_list, 'intcomma')
def test_get_text_list(self): self.assertEqual(get_text_list(['a', 'b', 'c', 'd']), 'a, b, c or d') self.assertEqual(get_text_list(['a', 'b', 'c'], 'and'), 'a, b and c') self.assertEqual(get_text_list(['a', 'b'], 'and'), 'a and b') self.assertEqual(get_text_list(['a']), 'a') self.assertEqual(get_text_list([]), '') with override('ar'): self.assertEqual(get_text_list(['a', 'b', 'c']), "a، b أو c")
def testI18NLanguageNonEnglishFallback(self): """ Makes sure that the fallback language is still working properly in cases where the selected language cannot be found. """ with self.settings(LANGUAGE_CODE='fr'): with override('none'): response = self.client.get('/views/jsi18n/') self.assertContains(response, 'Choisir une heure')
def testI18NWithLocalePaths(self): extended_locale_paths = settings.LOCALE_PATHS + ( path.join(path.dirname( path.dirname(path.abspath(__file__))), 'app3', 'locale'),) with self.settings(LANGUAGE_CODE='es-ar', LOCALE_PATHS=extended_locale_paths): with override('es-ar'): response = self.client.get('/views/jsi18n/') self.assertContains(response, javascript_quote('este texto de app3 debe ser traducido'))
def test_jsi18n_fallback_language(self): """ Let's make sure that the fallback language is still working properly in cases where the selected language cannot be found. """ with self.settings(LANGUAGE_CODE='fr'): with override('fi'): response = self.client.get('/views/jsi18n/') self.assertContains(response, 'il faut le traduire')
def testI18NDifferentNonEnLangs(self): """ Similar to above but with neither default or requested language being English. """ extended_apps = list(settings.INSTALLED_APPS) + ['regressiontests.views.app3', 'regressiontests.views.app4'] with self.settings(LANGUAGE_CODE='fr', INSTALLED_APPS=extended_apps): with override('es-ar'): response = self.client.get('/views/jsi18n_multi_packages2/') self.assertContains(response, javascript_quote('este texto de app3 debe ser traducido'))
def test_localization(self): w = widgets.AdminSplitDateTime() with self.settings(USE_L10N=True): with translation.override('de-at'): w.is_localized = True self.assertHTMLEqual( conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))), '<p class="datetime">Datum: <input value="01.12.2007" type="text" class="vDateField" name="test_0" size="10" /><br />Zeit: <input value="09:30:00" type="text" class="vTimeField" name="test_1" size="8" /></p>', )
def testI18NLanguageNonEnglishDefault(self): """ Check if the Javascript i18n view returns an empty language catalog if the default language is non-English, the selected language is English and there is not 'en' translation available. See #13388, #3594 and #13726 for more details. """ with self.settings(LANGUAGE_CODE='fr'): with override('en-us'): response = self.client.get('/views/jsi18n/') self.assertNotContains(response, 'Choisir une heure')
def test_nonenglish_default_english_userpref(self): """ Same as above with the difference that there IS an 'en' translation available. The Javascript i18n view must return a NON empty language catalog with the proper English translations. See #13726 for more details. """ extended_apps = list(settings.INSTALLED_APPS) + ['regressiontests.views.app0'] with self.settings(LANGUAGE_CODE='fr', INSTALLED_APPS=extended_apps): with override('en-us'): response = self.client.get('/views/jsi18n_english_translation/') self.assertContains(response, javascript_quote('this app0 string is to be translated'))
def test_inactive_user_i18n(self): with self.settings(USE_I18N=True): with translation.override('pt-br', deactivate=True): # The user is inactive. data = { 'username': '******', 'password': '******', } form = AuthenticationForm(None, data) self.assertFalse(form.is_valid()) self.assertEqual(form.non_field_errors(), [force_text(form.error_messages['inactive'])])
def testI18NLanguageEnglishDefault(self): """ Check if the JavaScript i18n view returns a complete language catalog if the default language is en-us, the selected language has a translation available and a catalog composed by djangojs domain translations of multiple Python packages is requested. See #13388, #3594 and #13514 for more details. """ extended_apps = list(settings.INSTALLED_APPS) + ['regressiontests.views.app1', 'regressiontests.views.app2'] with self.settings(LANGUAGE_CODE='en-us', INSTALLED_APPS=extended_apps): with override('fr'): response = self.client.get('/views/jsi18n_multi_packages1/') self.assertContains(response, javascript_quote('il faut traduire cette chaîne de caractères de app1'))
def test_jsi18n_with_missing_en_files(self): """ The javascript_catalog shouldn't load the fallback language in the case that the current selected language is actually the one translated from, and hence missing translation files completely. This happens easily when you're translating from English to other languages and you've set settings.LANGUAGE_CODE to some other language than English. """ with self.settings(LANGUAGE_CODE='es'): with override('en-us'): response = self.client.get('/views/jsi18n/') self.assertNotContains(response, 'esto tiene que ser traducido')
def test_percent_symbol_escaping(self): from djangocg.template import Template, Context os.chdir(test_dir) call_command("compilemessages", locale=self.LOCALE, stderr=StringIO()) with translation.override(self.LOCALE): t = Template( '{% load i18n %}{% trans "Looks like a str fmt spec %% o but shouldn\'t be interpreted as such" %}' ) rendered = t.render(Context({})) self.assertEqual(rendered, "IT translation contains %% for the above string") t = Template('{% load i18n %}{% trans "Completed 50%% of all the tasks" %}') rendered = t.render(Context({})) self.assertEqual(rendered, "IT translation of Completed 50%% of all the tasks")
def test_jsi18n(self): """The javascript_catalog can be deployed with language settings""" for lang_code in ['es', 'fr', 'ru']: with override(lang_code): catalog = gettext.translation('djangojs', locale_dir, [lang_code]) if six.PY3: trans_txt = catalog.gettext('this is to be translated') else: trans_txt = catalog.ugettext('this is to be translated') response = self.client.get('/views/jsi18n/') # in response content must to be a line like that: # catalog['this is to be translated'] = 'same_that_trans_txt' # javascript_quote is used to be able to check unicode strings self.assertContains(response, javascript_quote(trans_txt), 1) if lang_code == 'fr': # Message with context (msgctxt) self.assertContains(response, "['month name\x04May'] = 'mai';", 1)
def test_localized_filesizeformat(self): with self.settings(USE_L10N=True): with translation.override('de', deactivate=True): self.assertEqual(filesizeformat(1023), '1023 Bytes') self.assertEqual(filesizeformat(1024), '1,0 KB') self.assertEqual(filesizeformat(10*1024), '10,0 KB') self.assertEqual(filesizeformat(1024*1024-1), '1024,0 KB') self.assertEqual(filesizeformat(1024*1024), '1,0 MB') self.assertEqual(filesizeformat(1024*1024*50), '50,0 MB') self.assertEqual(filesizeformat(1024*1024*1024-1), '1024,0 MB') self.assertEqual(filesizeformat(1024*1024*1024), '1,0 GB') self.assertEqual(filesizeformat(1024*1024*1024*1024), '1,0 TB') self.assertEqual(filesizeformat(1024*1024*1024*1024*1024), '1,0 PB') self.assertEqual(filesizeformat(1024*1024*1024*1024*1024*2000), '2000,0 PB') self.assertEqual(filesizeformat(complex(1,-1)), '0 Bytes') self.assertEqual(filesizeformat(""), '0 Bytes') self.assertEqual(filesizeformat("\N{GREEK SMALL LETTER ALPHA}"), '0 Bytes')
def test_regression_5216(self): # There was some problems with form translations in #5216 class SomeForm(Form): field_1 = CharField(max_length=10, label=ugettext_lazy('field_1')) field_2 = CharField(max_length=10, label=ugettext_lazy('field_2'), widget=TextInput(attrs={'id': 'field_2_id'})) f = SomeForm() self.assertHTMLEqual(f['field_1'].label_tag(), '<label for="id_field_1">field_1</label>') self.assertHTMLEqual(f['field_2'].label_tag(), '<label for="field_2_id">field_2</label>') # Unicode decoding problems... GENDERS = (('\xc5', 'En tied\xe4'), ('\xf8', 'Mies'), ('\xdf', 'Nainen')) class SomeForm(Form): somechoice = ChoiceField(choices=GENDERS, widget=RadioSelect(), label='\xc5\xf8\xdf') f = SomeForm() self.assertHTMLEqual(f.as_p(), '<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul>\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>') # Testing choice validation with UTF-8 bytestrings as input (these are the # Russian abbreviations "мес." and "шт.". UNITS = ((b'\xd0\xbc\xd0\xb5\xd1\x81.', b'\xd0\xbc\xd0\xb5\xd1\x81.'), (b'\xd1\x88\xd1\x82.', b'\xd1\x88\xd1\x82.')) f = ChoiceField(choices=UNITS) self.assertEqual(f.clean('\u0448\u0442.'), '\u0448\u0442.') with catch_warnings(record=True): # Ignore UnicodeWarning self.assertEqual(f.clean(b'\xd1\x88\xd1\x82.'), '\u0448\u0442.') # Translated error messages used to be buggy. with override('ru'): f = SomeForm({}) self.assertHTMLEqual(f.as_p(), '<ul class="errorlist"><li>\u041e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.</li></ul>\n<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul>\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>') # Deep copying translated text shouldn't raise an error) from djangocg.utils.translation import gettext_lazy class CopyForm(Form): degree = IntegerField(widget=Select(choices=((1, gettext_lazy('test')),))) f = CopyForm()
def render(self, context): if self.message_context: message_context = self.message_context.resolve(context) else: message_context = None tmp_context = {} for var, val in self.extra_context.items(): tmp_context[var] = val.resolve(context) # Update() works like a push(), so corresponding context.pop() is at # the end of function context.update(tmp_context) singular, vars = self.render_token_list(self.singular) # Escape all isolated '%' singular = re.sub('%(?!\()', '%%', singular) if self.plural and self.countervar and self.counter: count = self.counter.resolve(context) context[self.countervar] = count plural, plural_vars = self.render_token_list(self.plural) plural = re.sub('%(?!\()', '%%', plural) if message_context: result = translation.npgettext(message_context, singular, plural, count) else: result = translation.ungettext(singular, plural, count) vars.extend(plural_vars) else: if message_context: result = translation.pgettext(message_context, singular) else: result = translation.ugettext(singular) data = dict([(v, _render_value_in_context(context.get(v, ''), context)) for v in vars]) context.pop() try: result = result % data except (KeyError, ValueError): with translation.override(None): result = self.render(context) return result
def test_intcomma_without_number_grouping(self): # Regression for #17414 with translation.override('ja'): with self.settings(USE_L10N=True): self.humanize_tester([100], ['100'], 'intcomma')
def test_language_preserved(self): out = StringIO() with translation.override('fr'): management.call_command('dance', stdout=out) self.assertEqual(translation.get_language(), 'fr')
def test_account_register(self): with translation.override('en'): self.assertEqual(reverse('account:register'), '/en/account/register/') with translation.override('nl'): self.assertEqual(reverse('account:register'), '/nl/profiel/registeren/')
def test_prefixed(self): with translation.override('en'): self.assertEqual(reverse('prefixed'), '/en/prefixed/') with translation.override('nl'): self.assertEqual(reverse('prefixed'), '/nl/prefixed/')
def test_prefixed_i18n_disabled(self): with translation.override('en'): self.assertEqual(reverse('prefixed'), '/prefixed/') with translation.override('nl'): self.assertEqual(reverse('prefixed'), '/prefixed/')
def render(self, context): with translation.override(self.language.resolve(context)): output = self.nodelist.render(context) return output
def test_verbose_name(self): company_type = ContentType.objects.get(app_label='i18n', model='company') with translation.override('en'): self.assertEqual(six.text_type(company_type), 'Company') with translation.override('fr'): self.assertEqual(six.text_type(company_type), 'Société')
def test_flatpage_requires_trailing_slash_with_append_slash(self): form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data)) with translation.override('en'): self.assertFalse(form.is_valid()) self.assertEqual(form.errors['url'], ["URL is missing a trailing slash."])