| 1 |
import datetime |
| 2 |
import decimal |
| 3 |
import gettext as gettext_module |
| 4 |
import os |
| 5 |
import pickle |
| 6 |
import re |
| 7 |
import tempfile |
| 8 |
from contextlib import contextmanager |
| 9 |
from importlib import import_module |
| 10 |
from pathlib import Path |
| 11 |
from unittest import mock, skipUnless |
| 12 |
|
| 13 |
from asgiref.local import Local |
| 14 |
|
| 15 |
from django import forms |
| 16 |
from django.apps import AppConfig |
| 17 |
from django.conf import settings |
| 18 |
from django.conf.locale import LANG_INFO |
| 19 |
from django.conf.urls.i18n import i18n_patterns |
| 20 |
from django.core.management.utils import find_command, popen_wrapper |
| 21 |
from django.template import Context, Template |
| 22 |
from django.test import RequestFactory, SimpleTestCase, TestCase, override_settings |
| 23 |
from django.utils import translation |
| 24 |
from django.utils.formats import ( |
| 25 |
date_format, |
| 26 |
get_format, |
| 27 |
iter_format_modules, |
| 28 |
localize, |
| 29 |
localize_input, |
| 30 |
reset_format_cache, |
| 31 |
sanitize_separators, |
| 32 |
sanitize_strftime_format, |
| 33 |
time_format, |
| 34 |
) |
| 35 |
from django.utils.numberformat import format as nformat |
| 36 |
from django.utils.safestring import SafeString, mark_safe |
| 37 |
from django.utils.translation import ( |
| 38 |
activate, |
| 39 |
check_for_language, |
| 40 |
deactivate, |
| 41 |
get_language, |
| 42 |
get_language_bidi, |
| 43 |
get_language_from_request, |
| 44 |
get_language_info, |
| 45 |
gettext, |
| 46 |
gettext_lazy, |
| 47 |
ngettext, |
| 48 |
ngettext_lazy, |
| 49 |
npgettext, |
| 50 |
npgettext_lazy, |
| 51 |
pgettext, |
| 52 |
round_away_from_one, |
| 53 |
to_language, |
| 54 |
to_locale, |
| 55 |
trans_null, |
| 56 |
trans_real, |
| 57 |
) |
| 58 |
from django.utils.translation.reloader import ( |
| 59 |
translation_file_changed, |
| 60 |
watch_for_translation_changes, |
| 61 |
) |
| 62 |
from django.utils.translation.trans_real import LANGUAGE_CODE_MAX_LENGTH |
| 63 |
|
| 64 |
from .forms import CompanyForm, I18nForm, SelectDateForm |
| 65 |
from .models import Company, TestModel |
| 66 |
|
| 67 |
here = os.path.dirname(os.path.abspath(__file__)) |
| 68 |
extended_locale_paths = settings.LOCALE_PATHS + [ |
| 69 |
os.path.join(here, "other", "locale"), |
| 70 |
] |
| 71 |
|
| 72 |
|
| 73 |
class AppModuleStub: |
| 74 |
def __init__(self, **kwargs): |
| 75 |
self.__dict__.update(kwargs) |
| 76 |
|
| 77 |
|
| 78 |
@contextmanager |
| 79 |
def patch_formats(lang, **settings): |
| 80 |
from django.utils.formats import _format_cache |
| 81 |
|
| 82 |
# Populate _format_cache with temporary values |
| 83 |
for key, value in settings.items(): |
| 84 |
_format_cache[(key, lang)] = value |
| 85 |
try: |
| 86 |
yield |
| 87 |
finally: |
| 88 |
reset_format_cache() |
| 89 |
|
| 90 |
|
| 91 |
class TranslationTests(SimpleTestCase): |
| 92 |
@translation.override("fr") |
| 93 |
def test_plural(self): |
| 94 |
""" |
| 95 |
Test plurals with ngettext. French differs from English in that 0 is singular. |
| 96 |
""" |
| 97 |
self.assertEqual( |
| 98 |
ngettext("%(num)d year", "%(num)d years", 0) % {"num": 0}, |
| 99 |
"0 année", |
| 100 |
) |
| 101 |
self.assertEqual( |
| 102 |
ngettext("%(num)d year", "%(num)d years", 2) % {"num": 2}, |
| 103 |
"2 ans", |
| 104 |
) |
| 105 |
self.assertEqual( |
| 106 |
ngettext("%(size)d byte", "%(size)d bytes", 0) % {"size": 0}, "0 octet" |
| 107 |
) |
| 108 |
self.assertEqual( |
| 109 |
ngettext("%(size)d byte", "%(size)d bytes", 2) % {"size": 2}, "2 octets" |
| 110 |
) |
| 111 |
|
| 112 |
def test_plural_null(self): |
| 113 |
g = trans_null.ngettext |
| 114 |
self.assertEqual(g("%(num)d year", "%(num)d years", 0) % {"num": 0}, "0 years") |
| 115 |
self.assertEqual(g("%(num)d year", "%(num)d years", 1) % {"num": 1}, "1 year") |
| 116 |
self.assertEqual(g("%(num)d year", "%(num)d years", 2) % {"num": 2}, "2 years") |
| 117 |
|
| 118 |
@override_settings(LOCALE_PATHS=extended_locale_paths) |
| 119 |
@translation.override("fr") |
| 120 |
def test_multiple_plurals_per_language(self): |
| 121 |
""" |
| 122 |
Normally, French has 2 plurals. As other/locale/fr/LC_MESSAGES/django.po |
| 123 |
has a different plural equation with 3 plurals, this tests if those |
| 124 |
plural are honored. |
| 125 |
""" |
| 126 |
self.assertEqual(ngettext("%d singular", "%d plural", 0) % 0, "0 pluriel1") |
| 127 |
self.assertEqual(ngettext("%d singular", "%d plural", 1) % 1, "1 singulier") |
| 128 |
self.assertEqual(ngettext("%d singular", "%d plural", 2) % 2, "2 pluriel2") |
| 129 |
french = trans_real.catalog() |
| 130 |
# Internal _catalog can query subcatalogs (from different po files). |
| 131 |
self.assertEqual(french._catalog[("%d singular", 0)], "%d singulier") |
| 132 |
self.assertEqual(french._catalog[("%(num)d hour", 0)], "%(num)d heure") |
| 133 |
|
| 134 |
@translation.override("fr") |
| 135 |
@skipUnless(find_command("msgfmt"), "msgfmt is mandatory for this test") |
| 136 |
def test_multiple_plurals_merge(self): |
| 137 |
def _create_translation_from_string(content): |
| 138 |
with tempfile.TemporaryDirectory() as dirname: |
| 139 |
po_path = Path(dirname).joinpath("fr", "LC_MESSAGES", "django.po") |
| 140 |
po_path.parent.mkdir(parents=True) |
| 141 |
po_path.write_text(content) |
| 142 |
errors = popen_wrapper( |
| 143 |
["msgfmt", "-o", po_path.with_suffix(".mo"), po_path] |
| 144 |
)[1] |
| 145 |
if errors: |
| 146 |
self.fail(f"msgfmt compilation error: {errors}") |
| 147 |
return gettext_module.translation( |
| 148 |
domain="django", |
| 149 |
localedir=dirname, |
| 150 |
languages=["fr"], |
| 151 |
) |
| 152 |
|
| 153 |
french = trans_real.catalog() |
| 154 |
# Merge a new translation file with different plural forms. |
| 155 |
catalog1 = _create_translation_from_string( |
| 156 |
'msgid ""\n' |
| 157 |
'msgstr ""\n' |
| 158 |
'"Content-Type: text/plain; charset=UTF-8\\n"\n' |
| 159 |
'"Plural-Forms: nplurals=3; plural=(n==1 ? 0 : n==0 ? 1 : 2);\\n"\n' |
| 160 |
'msgid "I win"\n' |
| 161 |
'msgstr "Je perds"\n' |
| 162 |
) |
| 163 |
french.merge(catalog1) |
| 164 |
# Merge a second translation file with plural forms from django.conf. |
| 165 |
catalog2 = _create_translation_from_string( |
| 166 |
'msgid ""\n' |
| 167 |
'msgstr ""\n' |
| 168 |
'"Content-Type: text/plain; charset=UTF-8\\n"\n' |
| 169 |
'"Plural-Forms: Plural-Forms: nplurals=2; plural=(n > 1);\\n"\n' |
| 170 |
'msgid "I win"\n' |
| 171 |
'msgstr "Je gagne"\n' |
| 172 |
) |
| 173 |
french.merge(catalog2) |
| 174 |
# Translations from this last one are supposed to win. |
| 175 |
self.assertEqual(french.gettext("I win"), "Je gagne") |
| 176 |
|
| 177 |
def test_override(self): |
| 178 |
activate("de") |
| 179 |
try: |
| 180 |
with translation.override("pl"): |
| 181 |
self.assertEqual(get_language(), "pl") |
| 182 |
self.assertEqual(get_language(), "de") |
| 183 |
with translation.override(None): |
| 184 |
self.assertIsNone(get_language()) |
| 185 |
with translation.override("pl"): |
| 186 |
pass |
| 187 |
self.assertIsNone(get_language()) |
| 188 |
self.assertEqual(get_language(), "de") |
| 189 |
finally: |
| 190 |
deactivate() |
| 191 |
|
| 192 |
def test_override_decorator(self): |
| 193 |
@translation.override("pl") |
| 194 |
def func_pl(): |
| 195 |
self.assertEqual(get_language(), "pl") |
| 196 |
|
| 197 |
@translation.override(None) |
| 198 |
def func_none(): |
| 199 |
self.assertIsNone(get_language()) |
| 200 |
|
| 201 |
try: |
| 202 |
activate("de") |
| 203 |
func_pl() |
| 204 |
self.assertEqual(get_language(), "de") |
| 205 |
func_none() |
| 206 |
self.assertEqual(get_language(), "de") |
| 207 |
finally: |
| 208 |
deactivate() |
| 209 |
|
| 210 |
def test_override_exit(self): |
| 211 |
""" |
| 212 |
The language restored is the one used when the function was |
| 213 |
called, not the one used when the decorator was initialized (#23381). |
| 214 |
""" |
| 215 |
activate("fr") |
| 216 |
|
| 217 |
@translation.override("pl") |
| 218 |
def func_pl(): |
| 219 |
pass |
| 220 |
|
| 221 |
deactivate() |
| 222 |
|
| 223 |
try: |
| 224 |
activate("en") |
| 225 |
func_pl() |
| 226 |
self.assertEqual(get_language(), "en") |
| 227 |
finally: |
| 228 |
deactivate() |
| 229 |
|
| 230 |
def test_lazy_objects(self): |
| 231 |
""" |
| 232 |
Format string interpolation should work with *_lazy objects. |
| 233 |
""" |
| 234 |
s = gettext_lazy("Add %(name)s") |
| 235 |
d = {"name": "Ringo"} |
| 236 |
self.assertEqual("Add Ringo", s % d) |
| 237 |
with translation.override("de", deactivate=True): |
| 238 |
self.assertEqual("Ringo hinzuf\xfcgen", s % d) |
| 239 |
with translation.override("pl"): |
| 240 |
self.assertEqual("Dodaj Ringo", s % d) |
| 241 |
|
| 242 |
# It should be possible to compare *_lazy objects. |
| 243 |
s1 = gettext_lazy("Add %(name)s") |
| 244 |
self.assertEqual(s, s1) |
| 245 |
s2 = gettext_lazy("Add %(name)s") |
| 246 |
s3 = gettext_lazy("Add %(name)s") |
| 247 |
self.assertEqual(s2, s3) |
| 248 |
self.assertEqual(s, s2) |
| 249 |
s4 = gettext_lazy("Some other string") |
| 250 |
self.assertNotEqual(s, s4) |
| 251 |
|
| 252 |
def test_lazy_pickle(self): |
| 253 |
s1 = gettext_lazy("test") |
| 254 |
self.assertEqual(str(s1), "test") |
| 255 |
s2 = pickle.loads(pickle.dumps(s1)) |
| 256 |
self.assertEqual(str(s2), "test") |
| 257 |
|
| 258 |
@override_settings(LOCALE_PATHS=extended_locale_paths) |
| 259 |
def test_ngettext_lazy(self): |
| 260 |
simple_with_format = ngettext_lazy("%d good result", "%d good results") |
| 261 |
simple_context_with_format = npgettext_lazy( |
| 262 |
"Exclamation", "%d good result", "%d good results" |
| 263 |
) |
| 264 |
simple_without_format = ngettext_lazy("good result", "good results") |
| 265 |
with translation.override("de"): |
| 266 |
self.assertEqual(simple_with_format % 1, "1 gutes Resultat") |
| 267 |
self.assertEqual(simple_with_format % 4, "4 guten Resultate") |
| 268 |
self.assertEqual(simple_context_with_format % 1, "1 gutes Resultat!") |
| 269 |
self.assertEqual(simple_context_with_format % 4, "4 guten Resultate!") |
| 270 |
self.assertEqual(simple_without_format % 1, "gutes Resultat") |
| 271 |
self.assertEqual(simple_without_format % 4, "guten Resultate") |
| 272 |
|
| 273 |
complex_nonlazy = ngettext_lazy( |
| 274 |
"Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", 4 |
| 275 |
) |
| 276 |
complex_deferred = ngettext_lazy( |
| 277 |
"Hi %(name)s, %(num)d good result", |
| 278 |
"Hi %(name)s, %(num)d good results", |
| 279 |
"num", |
| 280 |
) |
| 281 |
complex_context_nonlazy = npgettext_lazy( |
| 282 |
"Greeting", |
| 283 |
"Hi %(name)s, %(num)d good result", |
| 284 |
"Hi %(name)s, %(num)d good results", |
| 285 |
4, |
| 286 |
) |
| 287 |
complex_context_deferred = npgettext_lazy( |
| 288 |
"Greeting", |
| 289 |
"Hi %(name)s, %(num)d good result", |
| 290 |
"Hi %(name)s, %(num)d good results", |
| 291 |
"num", |
| 292 |
) |
| 293 |
with translation.override("de"): |
| 294 |
self.assertEqual( |
| 295 |
complex_nonlazy % {"num": 4, "name": "Jim"}, |
| 296 |
"Hallo Jim, 4 guten Resultate", |
| 297 |
) |
| 298 |
self.assertEqual( |
| 299 |
complex_deferred % {"name": "Jim", "num": 1}, |
| 300 |
"Hallo Jim, 1 gutes Resultat", |
| 301 |
) |
| 302 |
self.assertEqual( |
| 303 |
complex_deferred % {"name": "Jim", "num": 5}, |
| 304 |
"Hallo Jim, 5 guten Resultate", |
| 305 |
) |
| 306 |
with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): |
| 307 |
complex_deferred % {"name": "Jim"} |
| 308 |
self.assertEqual( |
| 309 |
complex_context_nonlazy % {"num": 4, "name": "Jim"}, |
| 310 |
"Willkommen Jim, 4 guten Resultate", |
| 311 |
) |
| 312 |
self.assertEqual( |
| 313 |
complex_context_deferred % {"name": "Jim", "num": 1}, |
| 314 |
"Willkommen Jim, 1 gutes Resultat", |
| 315 |
) |
| 316 |
self.assertEqual( |
| 317 |
complex_context_deferred % {"name": "Jim", "num": 5}, |
| 318 |
"Willkommen Jim, 5 guten Resultate", |
| 319 |
) |
| 320 |
with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): |
| 321 |
complex_context_deferred % {"name": "Jim"} |
| 322 |
|
| 323 |
@override_settings(LOCALE_PATHS=extended_locale_paths) |
| 324 |
def test_ngettext_lazy_format_style(self): |
| 325 |
simple_with_format = ngettext_lazy("{} good result", "{} good results") |
| 326 |
simple_context_with_format = npgettext_lazy( |
| 327 |
"Exclamation", "{} good result", "{} good results" |
| 328 |
) |
| 329 |
|
| 330 |
with translation.override("de"): |
| 331 |
self.assertEqual(simple_with_format.format(1), "1 gutes Resultat") |
| 332 |
self.assertEqual(simple_with_format.format(4), "4 guten Resultate") |
| 333 |
self.assertEqual(simple_context_with_format.format(1), "1 gutes Resultat!") |
| 334 |
self.assertEqual(simple_context_with_format.format(4), "4 guten Resultate!") |
| 335 |
|
| 336 |
complex_nonlazy = ngettext_lazy( |
| 337 |
"Hi {name}, {num} good result", "Hi {name}, {num} good results", 4 |
| 338 |
) |
| 339 |
complex_deferred = ngettext_lazy( |
| 340 |
"Hi {name}, {num} good result", "Hi {name}, {num} good results", "num" |
| 341 |
) |
| 342 |
complex_context_nonlazy = npgettext_lazy( |
| 343 |
"Greeting", |
| 344 |
"Hi {name}, {num} good result", |
| 345 |
"Hi {name}, {num} good results", |
| 346 |
4, |
| 347 |
) |
| 348 |
complex_context_deferred = npgettext_lazy( |
| 349 |
"Greeting", |
| 350 |
"Hi {name}, {num} good result", |
| 351 |
"Hi {name}, {num} good results", |
| 352 |
"num", |
| 353 |
) |
| 354 |
with translation.override("de"): |
| 355 |
self.assertEqual( |
| 356 |
complex_nonlazy.format(num=4, name="Jim"), |
| 357 |
"Hallo Jim, 4 guten Resultate", |
| 358 |
) |
| 359 |
self.assertEqual( |
| 360 |
complex_deferred.format(name="Jim", num=1), |
| 361 |
"Hallo Jim, 1 gutes Resultat", |
| 362 |
) |
| 363 |
self.assertEqual( |
| 364 |
complex_deferred.format(name="Jim", num=5), |
| 365 |
"Hallo Jim, 5 guten Resultate", |
| 366 |
) |
| 367 |
with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): |
| 368 |
complex_deferred.format(name="Jim") |
| 369 |
self.assertEqual( |
| 370 |
complex_context_nonlazy.format(num=4, name="Jim"), |
| 371 |
"Willkommen Jim, 4 guten Resultate", |
| 372 |
) |
| 373 |
self.assertEqual( |
| 374 |
complex_context_deferred.format(name="Jim", num=1), |
| 375 |
"Willkommen Jim, 1 gutes Resultat", |
| 376 |
) |
| 377 |
self.assertEqual( |
| 378 |
complex_context_deferred.format(name="Jim", num=5), |
| 379 |
"Willkommen Jim, 5 guten Resultate", |
| 380 |
) |
| 381 |
with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): |
| 382 |
complex_context_deferred.format(name="Jim") |
| 383 |
|
| 384 |
def test_ngettext_lazy_bool(self): |
| 385 |
self.assertTrue(ngettext_lazy("%d good result", "%d good results")) |
| 386 |
self.assertFalse(ngettext_lazy("", "")) |
| 387 |
|
| 388 |
def test_ngettext_lazy_pickle(self): |
| 389 |
s1 = ngettext_lazy("%d good result", "%d good results") |
| 390 |
self.assertEqual(s1 % 1, "1 good result") |
| 391 |
self.assertEqual(s1 % 8, "8 good results") |
| 392 |
s2 = pickle.loads(pickle.dumps(s1)) |
| 393 |
self.assertEqual(s2 % 1, "1 good result") |
| 394 |
self.assertEqual(s2 % 8, "8 good results") |
| 395 |
|
| 396 |
@override_settings(LOCALE_PATHS=extended_locale_paths) |
| 397 |
def test_pgettext(self): |
| 398 |
trans_real._active = Local() |
| 399 |
trans_real._translations = {} |
| 400 |
with translation.override("de"): |
| 401 |
self.assertEqual(pgettext("unexisting", "May"), "May") |
| 402 |
self.assertEqual(pgettext("month name", "May"), "Mai") |
| 403 |
self.assertEqual(pgettext("verb", "May"), "Kann") |
| 404 |
self.assertEqual( |
| 405 |
npgettext("search", "%d result", "%d results", 4) % 4, "4 Resultate" |
| 406 |
) |
| 407 |
|
| 408 |
def test_empty_value(self): |
| 409 |
"""Empty value must stay empty after being translated (#23196).""" |
| 410 |
with translation.override("de"): |
| 411 |
self.assertEqual("", gettext("")) |
| 412 |
s = mark_safe("") |
| 413 |
self.assertEqual(s, gettext(s)) |
| 414 |
|
| 415 |
@override_settings(LOCALE_PATHS=extended_locale_paths) |
| 416 |
def test_safe_status(self): |
| 417 |
""" |
| 418 |
Translating a string requiring no auto-escaping with gettext or pgettext |
| 419 |
shouldn't change the "safe" status. |
| 420 |
""" |
| 421 |
trans_real._active = Local() |
| 422 |
trans_real._translations = {} |
| 423 |
s1 = mark_safe("Password") |
| 424 |
s2 = mark_safe("May") |
| 425 |
with translation.override("de", deactivate=True): |
| 426 |
self.assertIs(type(gettext(s1)), SafeString) |
| 427 |
self.assertIs(type(pgettext("month name", s2)), SafeString) |
| 428 |
self.assertEqual("aPassword", SafeString("a") + s1) |
| 429 |
self.assertEqual("Passworda", s1 + SafeString("a")) |
| 430 |
self.assertEqual("Passworda", s1 + mark_safe("a")) |
| 431 |
self.assertEqual("aPassword", mark_safe("a") + s1) |
| 432 |
self.assertEqual("as", mark_safe("a") + mark_safe("s")) |
| 433 |
|
| 434 |
def test_maclines(self): |
| 435 |
""" |
| 436 |
Translations on files with Mac or DOS end of lines will be converted |
| 437 |
to unix EOF in .po catalogs. |
| 438 |
""" |
| 439 |
ca_translation = trans_real.translation("ca") |
| 440 |
ca_translation._catalog["Mac\nEOF\n"] = "Catalan Mac\nEOF\n" |
| 441 |
ca_translation._catalog["Win\nEOF\n"] = "Catalan Win\nEOF\n" |
| 442 |
with translation.override("ca", deactivate=True): |
| 443 |
self.assertEqual("Catalan Mac\nEOF\n", gettext("Mac\rEOF\r")) |
| 444 |
self.assertEqual("Catalan Win\nEOF\n", gettext("Win\r\nEOF\r\n")) |
| 445 |
|
| 446 |
def test_to_locale(self): |
| 447 |
tests = ( |
| 448 |
("en", "en"), |
| 449 |
("EN", "en"), |
| 450 |
("en-us", "en_US"), |
| 451 |
("EN-US", "en_US"), |
| 452 |
("en_US", "en_US"), |
| 453 |
# With > 2 characters after the dash. |
| 454 |
("sr-latn", "sr_Latn"), |
| 455 |
("sr-LATN", "sr_Latn"), |
| 456 |
("sr_Latn", "sr_Latn"), |
| 457 |
# 3-char language codes. |
| 458 |
("ber-MA", "ber_MA"), |
| 459 |
("BER-MA", "ber_MA"), |
| 460 |
("BER_MA", "ber_MA"), |
| 461 |
("ber_MA", "ber_MA"), |
| 462 |
# With private use subtag (x-informal). |
| 463 |
("nl-nl-x-informal", "nl_NL-x-informal"), |
| 464 |
("NL-NL-X-INFORMAL", "nl_NL-x-informal"), |
| 465 |
("sr-latn-x-informal", "sr_Latn-x-informal"), |
| 466 |
("SR-LATN-X-INFORMAL", "sr_Latn-x-informal"), |
| 467 |
) |
| 468 |
for lang, locale in tests: |
| 469 |
with self.subTest(lang=lang): |
| 470 |
self.assertEqual(to_locale(lang), locale) |
| 471 |
|
| 472 |
def test_to_language(self): |
| 473 |
self.assertEqual(to_language("en_US"), "en-us") |
| 474 |
self.assertEqual(to_language("sr_Lat"), "sr-lat") |
| 475 |
|
| 476 |
def test_language_bidi(self): |
| 477 |
self.assertIs(get_language_bidi(), False) |
| 478 |
with translation.override(None): |
| 479 |
self.assertIs(get_language_bidi(), False) |
| 480 |
|
| 481 |
def test_language_bidi_null(self): |
| 482 |
self.assertIs(trans_null.get_language_bidi(), False) |
| 483 |
with override_settings(LANGUAGE_CODE="he"): |
| 484 |
self.assertIs(get_language_bidi(), True) |
| 485 |
|
| 486 |
|
| 487 |
class TranslationLoadingTests(SimpleTestCase): |
| 488 |
def setUp(self): |
| 489 |
"""Clear translation state.""" |
| 490 |
self._old_language = get_language() |
| 491 |
self._old_translations = trans_real._translations |
| 492 |
deactivate() |
| 493 |
trans_real._translations = {} |
| 494 |
|
| 495 |
def tearDown(self): |
| 496 |
trans_real._translations = self._old_translations |
| 497 |
activate(self._old_language) |
| 498 |
|
| 499 |
@override_settings( |
| 500 |
USE_I18N=True, |
| 501 |
LANGUAGE_CODE="en", |
| 502 |
LANGUAGES=[ |
| 503 |
("en", "English"), |
| 504 |
("en-ca", "English (Canada)"), |
| 505 |
("en-nz", "English (New Zealand)"), |
| 506 |
("en-au", "English (Australia)"), |
| 507 |
], |
| 508 |
LOCALE_PATHS=[os.path.join(here, "loading")], |
| 509 |
INSTALLED_APPS=["i18n.loading_app"], |
| 510 |
) |
| 511 |
def test_translation_loading(self): |
| 512 |
""" |
| 513 |
"loading_app" does not have translations for all languages provided by |
| 514 |
"loading". Catalogs are merged correctly. |
| 515 |
""" |
| 516 |
tests = [ |
| 517 |
("en", "local country person"), |
| 518 |
("en_AU", "aussie"), |
| 519 |
("en_NZ", "kiwi"), |
| 520 |
("en_CA", "canuck"), |
| 521 |
] |
| 522 |
# Load all relevant translations. |
| 523 |
for language, _ in tests: |
| 524 |
activate(language) |
| 525 |
# Catalogs are merged correctly. |
| 526 |
for language, nickname in tests: |
| 527 |
with self.subTest(language=language): |
| 528 |
activate(language) |
| 529 |
self.assertEqual(gettext("local country person"), nickname) |
| 530 |
|
| 531 |
|
| 532 |
class TranslationThreadSafetyTests(SimpleTestCase): |
| 533 |
def setUp(self): |
| 534 |
self._old_language = get_language() |
| 535 |
self._translations = trans_real._translations |
| 536 |
|
| 537 |
# here we rely on .split() being called inside the _fetch() |
| 538 |
# in trans_real.translation() |
| 539 |
class sideeffect_str(str): |
| 540 |
def split(self, *args, **kwargs): |
| 541 |
res = str.split(self, *args, **kwargs) |
| 542 |
trans_real._translations["en-YY"] = None |
| 543 |
return res |
| 544 |
|
| 545 |
trans_real._translations = {sideeffect_str("en-XX"): None} |
| 546 |
|
| 547 |
def tearDown(self): |
| 548 |
trans_real._translations = self._translations |
| 549 |
activate(self._old_language) |
| 550 |
|
| 551 |
def test_bug14894_translation_activate_thread_safety(self): |
| 552 |
translation_count = len(trans_real._translations) |
| 553 |
# May raise RuntimeError if translation.activate() isn't thread-safe. |
| 554 |
translation.activate("pl") |
| 555 |
# make sure sideeffect_str actually added a new translation |
| 556 |
self.assertLess(translation_count, len(trans_real._translations)) |
| 557 |
|
| 558 |
|
| 559 |
class FormattingTests(SimpleTestCase): |
| 560 |
def setUp(self): |
| 561 |
super().setUp() |
| 562 |
self.n = decimal.Decimal("66666.666") |
| 563 |
self.f = 99999.999 |
| 564 |
self.d = datetime.date(2009, 12, 31) |
| 565 |
self.dt = datetime.datetime(2009, 12, 31, 20, 50) |
| 566 |
self.t = datetime.time(10, 15, 48) |
| 567 |
self.long = 10000 |
| 568 |
self.ctxt = Context( |
| 569 |
{ |
| 570 |
"n": self.n, |
| 571 |
"t": self.t, |
| 572 |
"d": self.d, |
| 573 |
"dt": self.dt, |
| 574 |
"f": self.f, |
| 575 |
"l": self.long, |
| 576 |
} |
| 577 |
) |
| 578 |
|
| 579 |
def test_all_format_strings(self): |
| 580 |
all_locales = LANG_INFO.keys() |
| 581 |
some_date = datetime.date(2017, 10, 14) |
| 582 |
some_datetime = datetime.datetime(2017, 10, 14, 10, 23) |
| 583 |
for locale in all_locales: |
| 584 |
with self.subTest(locale=locale), translation.override(locale): |
| 585 |
self.assertIn( |
| 586 |
"2017", date_format(some_date) |
| 587 |
) # Uses DATE_FORMAT by default |
| 588 |
self.assertIn( |
| 589 |
"23", time_format(some_datetime) |
| 590 |
) # Uses TIME_FORMAT by default |
| 591 |
self.assertIn("2017", date_format(some_datetime, "DATETIME_FORMAT")) |
| 592 |
self.assertIn("2017", date_format(some_date, "YEAR_MONTH_FORMAT")) |
| 593 |
self.assertIn("14", date_format(some_date, "MONTH_DAY_FORMAT")) |
| 594 |
self.assertIn("2017", date_format(some_date, "SHORT_DATE_FORMAT")) |
| 595 |
self.assertIn( |
| 596 |
"2017", |
| 597 |
date_format(some_datetime, "SHORT_DATETIME_FORMAT"), |
| 598 |
) |
| 599 |
|
| 600 |
def test_locale_independent(self): |
| 601 |
""" |
| 602 |
Localization of numbers |
| 603 |
""" |
| 604 |
with self.settings(USE_THOUSAND_SEPARATOR=False): |
| 605 |
self.assertEqual( |
| 606 |
"66666.66", |
| 607 |
nformat( |
| 608 |
self.n, decimal_sep=".", decimal_pos=2, grouping=3, thousand_sep="," |
| 609 |
), |
| 610 |
) |
| 611 |
self.assertEqual( |
| 612 |
"66666A6", |
| 613 |
nformat( |
| 614 |
self.n, decimal_sep="A", decimal_pos=1, grouping=1, thousand_sep="B" |
| 615 |
), |
| 616 |
) |
| 617 |
self.assertEqual( |
| 618 |
"66666", |
| 619 |
nformat( |
| 620 |
self.n, decimal_sep="X", decimal_pos=0, grouping=1, thousand_sep="Y" |
| 621 |
), |
| 622 |
) |
| 623 |
|
| 624 |
with self.settings(USE_THOUSAND_SEPARATOR=True): |
| 625 |
self.assertEqual( |
| 626 |
"66,666.66", |
| 627 |
nformat( |
| 628 |
self.n, decimal_sep=".", decimal_pos=2, grouping=3, thousand_sep="," |
| 629 |
), |
| 630 |
) |
| 631 |
self.assertEqual( |
| 632 |
"6B6B6B6B6A6", |
| 633 |
nformat( |
| 634 |
self.n, decimal_sep="A", decimal_pos=1, grouping=1, thousand_sep="B" |
| 635 |
), |
| 636 |
) |
| 637 |
self.assertEqual( |
| 638 |
"-66666.6", nformat(-66666.666, decimal_sep=".", decimal_pos=1) |
| 639 |
) |
| 640 |
self.assertEqual( |
| 641 |
"-66666.0", nformat(int("-66666"), decimal_sep=".", decimal_pos=1) |
| 642 |
) |
| 643 |
self.assertEqual( |
| 644 |
"10000.0", nformat(self.long, decimal_sep=".", decimal_pos=1) |
| 645 |
) |
| 646 |
self.assertEqual( |
| 647 |
"10,00,00,000.00", |
| 648 |
nformat( |
| 649 |
100000000.00, |
| 650 |
decimal_sep=".", |
| 651 |
decimal_pos=2, |
| 652 |
grouping=(3, 2, 0), |
| 653 |
thousand_sep=",", |
| 654 |
), |
| 655 |
) |
| 656 |
self.assertEqual( |
| 657 |
"1,0,00,000,0000.00", |
| 658 |
nformat( |
| 659 |
10000000000.00, |
| 660 |
decimal_sep=".", |
| 661 |
decimal_pos=2, |
| 662 |
grouping=(4, 3, 2, 1, 0), |
| 663 |
thousand_sep=",", |
| 664 |
), |
| 665 |
) |
| 666 |
self.assertEqual( |
| 667 |
"10000,00,000.00", |
| 668 |
nformat( |
| 669 |
1000000000.00, |
| 670 |
decimal_sep=".", |
| 671 |
decimal_pos=2, |
| 672 |
grouping=(3, 2, -1), |
| 673 |
thousand_sep=",", |
| 674 |
), |
| 675 |
) |
| 676 |
# This unusual grouping/force_grouping combination may be triggered |
| 677 |
# by the intcomma filter. |
| 678 |
self.assertEqual( |
| 679 |
"10000", |
| 680 |
nformat( |
| 681 |
self.long, |
| 682 |
decimal_sep=".", |
| 683 |
decimal_pos=0, |
| 684 |
grouping=0, |
| 685 |
force_grouping=True, |
| 686 |
), |
| 687 |
) |
| 688 |
# date filter |
| 689 |
self.assertEqual( |
| 690 |
"31.12.2009 в 20:50", |
| 691 |
Template('{{ dt|date:"d.m.Y в H:i" }}').render(self.ctxt), |
| 692 |
) |
| 693 |
self.assertEqual( |
| 694 |
"⌚ 10:15", Template('{{ t|time:"⌚ H:i" }}').render(self.ctxt) |
| 695 |
) |
| 696 |
|
| 697 |
def test_false_like_locale_formats(self): |
| 698 |
""" |
| 699 |
The active locale's formats take precedence over the default settings |
| 700 |
even if they would be interpreted as False in a conditional test |
| 701 |
(e.g. 0 or empty string) (#16938). |
| 702 |
""" |
| 703 |
with translation.override("fr"): |
| 704 |
with self.settings(USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="!"): |
| 705 |
self.assertEqual("\xa0", get_format("THOUSAND_SEPARATOR")) |
| 706 |
# Even a second time (after the format has been cached)... |
| 707 |
self.assertEqual("\xa0", get_format("THOUSAND_SEPARATOR")) |
| 708 |
|
| 709 |
with self.settings(FIRST_DAY_OF_WEEK=0): |
| 710 |
self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK")) |
| 711 |
# Even a second time (after the format has been cached)... |
| 712 |
self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK")) |
| 713 |
|
| 714 |
def test_l10n_enabled(self): |
| 715 |
self.maxDiff = 3000 |
| 716 |
# Catalan locale |
| 717 |
with translation.override("ca", deactivate=True): |
| 718 |
self.assertEqual(r"j E \d\e Y", get_format("DATE_FORMAT")) |
| 719 |
self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK")) |
| 720 |
self.assertEqual(",", get_format("DECIMAL_SEPARATOR")) |
| 721 |
self.assertEqual("10:15", time_format(self.t)) |
| 722 |
self.assertEqual("31 desembre de 2009", date_format(self.d)) |
| 723 |
self.assertEqual("1 abril de 2009", date_format(datetime.date(2009, 4, 1))) |
| 724 |
self.assertEqual( |
| 725 |
"desembre del 2009", date_format(self.d, "YEAR_MONTH_FORMAT") |
| 726 |
) |
| 727 |
self.assertEqual( |
| 728 |
"31/12/2009 20:50", date_format(self.dt, "SHORT_DATETIME_FORMAT") |
| 729 |
) |
| 730 |
self.assertEqual("No localizable", localize("No localizable")) |
| 731 |
|
| 732 |
with self.settings(USE_THOUSAND_SEPARATOR=True): |
| 733 |
self.assertEqual("66.666,666", localize(self.n)) |
| 734 |
self.assertEqual("99.999,999", localize(self.f)) |
| 735 |
self.assertEqual("10.000", localize(self.long)) |
| 736 |
self.assertEqual("True", localize(True)) |
| 737 |
|
| 738 |
with self.settings(USE_THOUSAND_SEPARATOR=False): |
| 739 |
self.assertEqual("66666,666", localize(self.n)) |
| 740 |
self.assertEqual("99999,999", localize(self.f)) |
| 741 |
self.assertEqual("10000", localize(self.long)) |
| 742 |
self.assertEqual("31 desembre de 2009", localize(self.d)) |
| 743 |
self.assertEqual("31 desembre de 2009 a les 20:50", localize(self.dt)) |
| 744 |
|
| 745 |
with self.settings(USE_THOUSAND_SEPARATOR=True): |
| 746 |
self.assertEqual("66.666,666", Template("{{ n }}").render(self.ctxt)) |
| 747 |
self.assertEqual("99.999,999", Template("{{ f }}").render(self.ctxt)) |
| 748 |
self.assertEqual("10.000", Template("{{ l }}").render(self.ctxt)) |
| 749 |
|
| 750 |
with self.settings(USE_THOUSAND_SEPARATOR=True): |
| 751 |
form3 = I18nForm( |
| 752 |
{ |
| 753 |
"decimal_field": "66.666,666", |
| 754 |
"float_field": "99.999,999", |
| 755 |
"date_field": "31/12/2009", |
| 756 |
"datetime_field": "31/12/2009 20:50", |
| 757 |
"time_field": "20:50", |
| 758 |
"integer_field": "1.234", |
| 759 |
} |
| 760 |
) |
| 761 |
self.assertTrue(form3.is_valid()) |
| 762 |
self.assertEqual( |
| 763 |
decimal.Decimal("66666.666"), form3.cleaned_data["decimal_field"] |
| 764 |
) |
| 765 |
self.assertEqual(99999.999, form3.cleaned_data["float_field"]) |
| 766 |
self.assertEqual( |
| 767 |
datetime.date(2009, 12, 31), form3.cleaned_data["date_field"] |
| 768 |
) |
| 769 |
self.assertEqual( |
| 770 |
datetime.datetime(2009, 12, 31, 20, 50), |
| 771 |
form3.cleaned_data["datetime_field"], |
| 772 |
) |
| 773 |
self.assertEqual( |
| 774 |
datetime.time(20, 50), form3.cleaned_data["time_field"] |
| 775 |
) |
| 776 |
self.assertEqual(1234, form3.cleaned_data["integer_field"]) |
| 777 |
|
| 778 |
with self.settings(USE_THOUSAND_SEPARATOR=False): |
| 779 |
self.assertEqual("66666,666", Template("{{ n }}").render(self.ctxt)) |
| 780 |
self.assertEqual("99999,999", Template("{{ f }}").render(self.ctxt)) |
| 781 |
self.assertEqual( |
| 782 |
"31 desembre de 2009", Template("{{ d }}").render(self.ctxt) |
| 783 |
) |
| 784 |
self.assertEqual( |
| 785 |
"31 desembre de 2009 a les 20:50", |
| 786 |
Template("{{ dt }}").render(self.ctxt), |
| 787 |
) |
| 788 |
self.assertEqual( |
| 789 |
"66666,67", Template("{{ n|floatformat:2 }}").render(self.ctxt) |
| 790 |
) |
| 791 |
self.assertEqual( |
| 792 |
"100000,0", Template("{{ f|floatformat }}").render(self.ctxt) |
| 793 |
) |
| 794 |
self.assertEqual( |
| 795 |
"66.666,67", |
| 796 |
Template('{{ n|floatformat:"2g" }}').render(self.ctxt), |
| 797 |
) |
| 798 |
self.assertEqual( |
| 799 |
"100.000,0", |
| 800 |
Template('{{ f|floatformat:"g" }}').render(self.ctxt), |
| 801 |
) |
| 802 |
self.assertEqual( |
| 803 |
"10:15", Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt) |
| 804 |
) |
| 805 |
self.assertEqual( |
| 806 |
"31/12/2009", |
| 807 |
Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt), |
| 808 |
) |
| 809 |
self.assertEqual( |
| 810 |
"31/12/2009 20:50", |
| 811 |
Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt), |
| 812 |
) |
| 813 |
self.assertEqual( |
| 814 |
date_format(datetime.datetime.now()), |
| 815 |
Template('{% now "DATE_FORMAT" %}').render(self.ctxt), |
| 816 |
) |
| 817 |
|
| 818 |
with self.settings(USE_THOUSAND_SEPARATOR=False): |
| 819 |
form4 = I18nForm( |
| 820 |
{ |
| 821 |
"decimal_field": "66666,666", |
| 822 |
"float_field": "99999,999", |
| 823 |
"date_field": "31/12/2009", |
| 824 |
"datetime_field": "31/12/2009 20:50", |
| 825 |
"time_field": "20:50", |
| 826 |
"integer_field": "1234", |
| 827 |
} |
| 828 |
) |
| 829 |
self.assertTrue(form4.is_valid()) |
| 830 |
self.assertEqual( |
| 831 |
decimal.Decimal("66666.666"), form4.cleaned_data["decimal_field"] |
| 832 |
) |
| 833 |
self.assertEqual(99999.999, form4.cleaned_data["float_field"]) |
| 834 |
self.assertEqual( |
| 835 |
datetime.date(2009, 12, 31), form4.cleaned_data["date_field"] |
| 836 |
) |
| 837 |
self.assertEqual( |
| 838 |
datetime.datetime(2009, 12, 31, 20, 50), |
| 839 |
form4.cleaned_data["datetime_field"], |
| 840 |
) |
| 841 |
self.assertEqual( |
| 842 |
datetime.time(20, 50), form4.cleaned_data["time_field"] |
| 843 |
) |
| 844 |
self.assertEqual(1234, form4.cleaned_data["integer_field"]) |
| 845 |
|
| 846 |
form5 = SelectDateForm( |
| 847 |
{ |
| 848 |
"date_field_month": "12", |
| 849 |
"date_field_day": "31", |
| 850 |
"date_field_year": "2009", |
| 851 |
} |
| 852 |
) |
| 853 |
self.assertTrue(form5.is_valid()) |
| 854 |
self.assertEqual( |
| 855 |
datetime.date(2009, 12, 31), form5.cleaned_data["date_field"] |
| 856 |
) |
| 857 |
self.assertHTMLEqual( |
| 858 |
'<select name="mydate_day" id="id_mydate_day">' |
| 859 |
'<option value="">---</option>' |
| 860 |
'<option value="1">1</option>' |
| 861 |
'<option value="2">2</option>' |
| 862 |
'<option value="3">3</option>' |
| 863 |
'<option value="4">4</option>' |
| 864 |
'<option value="5">5</option>' |
| 865 |
'<option value="6">6</option>' |
| 866 |
'<option value="7">7</option>' |
| 867 |
'<option value="8">8</option>' |
| 868 |
'<option value="9">9</option>' |
| 869 |
'<option value="10">10</option>' |
| 870 |
'<option value="11">11</option>' |
| 871 |
'<option value="12">12</option>' |
| 872 |
'<option value="13">13</option>' |
| 873 |
'<option value="14">14</option>' |
| 874 |
'<option value="15">15</option>' |
| 875 |
'<option value="16">16</option>' |
| 876 |
'<option value="17">17</option>' |
| 877 |
'<option value="18">18</option>' |
| 878 |
'<option value="19">19</option>' |
| 879 |
'<option value="20">20</option>' |
| 880 |
'<option value="21">21</option>' |
| 881 |
'<option value="22">22</option>' |
| 882 |
'<option value="23">23</option>' |
| 883 |
'<option value="24">24</option>' |
| 884 |
'<option value="25">25</option>' |
| 885 |
'<option value="26">26</option>' |
| 886 |
'<option value="27">27</option>' |
| 887 |
'<option value="28">28</option>' |
| 888 |
'<option value="29">29</option>' |
| 889 |
'<option value="30">30</option>' |
| 890 |
'<option value="31" selected>31</option>' |
| 891 |
"</select>" |
| 892 |
'<select name="mydate_month" id="id_mydate_month">' |
| 893 |
'<option value="">---</option>' |
| 894 |
'<option value="1">gener</option>' |
| 895 |
'<option value="2">febrer</option>' |
| 896 |
'<option value="3">mar\xe7</option>' |
| 897 |
'<option value="4">abril</option>' |
| 898 |
'<option value="5">maig</option>' |
| 899 |
'<option value="6">juny</option>' |
| 900 |
'<option value="7">juliol</option>' |
| 901 |
'<option value="8">agost</option>' |
| 902 |
'<option value="9">setembre</option>' |
| 903 |
'<option value="10">octubre</option>' |
| 904 |
'<option value="11">novembre</option>' |
| 905 |
'<option value="12" selected>desembre</option>' |
| 906 |
"</select>" |
| 907 |
'<select name="mydate_year" id="id_mydate_year">' |
| 908 |
'<option value="">---</option>' |
| 909 |
'<option value="2009" selected>2009</option>' |
| 910 |
'<option value="2010">2010</option>' |
| 911 |
'<option value="2011">2011</option>' |
| 912 |
'<option value="2012">2012</option>' |
| 913 |
'<option value="2013">2013</option>' |
| 914 |
'<option value="2014">2014</option>' |
| 915 |
'<option value="2015">2015</option>' |
| 916 |
'<option value="2016">2016</option>' |
| 917 |
'<option value="2017">2017</option>' |
| 918 |
'<option value="2018">2018</option>' |
| 919 |
"</select>", |
| 920 |
forms.SelectDateWidget(years=range(2009, 2019)).render( |
| 921 |
"mydate", datetime.date(2009, 12, 31) |
| 922 |
), |
| 923 |
) |
| 924 |
|
| 925 |
# Russian locale (with E as month) |
| 926 |
with translation.override("ru", deactivate=True): |
| 927 |
self.assertHTMLEqual( |
| 928 |
'<select name="mydate_day" id="id_mydate_day">' |
| 929 |
'<option value="">---</option>' |
| 930 |
'<option value="1">1</option>' |
| 931 |
'<option value="2">2</option>' |
| 932 |
'<option value="3">3</option>' |
| 933 |
'<option value="4">4</option>' |
| 934 |
'<option value="5">5</option>' |
| 935 |
'<option value="6">6</option>' |
| 936 |
'<option value="7">7</option>' |
| 937 |
'<option value="8">8</option>' |
| 938 |
'<option value="9">9</option>' |
| 939 |
'<option value="10">10</option>' |
| 940 |
'<option value="11">11</option>' |
| 941 |
'<option value="12">12</option>' |
| 942 |
'<option value="13">13</option>' |
| 943 |
'<option value="14">14</option>' |
| 944 |
'<option value="15">15</option>' |
| 945 |
'<option value="16">16</option>' |
| 946 |
'<option value="17">17</option>' |
| 947 |
'<option value="18">18</option>' |
| 948 |
'<option value="19">19</option>' |
| 949 |
'<option value="20">20</option>' |
| 950 |
'<option value="21">21</option>' |
| 951 |
'<option value="22">22</option>' |
| 952 |
'<option value="23">23</option>' |
| 953 |
'<option value="24">24</option>' |
| 954 |
'<option value="25">25</option>' |
| 955 |
'<option value="26">26</option>' |
| 956 |
'<option value="27">27</option>' |
| 957 |
'<option value="28">28</option>' |
| 958 |
'<option value="29">29</option>' |
| 959 |
'<option value="30">30</option>' |
| 960 |
'<option value="31" selected>31</option>' |
| 961 |
"</select>" |
| 962 |
'<select name="mydate_month" id="id_mydate_month">' |
| 963 |
'<option value="">---</option>' |
| 964 |
'<option value="1">\u042f\u043d\u0432\u0430\u0440\u044c</option>' |
| 965 |
'<option value="2">\u0424\u0435\u0432\u0440\u0430\u043b\u044c</option>' |
| 966 |
'<option value="3">\u041c\u0430\u0440\u0442</option>' |
| 967 |
'<option value="4">\u0410\u043f\u0440\u0435\u043b\u044c</option>' |
| 968 |
'<option value="5">\u041c\u0430\u0439</option>' |
| 969 |
'<option value="6">\u0418\u044e\u043d\u044c</option>' |
| 970 |
'<option value="7">\u0418\u044e\u043b\u044c</option>' |
| 971 |
'<option value="8">\u0410\u0432\u0433\u0443\u0441\u0442</option>' |
| 972 |
'<option value="9">\u0421\u0435\u043d\u0442\u044f\u0431\u0440\u044c' |
| 973 |
"</option>" |
| 974 |
'<option value="10">\u041e\u043a\u0442\u044f\u0431\u0440\u044c</option>' |
| 975 |
'<option value="11">\u041d\u043e\u044f\u0431\u0440\u044c</option>' |
| 976 |
'<option value="12" selected>\u0414\u0435\u043a\u0430\u0431\u0440\u044c' |
| 977 |
"</option>" |
| 978 |
"</select>" |
| 979 |
'<select name="mydate_year" id="id_mydate_year">' |
| 980 |
'<option value="">---</option>' |
| 981 |
'<option value="2009" selected>2009</option>' |
| 982 |
'<option value="2010">2010</option>' |
| 983 |
'<option value="2011">2011</option>' |
| 984 |
'<option value="2012">2012</option>' |
| 985 |
'<option value="2013">2013</option>' |
| 986 |
'<option value="2014">2014</option>' |
| 987 |
'<option value="2015">2015</option>' |
| 988 |
'<option value="2016">2016</option>' |
| 989 |
'<option value="2017">2017</option>' |
| 990 |
'<option value="2018">2018</option>' |
| 991 |
"</select>", |
| 992 |
forms.SelectDateWidget(years=range(2009, 2019)).render( |
| 993 |
"mydate", datetime.date(2009, 12, 31) |
| 994 |
), |
| 995 |
) |
| 996 |
|
| 997 |
# English locale |
| 998 |
with translation.override("en", deactivate=True): |
| 999 |
self.assertEqual("N j, Y", get_format("DATE_FORMAT")) |
| 1000 |
self.assertEqual(0, get_format("FIRST_DAY_OF_WEEK")) |
| 1001 |
self.assertEqual(".", get_format("DECIMAL_SEPARATOR")) |
| 1002 |
self.assertEqual("Dec. 31, 2009", date_format(self.d)) |
| 1003 |
self.assertEqual("December 2009", date_format(self.d, "YEAR_MONTH_FORMAT")) |
| 1004 |
self.assertEqual( |
| 1005 |
"12/31/2009 8:50 p.m.", date_format(self.dt, "SHORT_DATETIME_FORMAT") |
| 1006 |
) |
| 1007 |
self.assertEqual("No localizable", localize("No localizable")) |
| 1008 |
|
| 1009 |
with self.settings(USE_THOUSAND_SEPARATOR=True): |
| 1010 |
self.assertEqual("66,666.666", localize(self.n)) |
| 1011 |
self.assertEqual("99,999.999", localize(self.f)) |
| 1012 |
self.assertEqual("10,000", localize(self.long)) |
| 1013 |
|
| 1014 |
with self.settings(USE_THOUSAND_SEPARATOR=False): |
| 1015 |
self.assertEqual("66666.666", localize(self.n)) |
| 1016 |
self.assertEqual("99999.999", localize(self.f)) |
| 1017 |
self.assertEqual("10000", localize(self.long)) |
| 1018 |
self.assertEqual("Dec. 31, 2009", localize(self.d)) |
| 1019 |
self.assertEqual("Dec. 31, 2009, 8:50 p.m.", localize(self.dt)) |
| 1020 |
|
| 1021 |
with self.settings(USE_THOUSAND_SEPARATOR=True): |
| 1022 |
self.assertEqual("66,666.666", Template("{{ n }}").render(self.ctxt)) |
| 1023 |
self.assertEqual("99,999.999", Template("{{ f }}").render(self.ctxt)) |
| 1024 |
self.assertEqual("10,000", Template("{{ l }}").render(self.ctxt)) |
| 1025 |
|
| 1026 |
with self.settings(USE_THOUSAND_SEPARATOR=False): |
| 1027 |
self.assertEqual("66666.666", Template("{{ n }}").render(self.ctxt)) |
| 1028 |
self.assertEqual("99999.999", Template("{{ f }}").render(self.ctxt)) |
| 1029 |
self.assertEqual("Dec. 31, 2009", Template("{{ d }}").render(self.ctxt)) |
| 1030 |
self.assertEqual( |
| 1031 |
"Dec. 31, 2009, 8:50 p.m.", Template("{{ dt }}").render(self.ctxt) |
| 1032 |
) |
| 1033 |
self.assertEqual( |
| 1034 |
"66666.67", Template("{{ n|floatformat:2 }}").render(self.ctxt) |
| 1035 |
) |
| 1036 |
self.assertEqual( |
| 1037 |
"100000.0", Template("{{ f|floatformat }}").render(self.ctxt) |
| 1038 |
) |
| 1039 |
self.assertEqual( |
| 1040 |
"66,666.67", |
| 1041 |
Template('{{ n|floatformat:"2g" }}').render(self.ctxt), |
| 1042 |
) |
| 1043 |
self.assertEqual( |
| 1044 |
"100,000.0", |
| 1045 |
Template('{{ f|floatformat:"g" }}').render(self.ctxt), |
| 1046 |
) |
| 1047 |
self.assertEqual( |
| 1048 |
"12/31/2009", |
| 1049 |
Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt), |
| 1050 |
) |
| 1051 |
self.assertEqual( |
| 1052 |
"12/31/2009 8:50 p.m.", |
| 1053 |
Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt), |
| 1054 |
) |
| 1055 |
|
| 1056 |
form5 = I18nForm( |
| 1057 |
{ |
| 1058 |
"decimal_field": "66666.666", |
| 1059 |
"float_field": "99999.999", |
| 1060 |
"date_field": "12/31/2009", |
| 1061 |
"datetime_field": "12/31/2009 20:50", |
| 1062 |
"time_field": "20:50", |
| 1063 |
"integer_field": "1234", |
| 1064 |
} |
| 1065 |
) |
| 1066 |
self.assertTrue(form5.is_valid()) |
| 1067 |
self.assertEqual( |
| 1068 |
decimal.Decimal("66666.666"), form5.cleaned_data["decimal_field"] |
| 1069 |
) |
| 1070 |
self.assertEqual(99999.999, form5.cleaned_data["float_field"]) |
| 1071 |
self.assertEqual( |
| 1072 |
datetime.date(2009, 12, 31), form5.cleaned_data["date_field"] |
| 1073 |
) |
| 1074 |
self.assertEqual( |
| 1075 |
datetime.datetime(2009, 12, 31, 20, 50), |
| 1076 |
form5.cleaned_data["datetime_field"], |
| 1077 |
) |
| 1078 |
self.assertEqual(datetime.time(20, 50), form5.cleaned_data["time_field"]) |
| 1079 |
self.assertEqual(1234, form5.cleaned_data["integer_field"]) |
| 1080 |
|
| 1081 |
form6 = SelectDateForm( |
| 1082 |
{ |
| 1083 |
"date_field_month": "12", |
| 1084 |
"date_field_day": "31", |
| 1085 |
"date_field_year": "2009", |
| 1086 |
} |
| 1087 |
) |
| 1088 |
self.assertTrue(form6.is_valid()) |
| 1089 |
self.assertEqual( |
| 1090 |
datetime.date(2009, 12, 31), form6.cleaned_data["date_field"] |
| 1091 |
) |
| 1092 |
self.assertHTMLEqual( |
| 1093 |
'<select name="mydate_month" id="id_mydate_month">' |
| 1094 |
'<option value="">---</option>' |
| 1095 |
'<option value="1">January</option>' |
| 1096 |
'<option value="2">February</option>' |
| 1097 |
'<option value="3">March</option>' |
| 1098 |
'<option value="4">April</option>' |
| 1099 |
'<option value="5">May</option>' |
| 1100 |
'<option value="6">June</option>' |
| 1101 |
'<option value="7">July</option>' |
| 1102 |
'<option value="8">August</option>' |
| 1103 |
'<option value="9">September</option>' |
| 1104 |
'<option value="10">October</option>' |
| 1105 |
'<option value="11">November</option>' |
| 1106 |
'<option value="12" selected>December</option>' |
| 1107 |
"</select>" |
| 1108 |
'<select name="mydate_day" id="id_mydate_day">' |
| 1109 |
'<option value="">---</option>' |
| 1110 |
'<option value="1">1</option>' |
| 1111 |
'<option value="2">2</option>' |
| 1112 |
'<option value="3">3</option>' |
| 1113 |
'<option value="4">4</option>' |
| 1114 |
'<option value="5">5</option>' |
| 1115 |
'<option value="6">6</option>' |
| 1116 |
'<option value="7">7</option>' |
| 1117 |
'<option value="8">8</option>' |
| 1118 |
'<option value="9">9</option>' |
| 1119 |
'<option value="10">10</option>' |
| 1120 |
'<option value="11">11</option>' |
| 1121 |
'<option value="12">12</option>' |
| 1122 |
'<option value="13">13</option>' |
| 1123 |
'<option value="14">14</option>' |
| 1124 |
'<option value="15">15</option>' |
| 1125 |
'<option value="16">16</option>' |
| 1126 |
'<option value="17">17</option>' |
| 1127 |
'<option value="18">18</option>' |
| 1128 |
'<option value="19">19</option>' |
| 1129 |
'<option value="20">20</option>' |
| 1130 |
'<option value="21">21</option>' |
| 1131 |
'<option value="22">22</option>' |
| 1132 |
'<option value="23">23</option>' |
| 1133 |
'<option value="24">24</option>' |
| 1134 |
'<option value="25">25</option>' |
| 1135 |
'<option value="26">26</option>' |
| 1136 |
'<option value="27">27</option>' |
| 1137 |
'<option value="28">28</option>' |
| 1138 |
'<option value="29">29</option>' |
| 1139 |
'<option value="30">30</option>' |
| 1140 |
'<option value="31" selected>31</option>' |
| 1141 |
"</select>" |
| 1142 |
'<select name="mydate_year" id="id_mydate_year">' |
| 1143 |
'<option value="">---</option>' |
| 1144 |
'<option value="2009" selected>2009</option>' |
| 1145 |
'<option value="2010">2010</option>' |
| 1146 |
'<option value="2011">2011</option>' |
| 1147 |
'<option value="2012">2012</option>' |
| 1148 |
'<option value="2013">2013</option>' |
| 1149 |
'<option value="2014">2014</option>' |
| 1150 |
'<option value="2015">2015</option>' |
| 1151 |
'<option value="2016">2016</option>' |
| 1152 |
'<option value="2017">2017</option>' |
| 1153 |
'<option value="2018">2018</option>' |
| 1154 |
"</select>", |
| 1155 |
forms.SelectDateWidget(years=range(2009, 2019)).render( |
| 1156 |
"mydate", datetime.date(2009, 12, 31) |
| 1157 |
), |
| 1158 |
) |
| 1159 |
|
| 1160 |
def test_sub_locales(self): |
| 1161 |
""" |
| 1162 |
Check if sublocales fall back to the main locale |
| 1163 |
""" |
| 1164 |
with self.settings(USE_THOUSAND_SEPARATOR=True): |
| 1165 |
with translation.override("de-at", deactivate=True): |
| 1166 |
self.assertEqual("66.666,666", Template("{{ n }}").render(self.ctxt)) |
| 1167 |
with translation.override("es-us", deactivate=True): |
| 1168 |
self.assertEqual("31 de diciembre de 2009", date_format(self.d)) |
| 1169 |
|
| 1170 |
def test_localized_input(self): |
| 1171 |
""" |
| 1172 |
Tests if form input is correctly localized |
| 1173 |
""" |
| 1174 |
self.maxDiff = 1200 |
| 1175 |
with translation.override("de-at", deactivate=True): |
| 1176 |
form6 = CompanyForm( |
| 1177 |
{ |
| 1178 |
"name": "acme", |
| 1179 |
"date_added": datetime.datetime(2009, 12, 31, 6, 0, 0), |
| 1180 |
"cents_paid": decimal.Decimal("59.47"), |
| 1181 |
"products_delivered": 12000, |
| 1182 |
} |
| 1183 |
) |
| 1184 |
self.assertTrue(form6.is_valid()) |
| 1185 |
self.assertHTMLEqual( |
| 1186 |
form6.as_ul(), |
| 1187 |
'<li><label for="id_name">Name:</label>' |
| 1188 |
'<input id="id_name" type="text" name="name" value="acme" ' |
| 1189 |
' maxlength="50" required></li>' |
| 1190 |
'<li><label for="id_date_added">Date added:</label>' |
| 1191 |
'<input type="text" name="date_added" value="31.12.2009 06:00:00" ' |
| 1192 |
' id="id_date_added" required></li>' |
| 1193 |
'<li><label for="id_cents_paid">Cents paid:</label>' |
| 1194 |
'<input type="text" name="cents_paid" value="59,47" id="id_cents_paid" ' |
| 1195 |
" required></li>" |
| 1196 |
'<li><label for="id_products_delivered">Products delivered:</label>' |
| 1197 |
'<input type="text" name="products_delivered" value="12000" ' |
| 1198 |
' id="id_products_delivered" required>' |
| 1199 |
"</li>", |
| 1200 |
) |
| 1201 |
self.assertEqual( |
| 1202 |
localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), |
| 1203 |
"31.12.2009 06:00:00", |
| 1204 |
) |
| 1205 |
self.assertEqual( |
| 1206 |
datetime.datetime(2009, 12, 31, 6, 0, 0), |
| 1207 |
form6.cleaned_data["date_added"], |
| 1208 |
) |
| 1209 |
with self.settings(USE_THOUSAND_SEPARATOR=True): |
| 1210 |
# Checking for the localized "products_delivered" field |
| 1211 |
self.assertInHTML( |
| 1212 |
'<input type="text" name="products_delivered" ' |
| 1213 |
'value="12.000" id="id_products_delivered" required>', |
| 1214 |
form6.as_ul(), |
| 1215 |
) |
| 1216 |
|
| 1217 |
def test_localized_input_func(self): |
| 1218 |
tests = ( |
| 1219 |
(True, "True"), |
| 1220 |
(datetime.date(1, 1, 1), "0001-01-01"), |
| 1221 |
(datetime.datetime(1, 1, 1), "0001-01-01 00:00:00"), |
| 1222 |
) |
| 1223 |
with self.settings(USE_THOUSAND_SEPARATOR=True): |
| 1224 |
for value, expected in tests: |
| 1225 |
with self.subTest(value=value): |
| 1226 |
self.assertEqual(localize_input(value), expected) |
| 1227 |
|
| 1228 |
def test_sanitize_strftime_format(self): |
| 1229 |
for year in (1, 99, 999, 1000): |
| 1230 |
dt = datetime.date(year, 1, 1) |
| 1231 |
for fmt, expected in [ |
| 1232 |
("%C", "%02d" % (year // 100)), |
| 1233 |
("%F", "%04d-01-01" % year), |
| 1234 |
("%G", "%04d" % year), |
| 1235 |
("%Y", "%04d" % year), |
| 1236 |
]: |
| 1237 |
with self.subTest(year=year, fmt=fmt): |
| 1238 |
fmt = sanitize_strftime_format(fmt) |
| 1239 |
self.assertEqual(dt.strftime(fmt), expected) |
| 1240 |
|
| 1241 |
def test_sanitize_strftime_format_with_escaped_percent(self): |
| 1242 |
dt = datetime.date(1, 1, 1) |
| 1243 |
for fmt, expected in [ |
| 1244 |
("%%C", "%C"), |
| 1245 |
("%%F", "%F"), |
| 1246 |
("%%G", "%G"), |
| 1247 |
("%%Y", "%Y"), |
| 1248 |
("%%%%C", "%%C"), |
| 1249 |
("%%%%F", "%%F"), |
| 1250 |
("%%%%G", "%%G"), |
| 1251 |
("%%%%Y", "%%Y"), |
| 1252 |
]: |
| 1253 |
with self.subTest(fmt=fmt): |
| 1254 |
fmt = sanitize_strftime_format(fmt) |
| 1255 |
self.assertEqual(dt.strftime(fmt), expected) |
| 1256 |
|
| 1257 |
for year in (1, 99, 999, 1000): |
| 1258 |
dt = datetime.date(year, 1, 1) |
| 1259 |
for fmt, expected in [ |
| 1260 |
("%%%C", "%%%02d" % (year // 100)), |
| 1261 |
("%%%F", "%%%04d-01-01" % year), |
| 1262 |
("%%%G", "%%%04d" % year), |
| 1263 |
("%%%Y", "%%%04d" % year), |
| 1264 |
("%%%%%C", "%%%%%02d" % (year // 100)), |
| 1265 |
("%%%%%F", "%%%%%04d-01-01" % year), |
| 1266 |
("%%%%%G", "%%%%%04d" % year), |
| 1267 |
("%%%%%Y", "%%%%%04d" % year), |
| 1268 |
]: |
| 1269 |
with self.subTest(year=year, fmt=fmt): |
| 1270 |
fmt = sanitize_strftime_format(fmt) |
| 1271 |
self.assertEqual(dt.strftime(fmt), expected) |
| 1272 |
|
| 1273 |
def test_sanitize_separators(self): |
| 1274 |
""" |
| 1275 |
Tests django.utils.formats.sanitize_separators. |
| 1276 |
""" |
| 1277 |
# Non-strings are untouched |
| 1278 |
self.assertEqual(sanitize_separators(123), 123) |
| 1279 |
|
| 1280 |
with translation.override("ru", deactivate=True): |
| 1281 |
# Russian locale has non-breaking space (\xa0) as thousand separator |
| 1282 |
# Usual space is accepted too when sanitizing inputs |
| 1283 |
with self.settings(USE_THOUSAND_SEPARATOR=True): |
| 1284 |
self.assertEqual(sanitize_separators("1\xa0234\xa0567"), "1234567") |
| 1285 |
self.assertEqual(sanitize_separators("77\xa0777,777"), "77777.777") |
| 1286 |
self.assertEqual(sanitize_separators("12 345"), "12345") |
| 1287 |
self.assertEqual(sanitize_separators("77 777,777"), "77777.777") |
| 1288 |
with translation.override(None): |
| 1289 |
with self.settings(USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="."): |
| 1290 |
self.assertEqual(sanitize_separators("12\xa0345"), "12\xa0345") |
| 1291 |
|
| 1292 |
with self.settings(USE_THOUSAND_SEPARATOR=True): |
| 1293 |
with patch_formats( |
| 1294 |
get_language(), THOUSAND_SEPARATOR=".", DECIMAL_SEPARATOR="," |
| 1295 |
): |
| 1296 |
self.assertEqual(sanitize_separators("10.234"), "10234") |
| 1297 |
# Suspicion that user entered dot as decimal separator (#22171) |
| 1298 |
self.assertEqual(sanitize_separators("10.10"), "10.10") |
| 1299 |
|
| 1300 |
with translation.override(None): |
| 1301 |
with self.settings(DECIMAL_SEPARATOR=","): |
| 1302 |
self.assertEqual(sanitize_separators("1001,10"), "1001.10") |
| 1303 |
self.assertEqual(sanitize_separators("1001.10"), "1001.10") |
| 1304 |
with self.settings( |
| 1305 |
DECIMAL_SEPARATOR=",", |
| 1306 |
THOUSAND_SEPARATOR=".", |
| 1307 |
USE_THOUSAND_SEPARATOR=True, |
| 1308 |
): |
| 1309 |
self.assertEqual(sanitize_separators("1.001,10"), "1001.10") |
| 1310 |
self.assertEqual(sanitize_separators("1001,10"), "1001.10") |
| 1311 |
self.assertEqual(sanitize_separators("1001.10"), "1001.10") |
| 1312 |
# Invalid output. |
| 1313 |
self.assertEqual(sanitize_separators("1,001.10"), "1.001.10") |
| 1314 |
|
| 1315 |
def test_iter_format_modules(self): |
| 1316 |
""" |
| 1317 |
Tests the iter_format_modules function. |
| 1318 |
""" |
| 1319 |
# Importing some format modules so that we can compare the returned |
| 1320 |
# modules with these expected modules |
| 1321 |
default_mod = import_module("django.conf.locale.de.formats") |
| 1322 |
test_mod = import_module("i18n.other.locale.de.formats") |
| 1323 |
test_mod2 = import_module("i18n.other2.locale.de.formats") |
| 1324 |
|
| 1325 |
with translation.override("de-at", deactivate=True): |
| 1326 |
# Should return the correct default module when no setting is set |
| 1327 |
self.assertEqual(list(iter_format_modules("de")), [default_mod]) |
| 1328 |
|
| 1329 |
# When the setting is a string, should return the given module and |
| 1330 |
# the default module |
| 1331 |
self.assertEqual( |
| 1332 |
list(iter_format_modules("de", "i18n.other.locale")), |
| 1333 |
[test_mod, default_mod], |
| 1334 |
) |
| 1335 |
|
| 1336 |
# When setting is a list of strings, should return the given |
| 1337 |
# modules and the default module |
| 1338 |
self.assertEqual( |
| 1339 |
list( |
| 1340 |
iter_format_modules( |
| 1341 |
"de", ["i18n.other.locale", "i18n.other2.locale"] |
| 1342 |
) |
| 1343 |
), |
| 1344 |
[test_mod, test_mod2, default_mod], |
| 1345 |
) |
| 1346 |
|
| 1347 |
def test_iter_format_modules_stability(self): |
| 1348 |
""" |
| 1349 |
Tests the iter_format_modules function always yields format modules in |
| 1350 |
a stable and correct order in presence of both base ll and ll_CC formats. |
| 1351 |
""" |
| 1352 |
en_format_mod = import_module("django.conf.locale.en.formats") |
| 1353 |
en_gb_format_mod = import_module("django.conf.locale.en_GB.formats") |
| 1354 |
self.assertEqual( |
| 1355 |
list(iter_format_modules("en-gb")), [en_gb_format_mod, en_format_mod] |
| 1356 |
) |
| 1357 |
|
| 1358 |
def test_get_format_modules_lang(self): |
| 1359 |
with translation.override("de", deactivate=True): |
| 1360 |
self.assertEqual(".", get_format("DECIMAL_SEPARATOR", lang="en")) |
| 1361 |
|
| 1362 |
def test_get_format_lazy_format(self): |
| 1363 |
self.assertEqual(get_format(gettext_lazy("DATE_FORMAT")), "N j, Y") |
| 1364 |
|
| 1365 |
def test_localize_templatetag_and_filter(self): |
| 1366 |
""" |
| 1367 |
Test the {% localize %} templatetag and the localize/unlocalize filters. |
| 1368 |
""" |
| 1369 |
context = Context( |
| 1370 |
{"int": 1455, "float": 3.14, "date": datetime.date(2016, 12, 31)} |
| 1371 |
) |
| 1372 |
template1 = Template( |
| 1373 |
"{% load l10n %}{% localize %}" |
| 1374 |
"{{ int }}/{{ float }}/{{ date }}{% endlocalize %}; " |
| 1375 |
"{% localize on %}{{ int }}/{{ float }}/{{ date }}{% endlocalize %}" |
| 1376 |
) |
| 1377 |
template2 = Template( |
| 1378 |
"{% load l10n %}{{ int }}/{{ float }}/{{ date }}; " |
| 1379 |
"{% localize off %}{{ int }}/{{ float }}/{{ date }};{% endlocalize %} " |
| 1380 |
"{{ int }}/{{ float }}/{{ date }}" |
| 1381 |
) |
| 1382 |
template3 = Template( |
| 1383 |
"{% load l10n %}{{ int }}/{{ float }}/{{ date }}; " |
| 1384 |
"{{ int|unlocalize }}/{{ float|unlocalize }}/{{ date|unlocalize }}" |
| 1385 |
) |
| 1386 |
expected_localized = "1.455/3,14/31. Dezember 2016" |
| 1387 |
expected_unlocalized = "1455/3.14/Dez. 31, 2016" |
| 1388 |
output1 = "; ".join([expected_localized, expected_localized]) |
| 1389 |
output2 = "; ".join( |
| 1390 |
[expected_localized, expected_unlocalized, expected_localized] |
| 1391 |
) |
| 1392 |
output3 = "; ".join([expected_localized, expected_unlocalized]) |
| 1393 |
with translation.override("de", deactivate=True): |
| 1394 |
with self.settings(USE_THOUSAND_SEPARATOR=True): |
| 1395 |
self.assertEqual(template1.render(context), output1) |
| 1396 |
self.assertEqual(template2.render(context), output2) |
| 1397 |
self.assertEqual(template3.render(context), output3) |
| 1398 |
|
| 1399 |
def test_localized_off_numbers(self): |
| 1400 |
"""A string representation is returned for unlocalized numbers.""" |
| 1401 |
template = Template( |
| 1402 |
"{% load l10n %}{% localize off %}" |
| 1403 |
"{{ int }}/{{ float }}/{{ decimal }}{% endlocalize %}" |
| 1404 |
) |
| 1405 |
context = Context( |
| 1406 |
{"int": 1455, "float": 3.14, "decimal": decimal.Decimal("24.1567")} |
| 1407 |
) |
| 1408 |
with self.settings( |
| 1409 |
DECIMAL_SEPARATOR=",", |
| 1410 |
USE_THOUSAND_SEPARATOR=True, |
| 1411 |
THOUSAND_SEPARATOR="°", |
| 1412 |
NUMBER_GROUPING=2, |
| 1413 |
): |
| 1414 |
self.assertEqual(template.render(context), "1455/3.14/24.1567") |
| 1415 |
|
| 1416 |
def test_localized_as_text_as_hidden_input(self): |
| 1417 |
""" |
| 1418 |
Form input with 'as_hidden' or 'as_text' is correctly localized. |
| 1419 |
""" |
| 1420 |
self.maxDiff = 1200 |
| 1421 |
|
| 1422 |
with translation.override("de-at", deactivate=True): |
| 1423 |
template = Template( |
| 1424 |
"{% load l10n %}{{ form.date_added }}; {{ form.cents_paid }}" |
| 1425 |
) |
| 1426 |
template_as_text = Template( |
| 1427 |
"{% load l10n %}" |
| 1428 |
"{{ form.date_added.as_text }}; {{ form.cents_paid.as_text }}" |
| 1429 |
) |
| 1430 |
template_as_hidden = Template( |
| 1431 |
"{% load l10n %}" |
| 1432 |
"{{ form.date_added.as_hidden }}; {{ form.cents_paid.as_hidden }}" |
| 1433 |
) |
| 1434 |
form = CompanyForm( |
| 1435 |
{ |
| 1436 |
"name": "acme", |
| 1437 |
"date_added": datetime.datetime(2009, 12, 31, 6, 0, 0), |
| 1438 |
"cents_paid": decimal.Decimal("59.47"), |
| 1439 |
"products_delivered": 12000, |
| 1440 |
} |
| 1441 |
) |
| 1442 |
context = Context({"form": form}) |
| 1443 |
self.assertTrue(form.is_valid()) |
| 1444 |
|
| 1445 |
self.assertHTMLEqual( |
| 1446 |
template.render(context), |
| 1447 |
'<input id="id_date_added" name="date_added" type="text" ' |
| 1448 |
'value="31.12.2009 06:00:00" required>;' |
| 1449 |
'<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" ' |
| 1450 |
"required>", |
| 1451 |
) |
| 1452 |
self.assertHTMLEqual( |
| 1453 |
template_as_text.render(context), |
| 1454 |
'<input id="id_date_added" name="date_added" type="text" ' |
| 1455 |
'value="31.12.2009 06:00:00" required>;' |
| 1456 |
'<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" ' |
| 1457 |
"required>", |
| 1458 |
) |
| 1459 |
self.assertHTMLEqual( |
| 1460 |
template_as_hidden.render(context), |
| 1461 |
'<input id="id_date_added" name="date_added" type="hidden" ' |
| 1462 |
'value="31.12.2009 06:00:00">;' |
| 1463 |
'<input id="id_cents_paid" name="cents_paid" type="hidden" ' |
| 1464 |
'value="59,47">', |
| 1465 |
) |
| 1466 |
|
| 1467 |
def test_format_arbitrary_settings(self): |
| 1468 |
self.assertEqual(get_format("DEBUG"), "DEBUG") |
| 1469 |
|
| 1470 |
def test_get_custom_format(self): |
| 1471 |
reset_format_cache() |
| 1472 |
with self.settings(FORMAT_MODULE_PATH="i18n.other.locale"): |
| 1473 |
with translation.override("fr", deactivate=True): |
| 1474 |
self.assertEqual("d/m/Y CUSTOM", get_format("CUSTOM_DAY_FORMAT")) |
| 1475 |
|
| 1476 |
def test_admin_javascript_supported_input_formats(self): |
| 1477 |
""" |
| 1478 |
The first input format for DATE_INPUT_FORMATS, TIME_INPUT_FORMATS, and |
| 1479 |
DATETIME_INPUT_FORMATS must not contain %f since that's unsupported by |
| 1480 |
the admin's time picker widget. |
| 1481 |
""" |
| 1482 |
regex = re.compile("%([^BcdHImMpSwxXyY%])") |
| 1483 |
for language_code, language_name in settings.LANGUAGES: |
| 1484 |
for format_name in ( |
| 1485 |
"DATE_INPUT_FORMATS", |
| 1486 |
"TIME_INPUT_FORMATS", |
| 1487 |
"DATETIME_INPUT_FORMATS", |
| 1488 |
): |
| 1489 |
with self.subTest(language=language_code, format=format_name): |
| 1490 |
formatter = get_format(format_name, lang=language_code)[0] |
| 1491 |
self.assertEqual( |
| 1492 |
regex.findall(formatter), |
| 1493 |
[], |
| 1494 |
"%s locale's %s uses an unsupported format code." |
| 1495 |
% (language_code, format_name), |
| 1496 |
) |
| 1497 |
|
| 1498 |
|
| 1499 |
class MiscTests(SimpleTestCase): |
| 1500 |
rf = RequestFactory() |
| 1501 |
|
| 1502 |
@override_settings(LANGUAGE_CODE="de") |
| 1503 |
def test_english_fallback(self): |
| 1504 |
""" |
| 1505 |
With a non-English LANGUAGE_CODE and if the active language is English |
| 1506 |
or one of its variants, the untranslated string should be returned |
| 1507 |
(instead of falling back to LANGUAGE_CODE) (See #24413). |
| 1508 |
""" |
| 1509 |
self.assertEqual(gettext("Image"), "Bild") |
| 1510 |
with translation.override("en"): |
| 1511 |
self.assertEqual(gettext("Image"), "Image") |
| 1512 |
with translation.override("en-us"): |
| 1513 |
self.assertEqual(gettext("Image"), "Image") |
| 1514 |
with translation.override("en-ca"): |
| 1515 |
self.assertEqual(gettext("Image"), "Image") |
| 1516 |
|
| 1517 |
def test_parse_spec_http_header(self): |
| 1518 |
""" |
| 1519 |
Testing HTTP header parsing. First, we test that we can parse the |
| 1520 |
values according to the spec (and that we extract all the pieces in |
| 1521 |
the right order). |
| 1522 |
""" |
| 1523 |
tests = [ |
| 1524 |
# Good headers |
| 1525 |
("de", [("de", 1.0)]), |
| 1526 |
("en-AU", [("en-au", 1.0)]), |
| 1527 |
("es-419", [("es-419", 1.0)]), |
| 1528 |
("*;q=1.00", [("*", 1.0)]), |
| 1529 |
("en-AU;q=0.123", [("en-au", 0.123)]), |
| 1530 |
("en-au;q=0.5", [("en-au", 0.5)]), |
| 1531 |
("en-au;q=1.0", [("en-au", 1.0)]), |
| 1532 |
("da, en-gb;q=0.25, en;q=0.5", [("da", 1.0), ("en", 0.5), ("en-gb", 0.25)]), |
| 1533 |
("en-au-xx", [("en-au-xx", 1.0)]), |
| 1534 |
( |
| 1535 |
"de,en-au;q=0.75,en-us;q=0.5,en;q=0.25,es;q=0.125,fa;q=0.125", |
| 1536 |
[ |
| 1537 |
("de", 1.0), |
| 1538 |
("en-au", 0.75), |
| 1539 |
("en-us", 0.5), |
| 1540 |
("en", 0.25), |
| 1541 |
("es", 0.125), |
| 1542 |
("fa", 0.125), |
| 1543 |
], |
| 1544 |
), |
| 1545 |
("*", [("*", 1.0)]), |
| 1546 |
("de;q=0.", [("de", 0.0)]), |
| 1547 |
("en; q=1,", [("en", 1.0)]), |
| 1548 |
("en; q=1.0, * ; q=0.5", [("en", 1.0), ("*", 0.5)]), |
| 1549 |
( |
| 1550 |
"en" + "-x" * 20, |
| 1551 |
[("en-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x", 1.0)], |
| 1552 |
), |
| 1553 |
( |
| 1554 |
", ".join(["en; q=1.0"] * 20), |
| 1555 |
[("en", 1.0)] * 20, |
| 1556 |
), |
| 1557 |
# Bad headers |
| 1558 |
("en-gb;q=1.0000", []), |
| 1559 |
("en;q=0.1234", []), |
| 1560 |
("en;q=.2", []), |
| 1561 |
("abcdefghi-au", []), |
| 1562 |
("**", []), |
| 1563 |
("en,,gb", []), |
| 1564 |
("en-au;q=0.1.0", []), |
| 1565 |
(("X" * 97) + "Z,en", []), |
| 1566 |
("da, en-gb;q=0.8, en;q=0.7,#", []), |
| 1567 |
("de;q=2.0", []), |
| 1568 |
("de;q=0.a", []), |
| 1569 |
("12-345", []), |
| 1570 |
("", []), |
| 1571 |
("en;q=1e0", []), |
| 1572 |
("en-au;q=1.0", []), |
| 1573 |
# Invalid as language-range value too long. |
| 1574 |
("xxxxxxxx" + "-xxxxxxxx" * 500, []), |
| 1575 |
# Header value too long, only parse up to limit. |
| 1576 |
(", ".join(["en; q=1.0"] * 500), [("en", 1.0)] * 45), |
| 1577 |
] |
| 1578 |
for value, expected in tests: |
| 1579 |
with self.subTest(value=value): |
| 1580 |
self.assertEqual( |
| 1581 |
trans_real.parse_accept_lang_header(value), tuple(expected) |
| 1582 |
) |
| 1583 |
|
| 1584 |
def test_parse_literal_http_header(self): |
| 1585 |
tests = [ |
| 1586 |
("pt-br", "pt-br"), |
| 1587 |
("pt", "pt"), |
| 1588 |
("es,de", "es"), |
| 1589 |
("es-a,de", "es"), |
| 1590 |
# There isn't a Django translation to a US variation of the Spanish |
| 1591 |
# language, a safe assumption. When the user sets it as the |
| 1592 |
# preferred language, the main 'es' translation should be selected |
| 1593 |
# instead. |
| 1594 |
("es-us", "es"), |
| 1595 |
# There isn't a main language (zh) translation of Django but there |
| 1596 |
# is a translation to variation (zh-hans) the user sets zh-hans as |
| 1597 |
# the preferred language, it should be selected without falling |
| 1598 |
# back nor ignoring it. |
| 1599 |
("zh-hans,de", "zh-hans"), |
| 1600 |
("NL", "nl"), |
| 1601 |
("fy", "fy"), |
| 1602 |
("ia", "ia"), |
| 1603 |
("sr-latn", "sr-latn"), |
| 1604 |
("zh-hans", "zh-hans"), |
| 1605 |
("zh-hant", "zh-hant"), |
| 1606 |
] |
| 1607 |
for header, expected in tests: |
| 1608 |
with self.subTest(header=header): |
| 1609 |
request = self.rf.get("/", headers={"accept-language": header}) |
| 1610 |
self.assertEqual(get_language_from_request(request), expected) |
| 1611 |
|
| 1612 |
@override_settings( |
| 1613 |
LANGUAGES=[ |
| 1614 |
("en", "English"), |
| 1615 |
("zh-hans", "Simplified Chinese"), |
| 1616 |
("zh-hant", "Traditional Chinese"), |
| 1617 |
] |
| 1618 |
) |
| 1619 |
def test_support_for_deprecated_chinese_language_codes(self): |
| 1620 |
""" |
| 1621 |
Some browsers (Firefox, IE, etc.) use deprecated language codes. As these |
| 1622 |
language codes will be removed in Django 1.9, these will be incorrectly |
| 1623 |
matched. For example zh-tw (traditional) will be interpreted as zh-hans |
| 1624 |
(simplified), which is wrong. So we should also accept these deprecated |
| 1625 |
language codes. |
| 1626 |
|
| 1627 |
refs #18419 -- this is explicitly for browser compatibility |
| 1628 |
""" |
| 1629 |
g = get_language_from_request |
| 1630 |
request = self.rf.get("/", headers={"accept-language": "zh-cn,en"}) |
| 1631 |
self.assertEqual(g(request), "zh-hans") |
| 1632 |
|
| 1633 |
request = self.rf.get("/", headers={"accept-language": "zh-tw,en"}) |
| 1634 |
self.assertEqual(g(request), "zh-hant") |
| 1635 |
|
| 1636 |
def test_special_fallback_language(self): |
| 1637 |
""" |
| 1638 |
Some languages may have special fallbacks that don't follow the simple |
| 1639 |
'fr-ca' -> 'fr' logic (notably Chinese codes). |
| 1640 |
""" |
| 1641 |
request = self.rf.get("/", headers={"accept-language": "zh-my,en"}) |
| 1642 |
self.assertEqual(get_language_from_request(request), "zh-hans") |
| 1643 |
|
| 1644 |
def test_subsequent_code_fallback_language(self): |
| 1645 |
""" |
| 1646 |
Subsequent language codes should be used when the language code is not |
| 1647 |
supported. |
| 1648 |
""" |
| 1649 |
tests = [ |
| 1650 |
("zh-Hans-CN", "zh-hans"), |
| 1651 |
("zh-hans-mo", "zh-hans"), |
| 1652 |
("zh-hans-HK", "zh-hans"), |
| 1653 |
("zh-Hant-HK", "zh-hant"), |
| 1654 |
("zh-hant-tw", "zh-hant"), |
| 1655 |
("zh-hant-SG", "zh-hant"), |
| 1656 |
] |
| 1657 |
for value, expected in tests: |
| 1658 |
with self.subTest(value=value): |
| 1659 |
request = self.rf.get("/", headers={"accept-language": f"{value},en"}) |
| 1660 |
self.assertEqual(get_language_from_request(request), expected) |
| 1661 |
|
| 1662 |
def test_parse_language_cookie(self): |
| 1663 |
g = get_language_from_request |
| 1664 |
request = self.rf.get("/") |
| 1665 |
request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "pt-br" |
| 1666 |
self.assertEqual("pt-br", g(request)) |
| 1667 |
|
| 1668 |
request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "pt" |
| 1669 |
self.assertEqual("pt", g(request)) |
| 1670 |
|
| 1671 |
request = self.rf.get("/", headers={"accept-language": "de"}) |
| 1672 |
request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "es" |
| 1673 |
self.assertEqual("es", g(request)) |
| 1674 |
|
| 1675 |
# There isn't a Django translation to a US variation of the Spanish |
| 1676 |
# language, a safe assumption. When the user sets it as the preferred |
| 1677 |
# language, the main 'es' translation should be selected instead. |
| 1678 |
request = self.rf.get("/") |
| 1679 |
request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "es-us" |
| 1680 |
self.assertEqual(g(request), "es") |
| 1681 |
# There isn't a main language (zh) translation of Django but there is a |
| 1682 |
# translation to variation (zh-hans) the user sets zh-hans as the |
| 1683 |
# preferred language, it should be selected without falling back nor |
| 1684 |
# ignoring it. |
| 1685 |
request = self.rf.get("/", headers={"accept-language": "de"}) |
| 1686 |
request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "zh-hans" |
| 1687 |
self.assertEqual(g(request), "zh-hans") |
| 1688 |
|
| 1689 |
@override_settings( |
| 1690 |
USE_I18N=True, |
| 1691 |
LANGUAGES=[ |
| 1692 |
("en", "English"), |
| 1693 |
("ar-dz", "Algerian Arabic"), |
| 1694 |
("de", "German"), |
| 1695 |
("de-at", "Austrian German"), |
| 1696 |
("pt-BR", "Portuguese (Brazil)"), |
| 1697 |
], |
| 1698 |
) |
| 1699 |
def test_get_supported_language_variant_real(self): |
| 1700 |
g = trans_real.get_supported_language_variant |
| 1701 |
self.assertEqual(g("en"), "en") |
| 1702 |
self.assertEqual(g("en-gb"), "en") |
| 1703 |
self.assertEqual(g("de"), "de") |
| 1704 |
self.assertEqual(g("de-at"), "de-at") |
| 1705 |
self.assertEqual(g("de-ch"), "de") |
| 1706 |
self.assertEqual(g("pt-br"), "pt-br") |
| 1707 |
self.assertEqual(g("pt-BR"), "pt-BR") |
| 1708 |
self.assertEqual(g("pt"), "pt-br") |
| 1709 |
self.assertEqual(g("pt-pt"), "pt-br") |
| 1710 |
self.assertEqual(g("ar-dz"), "ar-dz") |
| 1711 |
self.assertEqual(g("ar-DZ"), "ar-DZ") |
| 1712 |
with self.assertRaises(LookupError): |
| 1713 |
g("pt", strict=True) |
| 1714 |
with self.assertRaises(LookupError): |
| 1715 |
g("pt-pt", strict=True) |
| 1716 |
with self.assertRaises(LookupError): |
| 1717 |
g("xyz") |
| 1718 |
with self.assertRaises(LookupError): |
| 1719 |
g("xy-zz") |
| 1720 |
with self.assertRaises(LookupError): |
| 1721 |
g("x" * LANGUAGE_CODE_MAX_LENGTH) |
| 1722 |
with self.assertRaises(LookupError): |
| 1723 |
g("x" * (LANGUAGE_CODE_MAX_LENGTH + 1)) |
| 1724 |
# 167 * 3 = 501 which is LANGUAGE_CODE_MAX_LENGTH + 1. |
| 1725 |
self.assertEqual(g("en-" * 167), "en") |
| 1726 |
with self.assertRaises(LookupError): |
| 1727 |
g("en-" * 167, strict=True) |
| 1728 |
self.assertEqual(g("en-" * 30000), "en") # catastrophic test |
| 1729 |
|
| 1730 |
def test_get_supported_language_variant_null(self): |
| 1731 |
g = trans_null.get_supported_language_variant |
| 1732 |
self.assertEqual(g(settings.LANGUAGE_CODE), settings.LANGUAGE_CODE) |
| 1733 |
with self.assertRaises(LookupError): |
| 1734 |
g("pt") |
| 1735 |
with self.assertRaises(LookupError): |
| 1736 |
g("de") |
| 1737 |
with self.assertRaises(LookupError): |
| 1738 |
g("de-at") |
| 1739 |
with self.assertRaises(LookupError): |
| 1740 |
g("de", strict=True) |
| 1741 |
with self.assertRaises(LookupError): |
| 1742 |
g("de-at", strict=True) |
| 1743 |
with self.assertRaises(LookupError): |
| 1744 |
g("xyz") |
| 1745 |
|
| 1746 |
@override_settings( |
| 1747 |
LANGUAGES=[ |
| 1748 |
("en", "English"), |
| 1749 |
("en-latn-us", "Latin English"), |
| 1750 |
("de", "German"), |
| 1751 |
("de-1996", "German, orthography of 1996"), |
| 1752 |
("de-at", "Austrian German"), |
| 1753 |
("de-ch-1901", "German, Swiss variant, traditional orthography"), |
| 1754 |
("i-mingo", "Mingo"), |
| 1755 |
("kl-tunumiit", "Tunumiisiut"), |
| 1756 |
("nan-hani-tw", "Hanji"), |
| 1757 |
("pl", "Polish"), |
| 1758 |
], |
| 1759 |
) |
| 1760 |
def test_get_language_from_path_real(self): |
| 1761 |
g = trans_real.get_language_from_path |
| 1762 |
tests = [ |
| 1763 |
("/pl/", "pl"), |
| 1764 |
("/pl", "pl"), |
| 1765 |
("/xyz/", None), |
| 1766 |
("/en/", "en"), |
| 1767 |
("/en-gb/", "en"), |
| 1768 |
("/en-latn-us/", "en-latn-us"), |
| 1769 |
("/en-Latn-US/", "en-Latn-US"), |
| 1770 |
("/de/", "de"), |
| 1771 |
("/de-1996/", "de-1996"), |
| 1772 |
("/de-at/", "de-at"), |
| 1773 |
("/de-AT/", "de-AT"), |
| 1774 |
("/de-ch/", "de"), |
| 1775 |
("/de-ch-1901/", "de-ch-1901"), |
| 1776 |
("/de-simple-page-test/", None), |
| 1777 |
("/i-mingo/", "i-mingo"), |
| 1778 |
("/kl-tunumiit/", "kl-tunumiit"), |
| 1779 |
("/nan-hani-tw/", "nan-hani-tw"), |
| 1780 |
(f"/{'a' * 501}/", None), |
| 1781 |
] |
| 1782 |
for path, language in tests: |
| 1783 |
with self.subTest(path=path): |
| 1784 |
self.assertEqual(g(path), language) |
| 1785 |
|
| 1786 |
def test_get_language_from_path_null(self): |
| 1787 |
g = trans_null.get_language_from_path |
| 1788 |
self.assertIsNone(g("/pl/")) |
| 1789 |
self.assertIsNone(g("/pl")) |
| 1790 |
self.assertIsNone(g("/xyz/")) |
| 1791 |
|
| 1792 |
def test_cache_resetting(self): |
| 1793 |
""" |
| 1794 |
After setting LANGUAGE, the cache should be cleared and languages |
| 1795 |
previously valid should not be used (#14170). |
| 1796 |
""" |
| 1797 |
g = get_language_from_request |
| 1798 |
request = self.rf.get("/", headers={"accept-language": "pt-br"}) |
| 1799 |
self.assertEqual("pt-br", g(request)) |
| 1800 |
with self.settings(LANGUAGES=[("en", "English")]): |
| 1801 |
self.assertNotEqual("pt-br", g(request)) |
| 1802 |
|
| 1803 |
def test_i18n_patterns_returns_list(self): |
| 1804 |
with override_settings(USE_I18N=False): |
| 1805 |
self.assertIsInstance(i18n_patterns([]), list) |
| 1806 |
with override_settings(USE_I18N=True): |
| 1807 |
self.assertIsInstance(i18n_patterns([]), list) |
| 1808 |
|
| 1809 |
|
| 1810 |
class ResolutionOrderI18NTests(SimpleTestCase): |
| 1811 |
def setUp(self): |
| 1812 |
super().setUp() |
| 1813 |
activate("de") |
| 1814 |
self.addCleanup(deactivate) |
| 1815 |
|
| 1816 |
def assertGettext(self, msgid, msgstr): |
| 1817 |
result = gettext(msgid) |
| 1818 |
self.assertIn( |
| 1819 |
msgstr, |
| 1820 |
result, |
| 1821 |
"The string '%s' isn't in the translation of '%s'; the actual result is " |
| 1822 |
"'%s'." % (msgstr, msgid, result), |
| 1823 |
) |
| 1824 |
|
| 1825 |
|
| 1826 |
class AppResolutionOrderI18NTests(ResolutionOrderI18NTests): |
| 1827 |
@override_settings(LANGUAGE_CODE="de") |
| 1828 |
def test_app_translation(self): |
| 1829 |
# Original translation. |
| 1830 |
self.assertGettext("Date/time", "Datum/Zeit") |
| 1831 |
|
| 1832 |
# Different translation. |
| 1833 |
with self.modify_settings(INSTALLED_APPS={"append": "i18n.resolution"}): |
| 1834 |
# Force refreshing translations. |
| 1835 |
activate("de") |
| 1836 |
|
| 1837 |
# Doesn't work because it's added later in the list. |
| 1838 |
self.assertGettext("Date/time", "Datum/Zeit") |
| 1839 |
|
| 1840 |
with self.modify_settings( |
| 1841 |
INSTALLED_APPS={"remove": "django.contrib.admin.apps.SimpleAdminConfig"} |
| 1842 |
): |
| 1843 |
# Force refreshing translations. |
| 1844 |
activate("de") |
| 1845 |
|
| 1846 |
# Unless the original is removed from the list. |
| 1847 |
self.assertGettext("Date/time", "Datum/Zeit (APP)") |
| 1848 |
|
| 1849 |
|
| 1850 |
@override_settings(LOCALE_PATHS=extended_locale_paths) |
| 1851 |
class LocalePathsResolutionOrderI18NTests(ResolutionOrderI18NTests): |
| 1852 |
def test_locale_paths_translation(self): |
| 1853 |
self.assertGettext("Time", "LOCALE_PATHS") |
| 1854 |
|
| 1855 |
def test_locale_paths_override_app_translation(self): |
| 1856 |
with self.settings(INSTALLED_APPS=["i18n.resolution"]): |
| 1857 |
self.assertGettext("Time", "LOCALE_PATHS") |
| 1858 |
|
| 1859 |
|
| 1860 |
class DjangoFallbackResolutionOrderI18NTests(ResolutionOrderI18NTests): |
| 1861 |
def test_django_fallback(self): |
| 1862 |
self.assertEqual(gettext("Date/time"), "Datum/Zeit") |
| 1863 |
|
| 1864 |
|
| 1865 |
@override_settings(INSTALLED_APPS=["i18n.territorial_fallback"]) |
| 1866 |
class TranslationFallbackI18NTests(ResolutionOrderI18NTests): |
| 1867 |
def test_sparse_territory_catalog(self): |
| 1868 |
""" |
| 1869 |
Untranslated strings for territorial language variants use the |
| 1870 |
translations of the generic language. In this case, the de-de |
| 1871 |
translation falls back to de. |
| 1872 |
""" |
| 1873 |
with translation.override("de-de"): |
| 1874 |
self.assertGettext("Test 1 (en)", "(de-de)") |
| 1875 |
self.assertGettext("Test 2 (en)", "(de)") |
| 1876 |
|
| 1877 |
|
| 1878 |
class TestModels(TestCase): |
| 1879 |
def test_lazy(self): |
| 1880 |
tm = TestModel() |
| 1881 |
tm.save() |
| 1882 |
|
| 1883 |
def test_safestr(self): |
| 1884 |
c = Company(cents_paid=12, products_delivered=1) |
| 1885 |
c.name = SafeString("Iñtërnâtiônàlizætiøn1") |
| 1886 |
c.save() |
| 1887 |
|
| 1888 |
|
| 1889 |
class TestLanguageInfo(SimpleTestCase): |
| 1890 |
def test_localized_language_info(self): |
| 1891 |
li = get_language_info("de") |
| 1892 |
self.assertEqual(li["code"], "de") |
| 1893 |
self.assertEqual(li["name_local"], "Deutsch") |
| 1894 |
self.assertEqual(li["name"], "German") |
| 1895 |
self.assertIs(li["bidi"], False) |
| 1896 |
|
| 1897 |
def test_unknown_language_code(self): |
| 1898 |
with self.assertRaisesMessage(KeyError, "Unknown language code xx"): |
| 1899 |
get_language_info("xx") |
| 1900 |
with translation.override("xx"): |
| 1901 |
# A language with no translation catalogs should fallback to the |
| 1902 |
# untranslated string. |
| 1903 |
self.assertEqual(gettext("Title"), "Title") |
| 1904 |
|
| 1905 |
def test_unknown_only_country_code(self): |
| 1906 |
li = get_language_info("de-xx") |
| 1907 |
self.assertEqual(li["code"], "de") |
| 1908 |
self.assertEqual(li["name_local"], "Deutsch") |
| 1909 |
self.assertEqual(li["name"], "German") |
| 1910 |
self.assertIs(li["bidi"], False) |
| 1911 |
|
| 1912 |
def test_unknown_language_code_and_country_code(self): |
| 1913 |
with self.assertRaisesMessage(KeyError, "Unknown language code xx-xx and xx"): |
| 1914 |
get_language_info("xx-xx") |
| 1915 |
|
| 1916 |
def test_fallback_language_code(self): |
| 1917 |
""" |
| 1918 |
get_language_info return the first fallback language info if the lang_info |
| 1919 |
struct does not contain the 'name' key. |
| 1920 |
""" |
| 1921 |
li = get_language_info("zh-my") |
| 1922 |
self.assertEqual(li["code"], "zh-hans") |
| 1923 |
li = get_language_info("zh-hans") |
| 1924 |
self.assertEqual(li["code"], "zh-hans") |
| 1925 |
|
| 1926 |
|
| 1927 |
@override_settings( |
| 1928 |
USE_I18N=True, |
| 1929 |
LANGUAGES=[ |
| 1930 |
("en", "English"), |
| 1931 |
("fr", "French"), |
| 1932 |
], |
| 1933 |
MIDDLEWARE=[ |
| 1934 |
"django.middleware.locale.LocaleMiddleware", |
| 1935 |
"django.middleware.common.CommonMiddleware", |
| 1936 |
], |
| 1937 |
ROOT_URLCONF="i18n.urls", |
| 1938 |
) |
| 1939 |
class LocaleMiddlewareTests(TestCase): |
| 1940 |
def test_streaming_response(self): |
| 1941 |
# Regression test for #5241 |
| 1942 |
response = self.client.get("/fr/streaming/") |
| 1943 |
self.assertContains(response, "Oui/Non") |
| 1944 |
response = self.client.get("/en/streaming/") |
| 1945 |
self.assertContains(response, "Yes/No") |
| 1946 |
|
| 1947 |
|
| 1948 |
@override_settings( |
| 1949 |
USE_I18N=True, |
| 1950 |
LANGUAGES=[ |
| 1951 |
("en", "English"), |
| 1952 |
("de", "German"), |
| 1953 |
("fr", "French"), |
| 1954 |
], |
| 1955 |
MIDDLEWARE=[ |
| 1956 |
"django.middleware.locale.LocaleMiddleware", |
| 1957 |
"django.middleware.common.CommonMiddleware", |
| 1958 |
], |
| 1959 |
ROOT_URLCONF="i18n.urls_default_unprefixed", |
| 1960 |
LANGUAGE_CODE="en", |
| 1961 |
) |
| 1962 |
class UnprefixedDefaultLanguageTests(SimpleTestCase): |
| 1963 |
def test_default_lang_without_prefix(self): |
| 1964 |
""" |
| 1965 |
With i18n_patterns(..., prefix_default_language=False), the default |
| 1966 |
language (settings.LANGUAGE_CODE) should be accessible without a prefix. |
| 1967 |
""" |
| 1968 |
response = self.client.get("/simple/") |
| 1969 |
self.assertEqual(response.content, b"Yes") |
| 1970 |
|
| 1971 |
@override_settings(LANGUAGE_CODE="en-us") |
| 1972 |
def test_default_lang_fallback_without_prefix(self): |
| 1973 |
response = self.client.get("/simple/") |
| 1974 |
self.assertEqual(response.status_code, 200) |
| 1975 |
self.assertEqual(response.content, b"Yes") |
| 1976 |
|
| 1977 |
def test_other_lang_with_prefix(self): |
| 1978 |
response = self.client.get("/fr/simple/") |
| 1979 |
self.assertEqual(response.content, b"Oui") |
| 1980 |
|
| 1981 |
def test_unprefixed_language_other_than_accept_language(self): |
| 1982 |
response = self.client.get("/simple/", HTTP_ACCEPT_LANGUAGE="fr") |
| 1983 |
self.assertEqual(response.content, b"Yes") |
| 1984 |
|
| 1985 |
def test_page_with_dash(self): |
| 1986 |
# A page starting with /de* shouldn't match the 'de' language code. |
| 1987 |
response = self.client.get("/de-simple-page-test/") |
| 1988 |
self.assertEqual(response.content, b"Yes") |
| 1989 |
|
| 1990 |
def test_no_redirect_on_404(self): |
| 1991 |
""" |
| 1992 |
A request for a nonexistent URL shouldn't cause a redirect to |
| 1993 |
/<default_language>/<request_url> when prefix_default_language=False and |
| 1994 |
/<default_language>/<request_url> has a URL match (#27402). |
| 1995 |
""" |
| 1996 |
# A match for /group1/group2/ must exist for this to act as a |
| 1997 |
# regression test. |
| 1998 |
response = self.client.get("/group1/group2/") |
| 1999 |
self.assertEqual(response.status_code, 200) |
| 2000 |
|
| 2001 |
response = self.client.get("/nonexistent/") |
| 2002 |
self.assertEqual(response.status_code, 404) |
| 2003 |
|
| 2004 |
|
| 2005 |
@override_settings( |
| 2006 |
USE_I18N=True, |
| 2007 |
LANGUAGES=[ |
| 2008 |
("bg", "Bulgarian"), |
| 2009 |
("en-us", "English"), |
| 2010 |
("pt-br", "Portuguese (Brazil)"), |
| 2011 |
], |
| 2012 |
MIDDLEWARE=[ |
| 2013 |
"django.middleware.locale.LocaleMiddleware", |
| 2014 |
"django.middleware.common.CommonMiddleware", |
| 2015 |
], |
| 2016 |
ROOT_URLCONF="i18n.urls", |
| 2017 |
) |
| 2018 |
class CountrySpecificLanguageTests(SimpleTestCase): |
| 2019 |
rf = RequestFactory() |
| 2020 |
|
| 2021 |
def test_check_for_language(self): |
| 2022 |
self.assertTrue(check_for_language("en")) |
| 2023 |
self.assertTrue(check_for_language("en-us")) |
| 2024 |
self.assertTrue(check_for_language("en-US")) |
| 2025 |
self.assertFalse(check_for_language("en_US")) |
| 2026 |
self.assertTrue(check_for_language("be")) |
| 2027 |
self.assertTrue(check_for_language("be@latin")) |
| 2028 |
self.assertTrue(check_for_language("sr-RS@latin")) |
| 2029 |
self.assertTrue(check_for_language("sr-RS@12345")) |
| 2030 |
self.assertFalse(check_for_language("en-ü")) |
| 2031 |
self.assertFalse(check_for_language("en\x00")) |
| 2032 |
self.assertFalse(check_for_language(None)) |
| 2033 |
self.assertFalse(check_for_language("be@ ")) |
| 2034 |
# Specifying encoding is not supported (Django enforces UTF-8) |
| 2035 |
self.assertFalse(check_for_language("tr-TR.UTF-8")) |
| 2036 |
self.assertFalse(check_for_language("tr-TR.UTF8")) |
| 2037 |
self.assertFalse(check_for_language("de-DE.utf-8")) |
| 2038 |
|
| 2039 |
def test_check_for_language_null(self): |
| 2040 |
self.assertIs(trans_null.check_for_language("en"), True) |
| 2041 |
|
| 2042 |
def test_get_language_from_request(self): |
| 2043 |
# issue 19919 |
| 2044 |
request = self.rf.get( |
| 2045 |
"/", headers={"accept-language": "en-US,en;q=0.8,bg;q=0.6,ru;q=0.4"} |
| 2046 |
) |
| 2047 |
lang = get_language_from_request(request) |
| 2048 |
self.assertEqual("en-us", lang) |
| 2049 |
|
| 2050 |
request = self.rf.get( |
| 2051 |
"/", headers={"accept-language": "bg-bg,en-US;q=0.8,en;q=0.6,ru;q=0.4"} |
| 2052 |
) |
| 2053 |
lang = get_language_from_request(request) |
| 2054 |
self.assertEqual("bg", lang) |
| 2055 |
|
| 2056 |
def test_get_language_from_request_code_too_long(self): |
| 2057 |
request = self.rf.get("/", headers={"accept-language": "a" * 501}) |
| 2058 |
lang = get_language_from_request(request) |
| 2059 |
self.assertEqual("en-us", lang) |
| 2060 |
|
| 2061 |
def test_get_language_from_request_null(self): |
| 2062 |
lang = trans_null.get_language_from_request(None) |
| 2063 |
self.assertEqual(lang, "en") |
| 2064 |
with override_settings(LANGUAGE_CODE="de"): |
| 2065 |
lang = trans_null.get_language_from_request(None) |
| 2066 |
self.assertEqual(lang, "de") |
| 2067 |
|
| 2068 |
def test_specific_language_codes(self): |
| 2069 |
# issue 11915 |
| 2070 |
request = self.rf.get( |
| 2071 |
"/", headers={"accept-language": "pt,en-US;q=0.8,en;q=0.6,ru;q=0.4"} |
| 2072 |
) |
| 2073 |
lang = get_language_from_request(request) |
| 2074 |
self.assertEqual("pt-br", lang) |
| 2075 |
|
| 2076 |
request = self.rf.get( |
| 2077 |
"/", headers={"accept-language": "pt-pt,en-US;q=0.8,en;q=0.6,ru;q=0.4"} |
| 2078 |
) |
| 2079 |
lang = get_language_from_request(request) |
| 2080 |
self.assertEqual("pt-br", lang) |
| 2081 |
|
| 2082 |
|
| 2083 |
class TranslationFilesMissing(SimpleTestCase): |
| 2084 |
def setUp(self): |
| 2085 |
super().setUp() |
| 2086 |
self.gettext_find_builtin = gettext_module.find |
| 2087 |
|
| 2088 |
def tearDown(self): |
| 2089 |
gettext_module.find = self.gettext_find_builtin |
| 2090 |
super().tearDown() |
| 2091 |
|
| 2092 |
def patchGettextFind(self): |
| 2093 |
gettext_module.find = lambda *args, **kw: None |
| 2094 |
|
| 2095 |
def test_failure_finding_default_mo_files(self): |
| 2096 |
"""OSError is raised if the default language is unparseable.""" |
| 2097 |
self.patchGettextFind() |
| 2098 |
trans_real._translations = {} |
| 2099 |
with self.assertRaises(OSError): |
| 2100 |
activate("en") |
| 2101 |
|
| 2102 |
|
| 2103 |
class NonDjangoLanguageTests(SimpleTestCase): |
| 2104 |
""" |
| 2105 |
A language non present in default Django languages can still be |
| 2106 |
installed/used by a Django project. |
| 2107 |
""" |
| 2108 |
|
| 2109 |
@override_settings( |
| 2110 |
USE_I18N=True, |
| 2111 |
LANGUAGES=[ |
| 2112 |
("en-us", "English"), |
| 2113 |
("xxx", "Somelanguage"), |
| 2114 |
], |
| 2115 |
LANGUAGE_CODE="xxx", |
| 2116 |
LOCALE_PATHS=[os.path.join(here, "commands", "locale")], |
| 2117 |
) |
| 2118 |
def test_non_django_language(self): |
| 2119 |
self.assertEqual(get_language(), "xxx") |
| 2120 |
self.assertEqual(gettext("year"), "reay") |
| 2121 |
|
| 2122 |
@override_settings(USE_I18N=True) |
| 2123 |
def test_check_for_language(self): |
| 2124 |
with tempfile.TemporaryDirectory() as app_dir: |
| 2125 |
os.makedirs(os.path.join(app_dir, "locale", "dummy_Lang", "LC_MESSAGES")) |
| 2126 |
open( |
| 2127 |
os.path.join( |
| 2128 |
app_dir, "locale", "dummy_Lang", "LC_MESSAGES", "django.mo" |
| 2129 |
), |
| 2130 |
"w", |
| 2131 |
).close() |
| 2132 |
app_config = AppConfig("dummy_app", AppModuleStub(__path__=[app_dir])) |
| 2133 |
with mock.patch( |
| 2134 |
"django.apps.apps.get_app_configs", return_value=[app_config] |
| 2135 |
): |
| 2136 |
self.assertIs(check_for_language("dummy-lang"), True) |
| 2137 |
|
| 2138 |
@override_settings( |
| 2139 |
USE_I18N=True, |
| 2140 |
LANGUAGES=[ |
| 2141 |
("en-us", "English"), |
| 2142 |
# xyz language has no locale files |
| 2143 |
("xyz", "XYZ"), |
| 2144 |
], |
| 2145 |
) |
| 2146 |
@translation.override("xyz") |
| 2147 |
def test_plural_non_django_language(self): |
| 2148 |
self.assertEqual(get_language(), "xyz") |
| 2149 |
self.assertEqual(ngettext("year", "years", 2), "years") |
| 2150 |
|
| 2151 |
|
| 2152 |
@override_settings(USE_I18N=True) |
| 2153 |
class WatchForTranslationChangesTests(SimpleTestCase): |
| 2154 |
@override_settings(USE_I18N=False) |
| 2155 |
def test_i18n_disabled(self): |
| 2156 |
mocked_sender = mock.MagicMock() |
| 2157 |
watch_for_translation_changes(mocked_sender) |
| 2158 |
mocked_sender.watch_dir.assert_not_called() |
| 2159 |
|
| 2160 |
def test_i18n_enabled(self): |
| 2161 |
mocked_sender = mock.MagicMock() |
| 2162 |
watch_for_translation_changes(mocked_sender) |
| 2163 |
self.assertGreater(mocked_sender.watch_dir.call_count, 1) |
| 2164 |
|
| 2165 |
def test_i18n_locale_paths(self): |
| 2166 |
mocked_sender = mock.MagicMock() |
| 2167 |
with tempfile.TemporaryDirectory() as app_dir: |
| 2168 |
with self.settings(LOCALE_PATHS=[app_dir]): |
| 2169 |
watch_for_translation_changes(mocked_sender) |
| 2170 |
mocked_sender.watch_dir.assert_any_call(Path(app_dir), "**/*.mo") |
| 2171 |
|
| 2172 |
def test_i18n_app_dirs(self): |
| 2173 |
mocked_sender = mock.MagicMock() |
| 2174 |
with self.settings(INSTALLED_APPS=["i18n.sampleproject"]): |
| 2175 |
watch_for_translation_changes(mocked_sender) |
| 2176 |
project_dir = Path(__file__).parent / "sampleproject" / "locale" |
| 2177 |
mocked_sender.watch_dir.assert_any_call(project_dir, "**/*.mo") |
| 2178 |
|
| 2179 |
def test_i18n_app_dirs_ignore_django_apps(self): |
| 2180 |
mocked_sender = mock.MagicMock() |
| 2181 |
with self.settings(INSTALLED_APPS=["django.contrib.admin"]): |
| 2182 |
watch_for_translation_changes(mocked_sender) |
| 2183 |
mocked_sender.watch_dir.assert_called_once_with(Path("locale"), "**/*.mo") |
| 2184 |
|
| 2185 |
def test_i18n_local_locale(self): |
| 2186 |
mocked_sender = mock.MagicMock() |
| 2187 |
watch_for_translation_changes(mocked_sender) |
| 2188 |
locale_dir = Path(__file__).parent / "locale" |
| 2189 |
mocked_sender.watch_dir.assert_any_call(locale_dir, "**/*.mo") |
| 2190 |
|
| 2191 |
|
| 2192 |
class TranslationFileChangedTests(SimpleTestCase): |
| 2193 |
def setUp(self): |
| 2194 |
self.gettext_translations = gettext_module._translations.copy() |
| 2195 |
self.trans_real_translations = trans_real._translations.copy() |
| 2196 |
|
| 2197 |
def tearDown(self): |
| 2198 |
gettext._translations = self.gettext_translations |
| 2199 |
trans_real._translations = self.trans_real_translations |
| 2200 |
|
| 2201 |
def test_ignores_non_mo_files(self): |
| 2202 |
gettext_module._translations = {"foo": "bar"} |
| 2203 |
path = Path("test.py") |
| 2204 |
self.assertIsNone(translation_file_changed(None, path)) |
| 2205 |
self.assertEqual(gettext_module._translations, {"foo": "bar"}) |
| 2206 |
|
| 2207 |
def test_resets_cache_with_mo_files(self): |
| 2208 |
gettext_module._translations = {"foo": "bar"} |
| 2209 |
trans_real._translations = {"foo": "bar"} |
| 2210 |
trans_real._default = 1 |
| 2211 |
trans_real._active = False |
| 2212 |
path = Path("test.mo") |
| 2213 |
self.assertIs(translation_file_changed(None, path), True) |
| 2214 |
self.assertEqual(gettext_module._translations, {}) |
| 2215 |
self.assertEqual(trans_real._translations, {}) |
| 2216 |
self.assertIsNone(trans_real._default) |
| 2217 |
self.assertIsInstance(trans_real._active, Local) |
| 2218 |
|
| 2219 |
|
| 2220 |
class UtilsTests(SimpleTestCase): |
| 2221 |
def test_round_away_from_one(self): |
| 2222 |
tests = [ |
| 2223 |
(0, 0), |
| 2224 |
(0.0, 0), |
| 2225 |
(0.25, 0), |
| 2226 |
(0.5, 0), |
| 2227 |
(0.75, 0), |
| 2228 |
(1, 1), |
| 2229 |
(1.0, 1), |
| 2230 |
(1.25, 2), |
| 2231 |
(1.5, 2), |
| 2232 |
(1.75, 2), |
| 2233 |
(-0.0, 0), |
| 2234 |
(-0.25, -1), |
| 2235 |
(-0.5, -1), |
| 2236 |
(-0.75, -1), |
| 2237 |
(-1, -1), |
| 2238 |
(-1.0, -1), |
| 2239 |
(-1.25, -2), |
| 2240 |
(-1.5, -2), |
| 2241 |
(-1.75, -2), |
| 2242 |
] |
| 2243 |
for value, expected in tests: |
| 2244 |
with self.subTest(value=value): |
| 2245 |
self.assertEqual(round_away_from_one(value), expected) |