tests.py 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927
  1. # -*- encoding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import datetime
  4. import decimal
  5. import gettext as gettext_module
  6. import os
  7. import pickle
  8. from contextlib import contextmanager
  9. from importlib import import_module
  10. from threading import local
  11. from unittest import skipUnless
  12. from django import forms
  13. from django.conf import settings
  14. from django.conf.urls.i18n import i18n_patterns
  15. from django.template import Context, Template, TemplateSyntaxError
  16. from django.test import (
  17. RequestFactory, SimpleTestCase, TestCase, override_settings,
  18. )
  19. from django.utils import six, translation
  20. from django.utils._os import upath
  21. from django.utils.formats import (
  22. date_format, get_format, get_format_modules, iter_format_modules, localize,
  23. localize_input, reset_format_cache, sanitize_separators, time_format,
  24. )
  25. from django.utils.numberformat import format as nformat
  26. from django.utils.safestring import SafeBytes, SafeString, SafeText, mark_safe
  27. from django.utils.six import PY3
  28. from django.utils.translation import (
  29. LANGUAGE_SESSION_KEY, activate, check_for_language, deactivate,
  30. get_language, get_language_bidi, get_language_from_request,
  31. get_language_info, gettext, gettext_lazy, ngettext_lazy, npgettext,
  32. npgettext_lazy, pgettext, pgettext_lazy, string_concat, to_locale,
  33. trans_real, ugettext, ugettext_lazy, ungettext, ungettext_lazy,
  34. )
  35. from .forms import CompanyForm, I18nForm, SelectDateForm
  36. from .models import Company, TestModel
  37. here = os.path.dirname(os.path.abspath(upath(__file__)))
  38. extended_locale_paths = settings.LOCALE_PATHS + [
  39. os.path.join(here, 'other', 'locale'),
  40. ]
  41. @contextmanager
  42. def patch_formats(lang, **settings):
  43. from django.utils.formats import _format_cache
  44. # Populate _format_cache with temporary values
  45. for key, value in settings.items():
  46. _format_cache[(key, lang)] = value
  47. try:
  48. yield
  49. finally:
  50. reset_format_cache()
  51. class TranslationTests(SimpleTestCase):
  52. @translation.override('fr')
  53. def test_plural(self):
  54. """
  55. Test plurals with ungettext. French differs from English in that 0 is singular.
  56. """
  57. self.assertEqual(ungettext("%d year", "%d years", 0) % 0, "0 année")
  58. self.assertEqual(ungettext("%d year", "%d years", 2) % 2, "2 années")
  59. self.assertEqual(ungettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0}, "0 octet")
  60. self.assertEqual(ungettext("%(size)d byte", "%(size)d bytes", 2) % {'size': 2}, "2 octets")
  61. def test_override(self):
  62. activate('de')
  63. try:
  64. with translation.override('pl'):
  65. self.assertEqual(get_language(), 'pl')
  66. self.assertEqual(get_language(), 'de')
  67. with translation.override(None):
  68. self.assertEqual(get_language(), None)
  69. with translation.override('pl'):
  70. pass
  71. self.assertEqual(get_language(), None)
  72. self.assertEqual(get_language(), 'de')
  73. finally:
  74. deactivate()
  75. def test_override_decorator(self):
  76. @translation.override('pl')
  77. def func_pl():
  78. self.assertEqual(get_language(), 'pl')
  79. @translation.override(None)
  80. def func_none():
  81. self.assertEqual(get_language(), None)
  82. try:
  83. activate('de')
  84. func_pl()
  85. self.assertEqual(get_language(), 'de')
  86. func_none()
  87. self.assertEqual(get_language(), 'de')
  88. finally:
  89. deactivate()
  90. def test_override_exit(self):
  91. """
  92. Test that the language restored is the one used when the function was
  93. called, not the one used when the decorator was initialized. refs #23381
  94. """
  95. activate('fr')
  96. @translation.override('pl')
  97. def func_pl():
  98. pass
  99. deactivate()
  100. try:
  101. activate('en')
  102. func_pl()
  103. self.assertEqual(get_language(), 'en')
  104. finally:
  105. deactivate()
  106. def test_lazy_objects(self):
  107. """
  108. Format string interpolation should work with *_lazy objects.
  109. """
  110. s = ugettext_lazy('Add %(name)s')
  111. d = {'name': 'Ringo'}
  112. self.assertEqual('Add Ringo', s % d)
  113. with translation.override('de', deactivate=True):
  114. self.assertEqual('Ringo hinzuf\xfcgen', s % d)
  115. with translation.override('pl'):
  116. self.assertEqual('Dodaj Ringo', s % d)
  117. # It should be possible to compare *_lazy objects.
  118. s1 = ugettext_lazy('Add %(name)s')
  119. self.assertEqual(s, s1)
  120. s2 = gettext_lazy('Add %(name)s')
  121. s3 = gettext_lazy('Add %(name)s')
  122. self.assertEqual(s2, s3)
  123. self.assertEqual(s, s2)
  124. s4 = ugettext_lazy('Some other string')
  125. self.assertNotEqual(s, s4)
  126. @skipUnless(six.PY2, "No more bytestring translations on PY3")
  127. def test_bytestrings(self):
  128. """gettext() returns a bytestring if input is bytestring."""
  129. # Using repr() to check translated text and type
  130. self.assertEqual(repr(gettext(b"Time")), repr(b"Time"))
  131. self.assertEqual(repr(gettext("Time")), repr("Time"))
  132. with translation.override('de', deactivate=True):
  133. self.assertEqual(repr(gettext(b"Time")), repr(b"Zeit"))
  134. self.assertEqual(repr(gettext("Time")), repr(b"Zeit"))
  135. @skipUnless(six.PY2, "No more bytestring translations on PY3")
  136. def test_lazy_and_bytestrings(self):
  137. # On Python 2, (n)gettext_lazy should not transform a bytestring to unicode
  138. self.assertEqual(gettext_lazy(b"test").upper(), b"TEST")
  139. self.assertEqual((ngettext_lazy(b"%d test", b"%d tests") % 1).upper(), b"1 TEST")
  140. # Other versions of lazy functions always return unicode
  141. self.assertEqual(ugettext_lazy(b"test").upper(), "TEST")
  142. self.assertEqual((ungettext_lazy(b"%d test", b"%d tests") % 1).upper(), "1 TEST")
  143. self.assertEqual(pgettext_lazy(b"context", b"test").upper(), "TEST")
  144. self.assertEqual(
  145. (npgettext_lazy(b"context", b"%d test", b"%d tests") % 1).upper(),
  146. "1 TEST"
  147. )
  148. def test_lazy_pickle(self):
  149. s1 = ugettext_lazy("test")
  150. self.assertEqual(six.text_type(s1), "test")
  151. s2 = pickle.loads(pickle.dumps(s1))
  152. self.assertEqual(six.text_type(s2), "test")
  153. @override_settings(LOCALE_PATHS=extended_locale_paths)
  154. def test_ungettext_lazy(self):
  155. simple_with_format = ungettext_lazy('%d good result', '%d good results')
  156. simple_str_with_format = ngettext_lazy(str('%d good result'), str('%d good results'))
  157. simple_context_with_format = npgettext_lazy('Exclamation', '%d good result', '%d good results')
  158. simple_without_format = ungettext_lazy('good result', 'good results')
  159. with translation.override('de'):
  160. self.assertEqual(simple_with_format % 1, '1 gutes Resultat')
  161. self.assertEqual(simple_with_format % 4, '4 guten Resultate')
  162. self.assertEqual(simple_str_with_format % 1, str('1 gutes Resultat'))
  163. self.assertEqual(simple_str_with_format % 4, str('4 guten Resultate'))
  164. self.assertEqual(simple_context_with_format % 1, '1 gutes Resultat!')
  165. self.assertEqual(simple_context_with_format % 4, '4 guten Resultate!')
  166. self.assertEqual(simple_without_format % 1, 'gutes Resultat')
  167. self.assertEqual(simple_without_format % 4, 'guten Resultate')
  168. complex_nonlazy = ungettext_lazy('Hi %(name)s, %(num)d good result', 'Hi %(name)s, %(num)d good results', 4)
  169. complex_deferred = ungettext_lazy(
  170. 'Hi %(name)s, %(num)d good result', 'Hi %(name)s, %(num)d good results', 'num'
  171. )
  172. complex_str_nonlazy = ngettext_lazy(
  173. str('Hi %(name)s, %(num)d good result'), str('Hi %(name)s, %(num)d good results'), 4
  174. )
  175. complex_str_deferred = ngettext_lazy(
  176. str('Hi %(name)s, %(num)d good result'), str('Hi %(name)s, %(num)d good results'), 'num'
  177. )
  178. complex_context_nonlazy = npgettext_lazy(
  179. 'Greeting', 'Hi %(name)s, %(num)d good result', 'Hi %(name)s, %(num)d good results', 4
  180. )
  181. complex_context_deferred = npgettext_lazy(
  182. 'Greeting', 'Hi %(name)s, %(num)d good result', 'Hi %(name)s, %(num)d good results', 'num'
  183. )
  184. with translation.override('de'):
  185. self.assertEqual(complex_nonlazy % {'num': 4, 'name': 'Jim'}, 'Hallo Jim, 4 guten Resultate')
  186. self.assertEqual(complex_deferred % {'name': 'Jim', 'num': 1}, 'Hallo Jim, 1 gutes Resultat')
  187. self.assertEqual(complex_deferred % {'name': 'Jim', 'num': 5}, 'Hallo Jim, 5 guten Resultate')
  188. with six.assertRaisesRegex(self, KeyError, 'Your dictionary lacks key.*'):
  189. complex_deferred % {'name': 'Jim'}
  190. self.assertEqual(complex_str_nonlazy % {'num': 4, 'name': 'Jim'}, str('Hallo Jim, 4 guten Resultate'))
  191. self.assertEqual(complex_str_deferred % {'name': 'Jim', 'num': 1}, str('Hallo Jim, 1 gutes Resultat'))
  192. self.assertEqual(complex_str_deferred % {'name': 'Jim', 'num': 5}, str('Hallo Jim, 5 guten Resultate'))
  193. with six.assertRaisesRegex(self, KeyError, 'Your dictionary lacks key.*'):
  194. complex_str_deferred % {'name': 'Jim'}
  195. self.assertEqual(complex_context_nonlazy % {'num': 4, 'name': 'Jim'}, 'Willkommen Jim, 4 guten Resultate')
  196. self.assertEqual(complex_context_deferred % {'name': 'Jim', 'num': 1}, 'Willkommen Jim, 1 gutes Resultat')
  197. self.assertEqual(complex_context_deferred % {'name': 'Jim', 'num': 5}, 'Willkommen Jim, 5 guten Resultate')
  198. with six.assertRaisesRegex(self, KeyError, 'Your dictionary lacks key.*'):
  199. complex_context_deferred % {'name': 'Jim'}
  200. @skipUnless(six.PY2, "PY3 doesn't have distinct int and long types")
  201. def test_ungettext_lazy_long(self):
  202. """
  203. Regression test for #22820: int and long should be treated alike in ungettext_lazy.
  204. """
  205. result = ungettext_lazy('%(name)s has %(num)d good result', '%(name)s has %(num)d good results', 4)
  206. self.assertEqual(result % {'name': 'Joe', 'num': 4}, "Joe has 4 good results")
  207. # Now with a long
  208. result = ungettext_lazy(
  209. '%(name)s has %(num)d good result', '%(name)s has %(num)d good results',
  210. long(4) # NOQA: long undefined on PY3
  211. )
  212. self.assertEqual(result % {'name': 'Joe', 'num': 4}, "Joe has 4 good results")
  213. def test_ungettext_lazy_bool(self):
  214. self.assertTrue(ungettext_lazy('%d good result', '%d good results'))
  215. self.assertFalse(ungettext_lazy('', ''))
  216. def test_ungettext_lazy_pickle(self):
  217. s1 = ungettext_lazy('%d good result', '%d good results')
  218. self.assertEqual(s1 % 1, '1 good result')
  219. self.assertEqual(s1 % 8, '8 good results')
  220. s2 = pickle.loads(pickle.dumps(s1))
  221. self.assertEqual(s2 % 1, '1 good result')
  222. self.assertEqual(s2 % 8, '8 good results')
  223. @override_settings(LOCALE_PATHS=extended_locale_paths)
  224. def test_pgettext(self):
  225. trans_real._active = local()
  226. trans_real._translations = {}
  227. with translation.override('de'):
  228. self.assertEqual(pgettext("unexisting", "May"), "May")
  229. self.assertEqual(pgettext("month name", "May"), "Mai")
  230. self.assertEqual(pgettext("verb", "May"), "Kann")
  231. self.assertEqual(npgettext("search", "%d result", "%d results", 4) % 4, "4 Resultate")
  232. @override_settings(LOCALE_PATHS=extended_locale_paths)
  233. def test_template_tags_pgettext(self):
  234. """
  235. Ensure that message contexts are taken into account the {% trans %} and
  236. {% blocktrans %} template tags.
  237. Refs #14806.
  238. """
  239. trans_real._active = local()
  240. trans_real._translations = {}
  241. with translation.override('de'):
  242. # {% trans %} -----------------------------------
  243. # Inexisting context...
  244. t = Template('{% load i18n %}{% trans "May" context "unexisting" %}')
  245. rendered = t.render(Context())
  246. self.assertEqual(rendered, 'May')
  247. # Existing context...
  248. # Using a literal
  249. t = Template('{% load i18n %}{% trans "May" context "month name" %}')
  250. rendered = t.render(Context())
  251. self.assertEqual(rendered, 'Mai')
  252. t = Template('{% load i18n %}{% trans "May" context "verb" %}')
  253. rendered = t.render(Context())
  254. self.assertEqual(rendered, 'Kann')
  255. # Using a variable
  256. t = Template('{% load i18n %}{% trans "May" context message_context %}')
  257. rendered = t.render(Context({'message_context': 'month name'}))
  258. self.assertEqual(rendered, 'Mai')
  259. t = Template('{% load i18n %}{% trans "May" context message_context %}')
  260. rendered = t.render(Context({'message_context': 'verb'}))
  261. self.assertEqual(rendered, 'Kann')
  262. # Using a filter
  263. t = Template('{% load i18n %}{% trans "May" context message_context|lower %}')
  264. rendered = t.render(Context({'message_context': 'MONTH NAME'}))
  265. self.assertEqual(rendered, 'Mai')
  266. t = Template('{% load i18n %}{% trans "May" context message_context|lower %}')
  267. rendered = t.render(Context({'message_context': 'VERB'}))
  268. self.assertEqual(rendered, 'Kann')
  269. # Using 'as'
  270. t = Template('{% load i18n %}{% trans "May" context "month name" as var %}Value: {{ var }}')
  271. rendered = t.render(Context())
  272. self.assertEqual(rendered, 'Value: Mai')
  273. t = Template('{% load i18n %}{% trans "May" as var context "verb" %}Value: {{ var }}')
  274. rendered = t.render(Context())
  275. self.assertEqual(rendered, 'Value: Kann')
  276. # {% blocktrans %} ------------------------------
  277. # Inexisting context...
  278. t = Template('{% load i18n %}{% blocktrans context "unexisting" %}May{% endblocktrans %}')
  279. rendered = t.render(Context())
  280. self.assertEqual(rendered, 'May')
  281. # Existing context...
  282. # Using a literal
  283. t = Template('{% load i18n %}{% blocktrans context "month name" %}May{% endblocktrans %}')
  284. rendered = t.render(Context())
  285. self.assertEqual(rendered, 'Mai')
  286. t = Template('{% load i18n %}{% blocktrans context "verb" %}May{% endblocktrans %}')
  287. rendered = t.render(Context())
  288. self.assertEqual(rendered, 'Kann')
  289. # Using a variable
  290. t = Template('{% load i18n %}{% blocktrans context message_context %}May{% endblocktrans %}')
  291. rendered = t.render(Context({'message_context': 'month name'}))
  292. self.assertEqual(rendered, 'Mai')
  293. t = Template('{% load i18n %}{% blocktrans context message_context %}May{% endblocktrans %}')
  294. rendered = t.render(Context({'message_context': 'verb'}))
  295. self.assertEqual(rendered, 'Kann')
  296. # Using a filter
  297. t = Template('{% load i18n %}{% blocktrans context message_context|lower %}May{% endblocktrans %}')
  298. rendered = t.render(Context({'message_context': 'MONTH NAME'}))
  299. self.assertEqual(rendered, 'Mai')
  300. t = Template('{% load i18n %}{% blocktrans context message_context|lower %}May{% endblocktrans %}')
  301. rendered = t.render(Context({'message_context': 'VERB'}))
  302. self.assertEqual(rendered, 'Kann')
  303. # Using 'count'
  304. t = Template(
  305. '{% load i18n %}{% blocktrans count number=1 context "super search" %}'
  306. '{{ number }} super result{% plural %}{{ number }} super results{% endblocktrans %}'
  307. )
  308. rendered = t.render(Context())
  309. self.assertEqual(rendered, '1 Super-Ergebnis')
  310. t = Template(
  311. '{% load i18n %}{% blocktrans count number=2 context "super search" %}{{ number }}'
  312. ' super result{% plural %}{{ number }} super results{% endblocktrans %}'
  313. )
  314. rendered = t.render(Context())
  315. self.assertEqual(rendered, '2 Super-Ergebnisse')
  316. t = Template(
  317. '{% load i18n %}{% blocktrans context "other super search" count number=1 %}'
  318. '{{ number }} super result{% plural %}{{ number }} super results{% endblocktrans %}'
  319. )
  320. rendered = t.render(Context())
  321. self.assertEqual(rendered, '1 anderen Super-Ergebnis')
  322. t = Template(
  323. '{% load i18n %}{% blocktrans context "other super search" count number=2 %}'
  324. '{{ number }} super result{% plural %}{{ number }} super results{% endblocktrans %}'
  325. )
  326. rendered = t.render(Context())
  327. self.assertEqual(rendered, '2 andere Super-Ergebnisse')
  328. # Using 'with'
  329. t = Template(
  330. '{% load i18n %}{% blocktrans with num_comments=5 context "comment count" %}'
  331. 'There are {{ num_comments }} comments{% endblocktrans %}'
  332. )
  333. rendered = t.render(Context())
  334. self.assertEqual(rendered, 'Es gibt 5 Kommentare')
  335. t = Template(
  336. '{% load i18n %}{% blocktrans with num_comments=5 context "other comment count" %}'
  337. 'There are {{ num_comments }} comments{% endblocktrans %}'
  338. )
  339. rendered = t.render(Context())
  340. self.assertEqual(rendered, 'Andere: Es gibt 5 Kommentare')
  341. # Using trimmed
  342. t = Template(
  343. '{% load i18n %}{% blocktrans trimmed %}\n\nThere\n\t are 5 '
  344. '\n\n comments\n{% endblocktrans %}'
  345. )
  346. rendered = t.render(Context())
  347. self.assertEqual(rendered, 'There are 5 comments')
  348. t = Template(
  349. '{% load i18n %}{% blocktrans with num_comments=5 context "comment count" trimmed %}\n\n'
  350. 'There are \t\n \t {{ num_comments }} comments\n\n{% endblocktrans %}'
  351. )
  352. rendered = t.render(Context())
  353. self.assertEqual(rendered, 'Es gibt 5 Kommentare')
  354. t = Template(
  355. '{% load i18n %}{% blocktrans context "other super search" count number=2 trimmed %}\n'
  356. '{{ number }} super \n result{% plural %}{{ number }} super results{% endblocktrans %}'
  357. )
  358. rendered = t.render(Context())
  359. self.assertEqual(rendered, '2 andere Super-Ergebnisse')
  360. # Mis-uses
  361. with self.assertRaises(TemplateSyntaxError):
  362. Template('{% load i18n %}{% blocktrans context with month="May" %}{{ month }}{% endblocktrans %}')
  363. with self.assertRaises(TemplateSyntaxError):
  364. Template('{% load i18n %}{% blocktrans context %}{% endblocktrans %}')
  365. with self.assertRaises(TemplateSyntaxError):
  366. Template(
  367. '{% load i18n %}{% blocktrans count number=2 context %}'
  368. '{{ number }} super result{% plural %}{{ number }}'
  369. ' super results{% endblocktrans %}'
  370. )
  371. def test_string_concat(self):
  372. """
  373. six.text_type(string_concat(...)) should not raise a TypeError - #4796
  374. """
  375. self.assertEqual('django', six.text_type(string_concat("dja", "ngo")))
  376. def test_empty_value(self):
  377. """
  378. Empty value must stay empty after being translated (#23196).
  379. """
  380. with translation.override('de'):
  381. self.assertEqual("", ugettext(""))
  382. self.assertEqual(str(""), gettext(str("")))
  383. s = mark_safe("")
  384. self.assertEqual(s, ugettext(s))
  385. def test_safe_status(self):
  386. """
  387. Translating a string requiring no auto-escaping shouldn't change the "safe" status.
  388. """
  389. s = mark_safe(str('Password'))
  390. self.assertEqual(SafeString, type(s))
  391. with translation.override('de', deactivate=True):
  392. self.assertEqual(SafeText, type(ugettext(s)))
  393. self.assertEqual('aPassword', SafeText('a') + s)
  394. self.assertEqual('Passworda', s + SafeText('a'))
  395. self.assertEqual('Passworda', s + mark_safe('a'))
  396. self.assertEqual('aPassword', mark_safe('a') + s)
  397. self.assertEqual('as', mark_safe('a') + mark_safe('s'))
  398. def test_maclines(self):
  399. """
  400. Translations on files with mac or dos end of lines will be converted
  401. to unix eof in .po catalogs, and they have to match when retrieved
  402. """
  403. ca_translation = trans_real.translation('ca')
  404. ca_translation._catalog['Mac\nEOF\n'] = 'Catalan Mac\nEOF\n'
  405. ca_translation._catalog['Win\nEOF\n'] = 'Catalan Win\nEOF\n'
  406. with translation.override('ca', deactivate=True):
  407. self.assertEqual('Catalan Mac\nEOF\n', ugettext('Mac\rEOF\r'))
  408. self.assertEqual('Catalan Win\nEOF\n', ugettext('Win\r\nEOF\r\n'))
  409. def test_to_locale(self):
  410. """
  411. Tests the to_locale function and the special case of Serbian Latin
  412. (refs #12230 and r11299)
  413. """
  414. self.assertEqual(to_locale('en-us'), 'en_US')
  415. self.assertEqual(to_locale('sr-lat'), 'sr_Lat')
  416. def test_to_language(self):
  417. """
  418. Test the to_language function
  419. """
  420. self.assertEqual(trans_real.to_language('en_US'), 'en-us')
  421. self.assertEqual(trans_real.to_language('sr_Lat'), 'sr-lat')
  422. def test_language_bidi(self):
  423. self.assertEqual(get_language_bidi(), False)
  424. with translation.override(None):
  425. self.assertEqual(get_language_bidi(), False)
  426. @override_settings(LOCALE_PATHS=[os.path.join(here, 'other', 'locale')])
  427. def test_bad_placeholder_1(self):
  428. """
  429. Error in translation file should not crash template rendering
  430. (%(person)s is translated as %(personne)s in fr.po)
  431. Refs #16516.
  432. """
  433. with translation.override('fr'):
  434. t = Template('{% load i18n %}{% blocktrans %}My name is {{ person }}.{% endblocktrans %}')
  435. rendered = t.render(Context({'person': 'James'}))
  436. self.assertEqual(rendered, 'My name is James.')
  437. @override_settings(LOCALE_PATHS=[os.path.join(here, 'other', 'locale')])
  438. def test_bad_placeholder_2(self):
  439. """
  440. Error in translation file should not crash template rendering
  441. (%(person) misses a 's' in fr.po, causing the string formatting to fail)
  442. Refs #18393.
  443. """
  444. with translation.override('fr'):
  445. t = Template('{% load i18n %}{% blocktrans %}My other name is {{ person }}.{% endblocktrans %}')
  446. rendered = t.render(Context({'person': 'James'}))
  447. self.assertEqual(rendered, 'My other name is James.')
  448. class TranslationThreadSafetyTests(SimpleTestCase):
  449. def setUp(self):
  450. self._old_language = get_language()
  451. self._translations = trans_real._translations
  452. # here we rely on .split() being called inside the _fetch()
  453. # in trans_real.translation()
  454. class sideeffect_str(str):
  455. def split(self, *args, **kwargs):
  456. res = str.split(self, *args, **kwargs)
  457. trans_real._translations['en-YY'] = None
  458. return res
  459. trans_real._translations = {sideeffect_str('en-XX'): None}
  460. def tearDown(self):
  461. trans_real._translations = self._translations
  462. activate(self._old_language)
  463. def test_bug14894_translation_activate_thread_safety(self):
  464. translation_count = len(trans_real._translations)
  465. try:
  466. translation.activate('pl')
  467. except RuntimeError:
  468. self.fail('translation.activate() is not thread-safe')
  469. # make sure sideeffect_str actually added a new translation
  470. self.assertLess(translation_count, len(trans_real._translations))
  471. @override_settings(USE_L10N=True)
  472. class FormattingTests(SimpleTestCase):
  473. def setUp(self):
  474. super(FormattingTests, self).setUp()
  475. self.n = decimal.Decimal('66666.666')
  476. self.f = 99999.999
  477. self.d = datetime.date(2009, 12, 31)
  478. self.dt = datetime.datetime(2009, 12, 31, 20, 50)
  479. self.t = datetime.time(10, 15, 48)
  480. self.l = 10000 if PY3 else long(10000) # NOQA: long undefined on PY3
  481. self.ctxt = Context({
  482. 'n': self.n,
  483. 't': self.t,
  484. 'd': self.d,
  485. 'dt': self.dt,
  486. 'f': self.f,
  487. 'l': self.l,
  488. })
  489. def test_locale_independent(self):
  490. """
  491. Localization of numbers
  492. """
  493. with self.settings(USE_THOUSAND_SEPARATOR=False):
  494. self.assertEqual('66666.66', nformat(self.n, decimal_sep='.', decimal_pos=2, grouping=3, thousand_sep=','))
  495. self.assertEqual('66666A6', nformat(self.n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B'))
  496. self.assertEqual('66666', nformat(self.n, decimal_sep='X', decimal_pos=0, grouping=1, thousand_sep='Y'))
  497. with self.settings(USE_THOUSAND_SEPARATOR=True):
  498. self.assertEqual(
  499. '66,666.66',
  500. nformat(self.n, decimal_sep='.', decimal_pos=2, grouping=3, thousand_sep=',')
  501. )
  502. self.assertEqual(
  503. '6B6B6B6B6A6',
  504. nformat(self.n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B')
  505. )
  506. self.assertEqual('-66666.6', nformat(-66666.666, decimal_sep='.', decimal_pos=1))
  507. self.assertEqual('-66666.0', nformat(int('-66666'), decimal_sep='.', decimal_pos=1))
  508. self.assertEqual('10000.0', nformat(self.l, decimal_sep='.', decimal_pos=1))
  509. # This unusual grouping/force_grouping combination may be triggered by the intcomma filter (#17414)
  510. self.assertEqual('10000', nformat(self.l, decimal_sep='.', decimal_pos=0, grouping=0, force_grouping=True))
  511. # date filter
  512. self.assertEqual('31.12.2009 в 20:50', Template('{{ dt|date:"d.m.Y в H:i" }}').render(self.ctxt))
  513. self.assertEqual('⌚ 10:15', Template('{{ t|time:"⌚ H:i" }}').render(self.ctxt))
  514. @override_settings(USE_L10N=False)
  515. def test_l10n_disabled(self):
  516. """
  517. Catalan locale with format i18n disabled translations will be used,
  518. but not formats
  519. """
  520. with translation.override('ca', deactivate=True):
  521. self.maxDiff = 3000
  522. self.assertEqual('N j, Y', get_format('DATE_FORMAT'))
  523. self.assertEqual(0, get_format('FIRST_DAY_OF_WEEK'))
  524. self.assertEqual('.', get_format('DECIMAL_SEPARATOR'))
  525. self.assertEqual('10:15 a.m.', time_format(self.t))
  526. self.assertEqual('des. 31, 2009', date_format(self.d))
  527. self.assertEqual('desembre 2009', date_format(self.d, 'YEAR_MONTH_FORMAT'))
  528. self.assertEqual('12/31/2009 8:50 p.m.', date_format(self.dt, 'SHORT_DATETIME_FORMAT'))
  529. self.assertEqual('No localizable', localize('No localizable'))
  530. self.assertEqual('66666.666', localize(self.n))
  531. self.assertEqual('99999.999', localize(self.f))
  532. self.assertEqual('10000', localize(self.l))
  533. self.assertEqual('des. 31, 2009', localize(self.d))
  534. self.assertEqual('des. 31, 2009, 8:50 p.m.', localize(self.dt))
  535. self.assertEqual('66666.666', Template('{{ n }}').render(self.ctxt))
  536. self.assertEqual('99999.999', Template('{{ f }}').render(self.ctxt))
  537. self.assertEqual('des. 31, 2009', Template('{{ d }}').render(self.ctxt))
  538. self.assertEqual('des. 31, 2009, 8:50 p.m.', Template('{{ dt }}').render(self.ctxt))
  539. self.assertEqual('66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt))
  540. self.assertEqual('100000.0', Template('{{ f|floatformat }}').render(self.ctxt))
  541. self.assertEqual('10:15 a.m.', Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt))
  542. self.assertEqual('12/31/2009', Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt))
  543. self.assertEqual(
  544. '12/31/2009 8:50 p.m.', Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt)
  545. )
  546. form = I18nForm({
  547. 'decimal_field': '66666,666',
  548. 'float_field': '99999,999',
  549. 'date_field': '31/12/2009',
  550. 'datetime_field': '31/12/2009 20:50',
  551. 'time_field': '20:50',
  552. 'integer_field': '1.234',
  553. })
  554. self.assertFalse(form.is_valid())
  555. self.assertEqual(['Introdu\xefu un n\xfamero.'], form.errors['float_field'])
  556. self.assertEqual(['Introdu\xefu un n\xfamero.'], form.errors['decimal_field'])
  557. self.assertEqual(['Introdu\xefu una data v\xe0lida.'], form.errors['date_field'])
  558. self.assertEqual(['Introdu\xefu una data/hora v\xe0lides.'], form.errors['datetime_field'])
  559. self.assertEqual(['Introdu\xefu un n\xfamero sencer.'], form.errors['integer_field'])
  560. form2 = SelectDateForm({
  561. 'date_field_month': '12',
  562. 'date_field_day': '31',
  563. 'date_field_year': '2009'
  564. })
  565. self.assertTrue(form2.is_valid())
  566. self.assertEqual(datetime.date(2009, 12, 31), form2.cleaned_data['date_field'])
  567. self.assertHTMLEqual(
  568. '<select name="mydate_month" id="id_mydate_month">'
  569. '<option value="0">---</option>'
  570. '<option value="1">gener</option>'
  571. '<option value="2">febrer</option>'
  572. '<option value="3">mar\xe7</option>'
  573. '<option value="4">abril</option>'
  574. '<option value="5">maig</option>'
  575. '<option value="6">juny</option>'
  576. '<option value="7">juliol</option>'
  577. '<option value="8">agost</option>'
  578. '<option value="9">setembre</option>'
  579. '<option value="10">octubre</option>'
  580. '<option value="11">novembre</option>'
  581. '<option value="12" selected="selected">desembre</option>'
  582. '</select>'
  583. '<select name="mydate_day" id="id_mydate_day">'
  584. '<option value="0">---</option>'
  585. '<option value="1">1</option>'
  586. '<option value="2">2</option>'
  587. '<option value="3">3</option>'
  588. '<option value="4">4</option>'
  589. '<option value="5">5</option>'
  590. '<option value="6">6</option>'
  591. '<option value="7">7</option>'
  592. '<option value="8">8</option>'
  593. '<option value="9">9</option>'
  594. '<option value="10">10</option>'
  595. '<option value="11">11</option>'
  596. '<option value="12">12</option>'
  597. '<option value="13">13</option>'
  598. '<option value="14">14</option>'
  599. '<option value="15">15</option>'
  600. '<option value="16">16</option>'
  601. '<option value="17">17</option>'
  602. '<option value="18">18</option>'
  603. '<option value="19">19</option>'
  604. '<option value="20">20</option>'
  605. '<option value="21">21</option>'
  606. '<option value="22">22</option>'
  607. '<option value="23">23</option>'
  608. '<option value="24">24</option>'
  609. '<option value="25">25</option>'
  610. '<option value="26">26</option>'
  611. '<option value="27">27</option>'
  612. '<option value="28">28</option>'
  613. '<option value="29">29</option>'
  614. '<option value="30">30</option>'
  615. '<option value="31" selected="selected">31</option>'
  616. '</select>'
  617. '<select name="mydate_year" id="id_mydate_year">'
  618. '<option value="0">---</option>'
  619. '<option value="2009" selected="selected">2009</option>'
  620. '<option value="2010">2010</option>'
  621. '<option value="2011">2011</option>'
  622. '<option value="2012">2012</option>'
  623. '<option value="2013">2013</option>'
  624. '<option value="2014">2014</option>'
  625. '<option value="2015">2015</option>'
  626. '<option value="2016">2016</option>'
  627. '<option value="2017">2017</option>'
  628. '<option value="2018">2018</option>'
  629. '</select>',
  630. forms.SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31))
  631. )
  632. # We shouldn't change the behavior of the floatformat filter re:
  633. # thousand separator and grouping when USE_L10N is False even
  634. # if the USE_THOUSAND_SEPARATOR, NUMBER_GROUPING and
  635. # THOUSAND_SEPARATOR settings are specified
  636. with self.settings(USE_THOUSAND_SEPARATOR=True, NUMBER_GROUPING=1, THOUSAND_SEPARATOR='!'):
  637. self.assertEqual('66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt))
  638. self.assertEqual('100000.0', Template('{{ f|floatformat }}').render(self.ctxt))
  639. def test_false_like_locale_formats(self):
  640. """
  641. Ensure that the active locale's formats take precedence over the
  642. default settings even if they would be interpreted as False in a
  643. conditional test (e.g. 0 or empty string).
  644. Refs #16938.
  645. """
  646. with patch_formats('fr', THOUSAND_SEPARATOR='', FIRST_DAY_OF_WEEK=0):
  647. with translation.override('fr'):
  648. with self.settings(USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR='!'):
  649. self.assertEqual('', get_format('THOUSAND_SEPARATOR'))
  650. # Even a second time (after the format has been cached)...
  651. self.assertEqual('', get_format('THOUSAND_SEPARATOR'))
  652. with self.settings(FIRST_DAY_OF_WEEK=1):
  653. self.assertEqual(0, get_format('FIRST_DAY_OF_WEEK'))
  654. # Even a second time (after the format has been cached)...
  655. self.assertEqual(0, get_format('FIRST_DAY_OF_WEEK'))
  656. def test_l10n_enabled(self):
  657. self.maxDiff = 3000
  658. # Catalan locale
  659. with translation.override('ca', deactivate=True):
  660. self.assertEqual('j \d\e F \d\e Y', get_format('DATE_FORMAT'))
  661. self.assertEqual(1, get_format('FIRST_DAY_OF_WEEK'))
  662. self.assertEqual(',', get_format('DECIMAL_SEPARATOR'))
  663. self.assertEqual('10:15', time_format(self.t))
  664. self.assertEqual('31 de desembre de 2009', date_format(self.d))
  665. self.assertEqual('desembre del 2009', date_format(self.d, 'YEAR_MONTH_FORMAT'))
  666. self.assertEqual('31/12/2009 20:50', date_format(self.dt, 'SHORT_DATETIME_FORMAT'))
  667. self.assertEqual('No localizable', localize('No localizable'))
  668. with self.settings(USE_THOUSAND_SEPARATOR=True):
  669. self.assertEqual('66.666,666', localize(self.n))
  670. self.assertEqual('99.999,999', localize(self.f))
  671. self.assertEqual('10.000', localize(self.l))
  672. self.assertEqual('True', localize(True))
  673. with self.settings(USE_THOUSAND_SEPARATOR=False):
  674. self.assertEqual('66666,666', localize(self.n))
  675. self.assertEqual('99999,999', localize(self.f))
  676. self.assertEqual('10000', localize(self.l))
  677. self.assertEqual('31 de desembre de 2009', localize(self.d))
  678. self.assertEqual('31 de desembre de 2009 a les 20:50', localize(self.dt))
  679. with self.settings(USE_THOUSAND_SEPARATOR=True):
  680. self.assertEqual('66.666,666', Template('{{ n }}').render(self.ctxt))
  681. self.assertEqual('99.999,999', Template('{{ f }}').render(self.ctxt))
  682. self.assertEqual('10.000', Template('{{ l }}').render(self.ctxt))
  683. with self.settings(USE_THOUSAND_SEPARATOR=True):
  684. form3 = I18nForm({
  685. 'decimal_field': '66.666,666',
  686. 'float_field': '99.999,999',
  687. 'date_field': '31/12/2009',
  688. 'datetime_field': '31/12/2009 20:50',
  689. 'time_field': '20:50',
  690. 'integer_field': '1.234',
  691. })
  692. self.assertTrue(form3.is_valid())
  693. self.assertEqual(decimal.Decimal('66666.666'), form3.cleaned_data['decimal_field'])
  694. self.assertEqual(99999.999, form3.cleaned_data['float_field'])
  695. self.assertEqual(datetime.date(2009, 12, 31), form3.cleaned_data['date_field'])
  696. self.assertEqual(datetime.datetime(2009, 12, 31, 20, 50), form3.cleaned_data['datetime_field'])
  697. self.assertEqual(datetime.time(20, 50), form3.cleaned_data['time_field'])
  698. self.assertEqual(1234, form3.cleaned_data['integer_field'])
  699. with self.settings(USE_THOUSAND_SEPARATOR=False):
  700. self.assertEqual('66666,666', Template('{{ n }}').render(self.ctxt))
  701. self.assertEqual('99999,999', Template('{{ f }}').render(self.ctxt))
  702. self.assertEqual('31 de desembre de 2009', Template('{{ d }}').render(self.ctxt))
  703. self.assertEqual('31 de desembre de 2009 a les 20:50', Template('{{ dt }}').render(self.ctxt))
  704. self.assertEqual('66666,67', Template('{{ n|floatformat:2 }}').render(self.ctxt))
  705. self.assertEqual('100000,0', Template('{{ f|floatformat }}').render(self.ctxt))
  706. self.assertEqual('10:15', Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt))
  707. self.assertEqual('31/12/2009', Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt))
  708. self.assertEqual(
  709. '31/12/2009 20:50',
  710. Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt)
  711. )
  712. self.assertEqual(date_format(datetime.datetime.now(), "DATE_FORMAT"),
  713. Template('{% now "DATE_FORMAT" %}').render(self.ctxt))
  714. with self.settings(USE_THOUSAND_SEPARATOR=False):
  715. form4 = I18nForm({
  716. 'decimal_field': '66666,666',
  717. 'float_field': '99999,999',
  718. 'date_field': '31/12/2009',
  719. 'datetime_field': '31/12/2009 20:50',
  720. 'time_field': '20:50',
  721. 'integer_field': '1234',
  722. })
  723. self.assertTrue(form4.is_valid())
  724. self.assertEqual(decimal.Decimal('66666.666'), form4.cleaned_data['decimal_field'])
  725. self.assertEqual(99999.999, form4.cleaned_data['float_field'])
  726. self.assertEqual(datetime.date(2009, 12, 31), form4.cleaned_data['date_field'])
  727. self.assertEqual(datetime.datetime(2009, 12, 31, 20, 50), form4.cleaned_data['datetime_field'])
  728. self.assertEqual(datetime.time(20, 50), form4.cleaned_data['time_field'])
  729. self.assertEqual(1234, form4.cleaned_data['integer_field'])
  730. form5 = SelectDateForm({
  731. 'date_field_month': '12',
  732. 'date_field_day': '31',
  733. 'date_field_year': '2009'
  734. })
  735. self.assertTrue(form5.is_valid())
  736. self.assertEqual(datetime.date(2009, 12, 31), form5.cleaned_data['date_field'])
  737. self.assertHTMLEqual(
  738. '<select name="mydate_day" id="id_mydate_day">'
  739. '<option value="0">---</option>'
  740. '<option value="1">1</option>'
  741. '<option value="2">2</option>'
  742. '<option value="3">3</option>'
  743. '<option value="4">4</option>'
  744. '<option value="5">5</option>'
  745. '<option value="6">6</option>'
  746. '<option value="7">7</option>'
  747. '<option value="8">8</option>'
  748. '<option value="9">9</option>'
  749. '<option value="10">10</option>'
  750. '<option value="11">11</option>'
  751. '<option value="12">12</option>'
  752. '<option value="13">13</option>'
  753. '<option value="14">14</option>'
  754. '<option value="15">15</option>'
  755. '<option value="16">16</option>'
  756. '<option value="17">17</option>'
  757. '<option value="18">18</option>'
  758. '<option value="19">19</option>'
  759. '<option value="20">20</option>'
  760. '<option value="21">21</option>'
  761. '<option value="22">22</option>'
  762. '<option value="23">23</option>'
  763. '<option value="24">24</option>'
  764. '<option value="25">25</option>'
  765. '<option value="26">26</option>'
  766. '<option value="27">27</option>'
  767. '<option value="28">28</option>'
  768. '<option value="29">29</option>'
  769. '<option value="30">30</option>'
  770. '<option value="31" selected="selected">31</option>'
  771. '</select>'
  772. '<select name="mydate_month" id="id_mydate_month">'
  773. '<option value="0">---</option>'
  774. '<option value="1">gener</option>'
  775. '<option value="2">febrer</option>'
  776. '<option value="3">mar\xe7</option>'
  777. '<option value="4">abril</option>'
  778. '<option value="5">maig</option>'
  779. '<option value="6">juny</option>'
  780. '<option value="7">juliol</option>'
  781. '<option value="8">agost</option>'
  782. '<option value="9">setembre</option>'
  783. '<option value="10">octubre</option>'
  784. '<option value="11">novembre</option>'
  785. '<option value="12" selected="selected">desembre</option>'
  786. '</select>'
  787. '<select name="mydate_year" id="id_mydate_year">'
  788. '<option value="0">---</option>'
  789. '<option value="2009" selected="selected">2009</option>'
  790. '<option value="2010">2010</option>'
  791. '<option value="2011">2011</option>'
  792. '<option value="2012">2012</option>'
  793. '<option value="2013">2013</option>'
  794. '<option value="2014">2014</option>'
  795. '<option value="2015">2015</option>'
  796. '<option value="2016">2016</option>'
  797. '<option value="2017">2017</option>'
  798. '<option value="2018">2018</option>'
  799. '</select>',
  800. forms.SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31))
  801. )
  802. # Russian locale (with E as month)
  803. with translation.override('ru', deactivate=True):
  804. self.assertHTMLEqual(
  805. '<select name="mydate_day" id="id_mydate_day">'
  806. '<option value="0">---</option>'
  807. '<option value="1">1</option>'
  808. '<option value="2">2</option>'
  809. '<option value="3">3</option>'
  810. '<option value="4">4</option>'
  811. '<option value="5">5</option>'
  812. '<option value="6">6</option>'
  813. '<option value="7">7</option>'
  814. '<option value="8">8</option>'
  815. '<option value="9">9</option>'
  816. '<option value="10">10</option>'
  817. '<option value="11">11</option>'
  818. '<option value="12">12</option>'
  819. '<option value="13">13</option>'
  820. '<option value="14">14</option>'
  821. '<option value="15">15</option>'
  822. '<option value="16">16</option>'
  823. '<option value="17">17</option>'
  824. '<option value="18">18</option>'
  825. '<option value="19">19</option>'
  826. '<option value="20">20</option>'
  827. '<option value="21">21</option>'
  828. '<option value="22">22</option>'
  829. '<option value="23">23</option>'
  830. '<option value="24">24</option>'
  831. '<option value="25">25</option>'
  832. '<option value="26">26</option>'
  833. '<option value="27">27</option>'
  834. '<option value="28">28</option>'
  835. '<option value="29">29</option>'
  836. '<option value="30">30</option>'
  837. '<option value="31" selected="selected">31</option>'
  838. '</select>'
  839. '<select name="mydate_month" id="id_mydate_month">'
  840. '<option value="0">---</option>'
  841. '<option value="1">\u042f\u043d\u0432\u0430\u0440\u044c</option>'
  842. '<option value="2">\u0424\u0435\u0432\u0440\u0430\u043b\u044c</option>'
  843. '<option value="3">\u041c\u0430\u0440\u0442</option>'
  844. '<option value="4">\u0410\u043f\u0440\u0435\u043b\u044c</option>'
  845. '<option value="5">\u041c\u0430\u0439</option>'
  846. '<option value="6">\u0418\u044e\u043d\u044c</option>'
  847. '<option value="7">\u0418\u044e\u043b\u044c</option>'
  848. '<option value="8">\u0410\u0432\u0433\u0443\u0441\u0442</option>'
  849. '<option value="9">\u0421\u0435\u043d\u0442\u044f\u0431\u0440\u044c</option>'
  850. '<option value="10">\u041e\u043a\u0442\u044f\u0431\u0440\u044c</option>'
  851. '<option value="11">\u041d\u043e\u044f\u0431\u0440\u044c</option>'
  852. '<option value="12" selected="selected">\u0414\u0435\u043a\u0430\u0431\u0440\u044c</option>'
  853. '</select>'
  854. '<select name="mydate_year" id="id_mydate_year">'
  855. '<option value="0">---</option>'
  856. '<option value="2009" selected="selected">2009</option>'
  857. '<option value="2010">2010</option>'
  858. '<option value="2011">2011</option>'
  859. '<option value="2012">2012</option>'
  860. '<option value="2013">2013</option>'
  861. '<option value="2014">2014</option>'
  862. '<option value="2015">2015</option>'
  863. '<option value="2016">2016</option>'
  864. '<option value="2017">2017</option>'
  865. '<option value="2018">2018</option>'
  866. '</select>',
  867. forms.SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31))
  868. )
  869. # English locale
  870. with translation.override('en', deactivate=True):
  871. self.assertEqual('N j, Y', get_format('DATE_FORMAT'))
  872. self.assertEqual(0, get_format('FIRST_DAY_OF_WEEK'))
  873. self.assertEqual('.', get_format('DECIMAL_SEPARATOR'))
  874. self.assertEqual('Dec. 31, 2009', date_format(self.d))
  875. self.assertEqual('December 2009', date_format(self.d, 'YEAR_MONTH_FORMAT'))
  876. self.assertEqual('12/31/2009 8:50 p.m.', date_format(self.dt, 'SHORT_DATETIME_FORMAT'))
  877. self.assertEqual('No localizable', localize('No localizable'))
  878. with self.settings(USE_THOUSAND_SEPARATOR=True):
  879. self.assertEqual('66,666.666', localize(self.n))
  880. self.assertEqual('99,999.999', localize(self.f))
  881. self.assertEqual('10,000', localize(self.l))
  882. with self.settings(USE_THOUSAND_SEPARATOR=False):
  883. self.assertEqual('66666.666', localize(self.n))
  884. self.assertEqual('99999.999', localize(self.f))
  885. self.assertEqual('10000', localize(self.l))
  886. self.assertEqual('Dec. 31, 2009', localize(self.d))
  887. self.assertEqual('Dec. 31, 2009, 8:50 p.m.', localize(self.dt))
  888. with self.settings(USE_THOUSAND_SEPARATOR=True):
  889. self.assertEqual('66,666.666', Template('{{ n }}').render(self.ctxt))
  890. self.assertEqual('99,999.999', Template('{{ f }}').render(self.ctxt))
  891. self.assertEqual('10,000', Template('{{ l }}').render(self.ctxt))
  892. with self.settings(USE_THOUSAND_SEPARATOR=False):
  893. self.assertEqual('66666.666', Template('{{ n }}').render(self.ctxt))
  894. self.assertEqual('99999.999', Template('{{ f }}').render(self.ctxt))
  895. self.assertEqual('Dec. 31, 2009', Template('{{ d }}').render(self.ctxt))
  896. self.assertEqual('Dec. 31, 2009, 8:50 p.m.', Template('{{ dt }}').render(self.ctxt))
  897. self.assertEqual('66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt))
  898. self.assertEqual('100000.0', Template('{{ f|floatformat }}').render(self.ctxt))
  899. self.assertEqual('12/31/2009', Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt))
  900. self.assertEqual(
  901. '12/31/2009 8:50 p.m.',
  902. Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt)
  903. )
  904. form5 = I18nForm({
  905. 'decimal_field': '66666.666',
  906. 'float_field': '99999.999',
  907. 'date_field': '12/31/2009',
  908. 'datetime_field': '12/31/2009 20:50',
  909. 'time_field': '20:50',
  910. 'integer_field': '1234',
  911. })
  912. self.assertTrue(form5.is_valid())
  913. self.assertEqual(decimal.Decimal('66666.666'), form5.cleaned_data['decimal_field'])
  914. self.assertEqual(99999.999, form5.cleaned_data['float_field'])
  915. self.assertEqual(datetime.date(2009, 12, 31), form5.cleaned_data['date_field'])
  916. self.assertEqual(datetime.datetime(2009, 12, 31, 20, 50), form5.cleaned_data['datetime_field'])
  917. self.assertEqual(datetime.time(20, 50), form5.cleaned_data['time_field'])
  918. self.assertEqual(1234, form5.cleaned_data['integer_field'])
  919. form6 = SelectDateForm({
  920. 'date_field_month': '12',
  921. 'date_field_day': '31',
  922. 'date_field_year': '2009'
  923. })
  924. self.assertTrue(form6.is_valid())
  925. self.assertEqual(datetime.date(2009, 12, 31), form6.cleaned_data['date_field'])
  926. self.assertHTMLEqual(
  927. '<select name="mydate_month" id="id_mydate_month">'
  928. '<option value="0">---</option>'
  929. '<option value="1">January</option>'
  930. '<option value="2">February</option>'
  931. '<option value="3">March</option>'
  932. '<option value="4">April</option>'
  933. '<option value="5">May</option>'
  934. '<option value="6">June</option>'
  935. '<option value="7">July</option>'
  936. '<option value="8">August</option>'
  937. '<option value="9">September</option>'
  938. '<option value="10">October</option>'
  939. '<option value="11">November</option>'
  940. '<option value="12" selected="selected">December</option>'
  941. '</select>'
  942. '<select name="mydate_day" id="id_mydate_day">'
  943. '<option value="0">---</option>'
  944. '<option value="1">1</option>'
  945. '<option value="2">2</option>'
  946. '<option value="3">3</option>'
  947. '<option value="4">4</option>'
  948. '<option value="5">5</option>'
  949. '<option value="6">6</option>'
  950. '<option value="7">7</option>'
  951. '<option value="8">8</option>'
  952. '<option value="9">9</option>'
  953. '<option value="10">10</option>'
  954. '<option value="11">11</option>'
  955. '<option value="12">12</option>'
  956. '<option value="13">13</option>'
  957. '<option value="14">14</option>'
  958. '<option value="15">15</option>'
  959. '<option value="16">16</option>'
  960. '<option value="17">17</option>'
  961. '<option value="18">18</option>'
  962. '<option value="19">19</option>'
  963. '<option value="20">20</option>'
  964. '<option value="21">21</option>'
  965. '<option value="22">22</option>'
  966. '<option value="23">23</option>'
  967. '<option value="24">24</option>'
  968. '<option value="25">25</option>'
  969. '<option value="26">26</option>'
  970. '<option value="27">27</option>'
  971. '<option value="28">28</option>'
  972. '<option value="29">29</option>'
  973. '<option value="30">30</option>'
  974. '<option value="31" selected="selected">31</option>'
  975. '</select>'
  976. '<select name="mydate_year" id="id_mydate_year">'
  977. '<option value="0">---</option>'
  978. '<option value="2009" selected="selected">2009</option>'
  979. '<option value="2010">2010</option>'
  980. '<option value="2011">2011</option>'
  981. '<option value="2012">2012</option>'
  982. '<option value="2013">2013</option>'
  983. '<option value="2014">2014</option>'
  984. '<option value="2015">2015</option>'
  985. '<option value="2016">2016</option>'
  986. '<option value="2017">2017</option>'
  987. '<option value="2018">2018</option>'
  988. '</select>',
  989. forms.SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31))
  990. )
  991. def test_sub_locales(self):
  992. """
  993. Check if sublocales fall back to the main locale
  994. """
  995. with self.settings(USE_THOUSAND_SEPARATOR=True):
  996. with translation.override('de-at', deactivate=True):
  997. self.assertEqual('66.666,666', Template('{{ n }}').render(self.ctxt))
  998. with translation.override('es-us', deactivate=True):
  999. self.assertEqual('31 de Diciembre de 2009', date_format(self.d))
  1000. def test_localized_input(self):
  1001. """
  1002. Tests if form input is correctly localized
  1003. """
  1004. self.maxDiff = 1200
  1005. with translation.override('de-at', deactivate=True):
  1006. form6 = CompanyForm({
  1007. 'name': 'acme',
  1008. 'date_added': datetime.datetime(2009, 12, 31, 6, 0, 0),
  1009. 'cents_paid': decimal.Decimal('59.47'),
  1010. 'products_delivered': 12000,
  1011. })
  1012. self.assertTrue(form6.is_valid())
  1013. self.assertHTMLEqual(
  1014. form6.as_ul(),
  1015. '<li><label for="id_name">Name:</label>'
  1016. '<input id="id_name" type="text" name="name" value="acme" maxlength="50" required /></li>'
  1017. '<li><label for="id_date_added">Date added:</label>'
  1018. '<input type="text" name="date_added" value="31.12.2009 06:00:00" id="id_date_added" required /></li>'
  1019. '<li><label for="id_cents_paid">Cents paid:</label>'
  1020. '<input type="text" name="cents_paid" value="59,47" id="id_cents_paid" required /></li>'
  1021. '<li><label for="id_products_delivered">Products delivered:</label>'
  1022. '<input type="text" name="products_delivered" value="12000" id="id_products_delivered" required />'
  1023. '</li>'
  1024. )
  1025. self.assertEqual(localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), '31.12.2009 06:00:00')
  1026. self.assertEqual(datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data['date_added'])
  1027. with self.settings(USE_THOUSAND_SEPARATOR=True):
  1028. # Checking for the localized "products_delivered" field
  1029. self.assertInHTML(
  1030. '<input type="text" name="products_delivered" '
  1031. 'value="12.000" id="id_products_delivered" required />',
  1032. form6.as_ul()
  1033. )
  1034. def test_localized_input_func(self):
  1035. with self.settings(USE_THOUSAND_SEPARATOR=True):
  1036. self.assertEqual(localize_input(True), 'True')
  1037. def test_sanitize_separators(self):
  1038. """
  1039. Tests django.utils.formats.sanitize_separators.
  1040. """
  1041. # Non-strings are untouched
  1042. self.assertEqual(sanitize_separators(123), 123)
  1043. with translation.override('ru', deactivate=True):
  1044. # Russian locale has non-breaking space (\xa0) as thousand separator
  1045. # Check that usual space is accepted too when sanitizing inputs
  1046. with self.settings(USE_THOUSAND_SEPARATOR=True):
  1047. self.assertEqual(sanitize_separators('1\xa0234\xa0567'), '1234567')
  1048. self.assertEqual(sanitize_separators('77\xa0777,777'), '77777.777')
  1049. self.assertEqual(sanitize_separators('12 345'), '12345')
  1050. self.assertEqual(sanitize_separators('77 777,777'), '77777.777')
  1051. with self.settings(USE_THOUSAND_SEPARATOR=True, USE_L10N=False):
  1052. self.assertEqual(sanitize_separators('12\xa0345'), '12\xa0345')
  1053. with patch_formats(get_language(), THOUSAND_SEPARATOR='.', DECIMAL_SEPARATOR=','):
  1054. with self.settings(USE_THOUSAND_SEPARATOR=True):
  1055. self.assertEqual(sanitize_separators('10.234'), '10234')
  1056. # Suspicion that user entered dot as decimal separator (#22171)
  1057. self.assertEqual(sanitize_separators('10.10'), '10.10')
  1058. def test_iter_format_modules(self):
  1059. """
  1060. Tests the iter_format_modules function.
  1061. """
  1062. # Importing some format modules so that we can compare the returned
  1063. # modules with these expected modules
  1064. default_mod = import_module('django.conf.locale.de.formats')
  1065. test_mod = import_module('i18n.other.locale.de.formats')
  1066. test_mod2 = import_module('i18n.other2.locale.de.formats')
  1067. with translation.override('de-at', deactivate=True):
  1068. # Should return the correct default module when no setting is set
  1069. self.assertEqual(list(iter_format_modules('de')), [default_mod])
  1070. # When the setting is a string, should return the given module and
  1071. # the default module
  1072. self.assertEqual(
  1073. list(iter_format_modules('de', 'i18n.other.locale')),
  1074. [test_mod, default_mod])
  1075. # When setting is a list of strings, should return the given
  1076. # modules and the default module
  1077. self.assertEqual(
  1078. list(iter_format_modules('de', ['i18n.other.locale', 'i18n.other2.locale'])),
  1079. [test_mod, test_mod2, default_mod])
  1080. def test_iter_format_modules_stability(self):
  1081. """
  1082. Tests the iter_format_modules function always yields format modules in
  1083. a stable and correct order in presence of both base ll and ll_CC formats.
  1084. """
  1085. en_format_mod = import_module('django.conf.locale.en.formats')
  1086. en_gb_format_mod = import_module('django.conf.locale.en_GB.formats')
  1087. self.assertEqual(list(iter_format_modules('en-gb')), [en_gb_format_mod, en_format_mod])
  1088. def test_get_format_modules_lang(self):
  1089. with translation.override('de', deactivate=True):
  1090. self.assertEqual('.', get_format('DECIMAL_SEPARATOR', lang='en'))
  1091. def test_get_format_modules_stability(self):
  1092. with self.settings(FORMAT_MODULE_PATH='i18n.other.locale'):
  1093. with translation.override('de', deactivate=True):
  1094. old = str("%r") % get_format_modules(reverse=True)
  1095. new = str("%r") % get_format_modules(reverse=True) # second try
  1096. self.assertEqual(new, old, 'Value returned by get_formats_modules() must be preserved between calls.')
  1097. def test_localize_templatetag_and_filter(self):
  1098. """
  1099. Tests the {% localize %} templatetag
  1100. """
  1101. context = Context({'value': 3.14})
  1102. template1 = Template(
  1103. '{% load l10n %}{% localize %}{{ value }}{% endlocalize %};'
  1104. '{% localize on %}{{ value }}{% endlocalize %}'
  1105. )
  1106. template2 = Template("{% load l10n %}{{ value }};{% localize off %}{{ value }};{% endlocalize %}{{ value }}")
  1107. template3 = Template('{% load l10n %}{{ value }};{{ value|unlocalize }}')
  1108. template4 = Template('{% load l10n %}{{ value }};{{ value|localize }}')
  1109. output1 = '3,14;3,14'
  1110. output2 = '3,14;3.14;3,14'
  1111. output3 = '3,14;3.14'
  1112. output4 = '3.14;3,14'
  1113. with translation.override('de', deactivate=True):
  1114. with self.settings(USE_L10N=False):
  1115. self.assertEqual(template1.render(context), output1)
  1116. self.assertEqual(template4.render(context), output4)
  1117. with self.settings(USE_L10N=True):
  1118. self.assertEqual(template1.render(context), output1)
  1119. self.assertEqual(template2.render(context), output2)
  1120. self.assertEqual(template3.render(context), output3)
  1121. def test_localized_as_text_as_hidden_input(self):
  1122. """
  1123. Tests if form input with 'as_hidden' or 'as_text' is correctly localized. Ticket #18777
  1124. """
  1125. self.maxDiff = 1200
  1126. with translation.override('de-at', deactivate=True):
  1127. template = Template('{% load l10n %}{{ form.date_added }}; {{ form.cents_paid }}')
  1128. template_as_text = Template('{% load l10n %}{{ form.date_added.as_text }}; {{ form.cents_paid.as_text }}')
  1129. template_as_hidden = Template(
  1130. '{% load l10n %}{{ form.date_added.as_hidden }}; {{ form.cents_paid.as_hidden }}'
  1131. )
  1132. form = CompanyForm({
  1133. 'name': 'acme',
  1134. 'date_added': datetime.datetime(2009, 12, 31, 6, 0, 0),
  1135. 'cents_paid': decimal.Decimal('59.47'),
  1136. 'products_delivered': 12000,
  1137. })
  1138. context = Context({'form': form})
  1139. self.assertTrue(form.is_valid())
  1140. self.assertHTMLEqual(
  1141. template.render(context),
  1142. '<input id="id_date_added" name="date_added" type="text" value="31.12.2009 06:00:00" required />;'
  1143. '<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" required />'
  1144. )
  1145. self.assertHTMLEqual(
  1146. template_as_text.render(context),
  1147. '<input id="id_date_added" name="date_added" type="text" value="31.12.2009 06:00:00" required />;'
  1148. ' <input id="id_cents_paid" name="cents_paid" type="text" value="59,47" required />'
  1149. )
  1150. self.assertHTMLEqual(
  1151. template_as_hidden.render(context),
  1152. '<input id="id_date_added" name="date_added" type="hidden" value="31.12.2009 06:00:00" />;'
  1153. '<input id="id_cents_paid" name="cents_paid" type="hidden" value="59,47" />'
  1154. )
  1155. def test_format_arbitrary_settings(self):
  1156. self.assertEqual(get_format('DEBUG'), 'DEBUG')
  1157. def test_get_custom_format(self):
  1158. with self.settings(FORMAT_MODULE_PATH='i18n.other.locale'):
  1159. with translation.override('fr', deactivate=True):
  1160. self.assertEqual('d/m/Y CUSTOM', get_format('CUSTOM_DAY_FORMAT'))
  1161. class MiscTests(SimpleTestCase):
  1162. def setUp(self):
  1163. super(MiscTests, self).setUp()
  1164. self.rf = RequestFactory()
  1165. @override_settings(LANGUAGE_CODE='de')
  1166. def test_english_fallback(self):
  1167. """
  1168. With a non-English LANGUAGE_CODE and if the active language is English
  1169. or one of its variants, the untranslated string should be returned
  1170. (instead of falling back to LANGUAGE_CODE) (See #24413).
  1171. """
  1172. self.assertEqual(ugettext("Image"), "Bild")
  1173. with translation.override('en'):
  1174. self.assertEqual(ugettext("Image"), "Image")
  1175. with translation.override('en-us'):
  1176. self.assertEqual(ugettext("Image"), "Image")
  1177. with translation.override('en-ca'):
  1178. self.assertEqual(ugettext("Image"), "Image")
  1179. def test_parse_spec_http_header(self):
  1180. """
  1181. Testing HTTP header parsing. First, we test that we can parse the
  1182. values according to the spec (and that we extract all the pieces in
  1183. the right order).
  1184. """
  1185. p = trans_real.parse_accept_lang_header
  1186. # Good headers.
  1187. self.assertEqual([('de', 1.0)], p('de'))
  1188. self.assertEqual([('en-au', 1.0)], p('en-AU'))
  1189. self.assertEqual([('es-419', 1.0)], p('es-419'))
  1190. self.assertEqual([('*', 1.0)], p('*;q=1.00'))
  1191. self.assertEqual([('en-au', 0.123)], p('en-AU;q=0.123'))
  1192. self.assertEqual([('en-au', 0.5)], p('en-au;q=0.5'))
  1193. self.assertEqual([('en-au', 1.0)], p('en-au;q=1.0'))
  1194. self.assertEqual([('da', 1.0), ('en', 0.5), ('en-gb', 0.25)], p('da, en-gb;q=0.25, en;q=0.5'))
  1195. self.assertEqual([('en-au-xx', 1.0)], p('en-au-xx'))
  1196. self.assertEqual(
  1197. [('de', 1.0), ('en-au', 0.75), ('en-us', 0.5), ('en', 0.25), ('es', 0.125), ('fa', 0.125)],
  1198. p('de,en-au;q=0.75,en-us;q=0.5,en;q=0.25,es;q=0.125,fa;q=0.125')
  1199. )
  1200. self.assertEqual([('*', 1.0)], p('*'))
  1201. self.assertEqual([('de', 1.0)], p('de;q=0.'))
  1202. self.assertEqual([('en', 1.0), ('*', 0.5)], p('en; q=1.0, * ; q=0.5'))
  1203. self.assertEqual([], p(''))
  1204. # Bad headers; should always return [].
  1205. self.assertEqual([], p('en-gb;q=1.0000'))
  1206. self.assertEqual([], p('en;q=0.1234'))
  1207. self.assertEqual([], p('en;q=.2'))
  1208. self.assertEqual([], p('abcdefghi-au'))
  1209. self.assertEqual([], p('**'))
  1210. self.assertEqual([], p('en,,gb'))
  1211. self.assertEqual([], p('en-au;q=0.1.0'))
  1212. self.assertEqual(
  1213. [],
  1214. p('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXZ,en')
  1215. )
  1216. self.assertEqual([], p('da, en-gb;q=0.8, en;q=0.7,#'))
  1217. self.assertEqual([], p('de;q=2.0'))
  1218. self.assertEqual([], p('de;q=0.a'))
  1219. self.assertEqual([], p('12-345'))
  1220. self.assertEqual([], p(''))
  1221. self.assertEqual([], p('en; q=1,'))
  1222. def test_parse_literal_http_header(self):
  1223. """
  1224. Now test that we parse a literal HTTP header correctly.
  1225. """
  1226. g = get_language_from_request
  1227. r = self.rf.get('/')
  1228. r.COOKIES = {}
  1229. r.META = {'HTTP_ACCEPT_LANGUAGE': 'pt-br'}
  1230. self.assertEqual('pt-br', g(r))
  1231. r.META = {'HTTP_ACCEPT_LANGUAGE': 'pt'}
  1232. self.assertEqual('pt', g(r))
  1233. r.META = {'HTTP_ACCEPT_LANGUAGE': 'es,de'}
  1234. self.assertEqual('es', g(r))
  1235. r.META = {'HTTP_ACCEPT_LANGUAGE': 'es-ar,de'}
  1236. self.assertEqual('es-ar', g(r))
  1237. # This test assumes there won't be a Django translation to a US
  1238. # variation of the Spanish language, a safe assumption. When the
  1239. # user sets it as the preferred language, the main 'es'
  1240. # translation should be selected instead.
  1241. r.META = {'HTTP_ACCEPT_LANGUAGE': 'es-us'}
  1242. self.assertEqual(g(r), 'es')
  1243. # This tests the following scenario: there isn't a main language (zh)
  1244. # translation of Django but there is a translation to variation (zh-hans)
  1245. # the user sets zh-hans as the preferred language, it should be selected
  1246. # by Django without falling back nor ignoring it.
  1247. r.META = {'HTTP_ACCEPT_LANGUAGE': 'zh-hans,de'}
  1248. self.assertEqual(g(r), 'zh-hans')
  1249. r.META = {'HTTP_ACCEPT_LANGUAGE': 'NL'}
  1250. self.assertEqual('nl', g(r))
  1251. r.META = {'HTTP_ACCEPT_LANGUAGE': 'fy'}
  1252. self.assertEqual('fy', g(r))
  1253. r.META = {'HTTP_ACCEPT_LANGUAGE': 'ia'}
  1254. self.assertEqual('ia', g(r))
  1255. r.META = {'HTTP_ACCEPT_LANGUAGE': 'sr-latn'}
  1256. self.assertEqual('sr-latn', g(r))
  1257. r.META = {'HTTP_ACCEPT_LANGUAGE': 'zh-hans'}
  1258. self.assertEqual('zh-hans', g(r))
  1259. r.META = {'HTTP_ACCEPT_LANGUAGE': 'zh-hant'}
  1260. self.assertEqual('zh-hant', g(r))
  1261. @override_settings(
  1262. LANGUAGES=[
  1263. ('en', 'English'),
  1264. ('zh-hans', 'Simplified Chinese'),
  1265. ('zh-hant', 'Traditional Chinese'),
  1266. ]
  1267. )
  1268. def test_support_for_deprecated_chinese_language_codes(self):
  1269. """
  1270. Some browsers (Firefox, IE, etc.) use deprecated language codes. As these
  1271. language codes will be removed in Django 1.9, these will be incorrectly
  1272. matched. For example zh-tw (traditional) will be interpreted as zh-hans
  1273. (simplified), which is wrong. So we should also accept these deprecated
  1274. language codes.
  1275. refs #18419 -- this is explicitly for browser compatibility
  1276. """
  1277. g = get_language_from_request
  1278. r = self.rf.get('/')
  1279. r.COOKIES = {}
  1280. r.META = {'HTTP_ACCEPT_LANGUAGE': 'zh-cn,en'}
  1281. self.assertEqual(g(r), 'zh-hans')
  1282. r.META = {'HTTP_ACCEPT_LANGUAGE': 'zh-tw,en'}
  1283. self.assertEqual(g(r), 'zh-hant')
  1284. def test_special_fallback_language(self):
  1285. """
  1286. Some languages may have special fallbacks that don't follow the simple
  1287. 'fr-ca' -> 'fr' logic (notably Chinese codes).
  1288. """
  1289. r = self.rf.get('/')
  1290. r.COOKIES = {}
  1291. r.META = {'HTTP_ACCEPT_LANGUAGE': 'zh-my,en'}
  1292. self.assertEqual(get_language_from_request(r), 'zh-hans')
  1293. def test_parse_language_cookie(self):
  1294. """
  1295. Now test that we parse language preferences stored in a cookie correctly.
  1296. """
  1297. g = get_language_from_request
  1298. r = self.rf.get('/')
  1299. r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'pt-br'}
  1300. r.META = {}
  1301. self.assertEqual('pt-br', g(r))
  1302. r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'pt'}
  1303. r.META = {}
  1304. self.assertEqual('pt', g(r))
  1305. r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'es'}
  1306. r.META = {'HTTP_ACCEPT_LANGUAGE': 'de'}
  1307. self.assertEqual('es', g(r))
  1308. # This test assumes there won't be a Django translation to a US
  1309. # variation of the Spanish language, a safe assumption. When the
  1310. # user sets it as the preferred language, the main 'es'
  1311. # translation should be selected instead.
  1312. r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'es-us'}
  1313. r.META = {}
  1314. self.assertEqual(g(r), 'es')
  1315. # This tests the following scenario: there isn't a main language (zh)
  1316. # translation of Django but there is a translation to variation (zh-hans)
  1317. # the user sets zh-hans as the preferred language, it should be selected
  1318. # by Django without falling back nor ignoring it.
  1319. r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'zh-hans'}
  1320. r.META = {'HTTP_ACCEPT_LANGUAGE': 'de'}
  1321. self.assertEqual(g(r), 'zh-hans')
  1322. def test_get_language_from_path_real(self):
  1323. g = trans_real.get_language_from_path
  1324. self.assertEqual(g('/pl/'), 'pl')
  1325. self.assertEqual(g('/pl'), 'pl')
  1326. self.assertEqual(g('/xyz/'), None)
  1327. def test_get_language_from_path_null(self):
  1328. from django.utils.translation.trans_null import get_language_from_path as g
  1329. self.assertEqual(g('/pl/'), None)
  1330. self.assertEqual(g('/pl'), None)
  1331. self.assertEqual(g('/xyz/'), None)
  1332. @override_settings(LOCALE_PATHS=extended_locale_paths)
  1333. def test_percent_in_translatable_block(self):
  1334. t_sing = Template("{% load i18n %}{% blocktrans %}The result was {{ percent }}%{% endblocktrans %}")
  1335. t_plur = Template(
  1336. "{% load i18n %}{% blocktrans count num as number %}"
  1337. "{{ percent }}% represents {{ num }} object{% plural %}"
  1338. "{{ percent }}% represents {{ num }} objects{% endblocktrans %}"
  1339. )
  1340. with translation.override('de'):
  1341. self.assertEqual(t_sing.render(Context({'percent': 42})), 'Das Ergebnis war 42%')
  1342. self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 1})), '42% stellt 1 Objekt dar')
  1343. self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 4})), '42% stellt 4 Objekte dar')
  1344. @override_settings(LOCALE_PATHS=extended_locale_paths)
  1345. def test_percent_formatting_in_blocktrans(self):
  1346. """
  1347. Test that using Python's %-formatting is properly escaped in blocktrans,
  1348. singular or plural
  1349. """
  1350. t_sing = Template("{% load i18n %}{% blocktrans %}There are %(num_comments)s comments{% endblocktrans %}")
  1351. t_plur = Template(
  1352. "{% load i18n %}{% blocktrans count num as number %}"
  1353. "%(percent)s% represents {{ num }} object{% plural %}"
  1354. "%(percent)s% represents {{ num }} objects{% endblocktrans %}"
  1355. )
  1356. with translation.override('de'):
  1357. # Strings won't get translated as they don't match after escaping %
  1358. self.assertEqual(t_sing.render(Context({'num_comments': 42})), 'There are %(num_comments)s comments')
  1359. self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 1})), '%(percent)s% represents 1 object')
  1360. self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 4})), '%(percent)s% represents 4 objects')
  1361. def test_cache_resetting(self):
  1362. """
  1363. #14170 after setting LANGUAGE, cache should be cleared and languages
  1364. previously valid should not be used.
  1365. """
  1366. g = get_language_from_request
  1367. r = self.rf.get('/')
  1368. r.COOKIES = {}
  1369. r.META = {'HTTP_ACCEPT_LANGUAGE': 'pt-br'}
  1370. self.assertEqual('pt-br', g(r))
  1371. with self.settings(LANGUAGES=[('en', 'English')]):
  1372. self.assertNotEqual('pt-br', g(r))
  1373. class ResolutionOrderI18NTests(SimpleTestCase):
  1374. def setUp(self):
  1375. super(ResolutionOrderI18NTests, self).setUp()
  1376. activate('de')
  1377. def tearDown(self):
  1378. deactivate()
  1379. super(ResolutionOrderI18NTests, self).tearDown()
  1380. def assertUgettext(self, msgid, msgstr):
  1381. result = ugettext(msgid)
  1382. self.assertIn(
  1383. msgstr, result,
  1384. "The string '%s' isn't in the translation of '%s'; the actual result is '%s'."
  1385. % (msgstr, msgid, result)
  1386. )
  1387. class AppResolutionOrderI18NTests(ResolutionOrderI18NTests):
  1388. @override_settings(LANGUAGE_CODE='de')
  1389. def test_app_translation(self):
  1390. # Original translation.
  1391. self.assertUgettext('Date/time', 'Datum/Zeit')
  1392. # Different translation.
  1393. with self.modify_settings(INSTALLED_APPS={'append': 'i18n.resolution'}):
  1394. # Force refreshing translations.
  1395. activate('de')
  1396. # Doesn't work because it's added later in the list.
  1397. self.assertUgettext('Date/time', 'Datum/Zeit')
  1398. with self.modify_settings(INSTALLED_APPS={'remove': 'django.contrib.admin.apps.SimpleAdminConfig'}):
  1399. # Force refreshing translations.
  1400. activate('de')
  1401. # Unless the original is removed from the list.
  1402. self.assertUgettext('Date/time', 'Datum/Zeit (APP)')
  1403. @override_settings(LOCALE_PATHS=extended_locale_paths)
  1404. class LocalePathsResolutionOrderI18NTests(ResolutionOrderI18NTests):
  1405. def test_locale_paths_translation(self):
  1406. self.assertUgettext('Time', 'LOCALE_PATHS')
  1407. def test_locale_paths_override_app_translation(self):
  1408. with self.settings(INSTALLED_APPS=['i18n.resolution']):
  1409. self.assertUgettext('Time', 'LOCALE_PATHS')
  1410. class DjangoFallbackResolutionOrderI18NTests(ResolutionOrderI18NTests):
  1411. def test_django_fallback(self):
  1412. self.assertEqual(ugettext('Date/time'), 'Datum/Zeit')
  1413. class TestModels(TestCase):
  1414. def test_lazy(self):
  1415. tm = TestModel()
  1416. tm.save()
  1417. def test_safestr(self):
  1418. c = Company(cents_paid=12, products_delivered=1)
  1419. c.name = SafeText('Iñtërnâtiônàlizætiøn1')
  1420. c.save()
  1421. c.name = SafeBytes('Iñtërnâtiônàlizætiøn1'.encode('utf-8'))
  1422. c.save()
  1423. class TestLanguageInfo(SimpleTestCase):
  1424. def test_localized_language_info(self):
  1425. li = get_language_info('de')
  1426. self.assertEqual(li['code'], 'de')
  1427. self.assertEqual(li['name_local'], 'Deutsch')
  1428. self.assertEqual(li['name'], 'German')
  1429. self.assertEqual(li['bidi'], False)
  1430. def test_unknown_language_code(self):
  1431. six.assertRaisesRegex(self, KeyError, r"Unknown language code xx\.", get_language_info, 'xx')
  1432. with translation.override('xx'):
  1433. # A language with no translation catalogs should fallback to the
  1434. # untranslated string.
  1435. self.assertEqual(ugettext("Title"), "Title")
  1436. def test_unknown_only_country_code(self):
  1437. li = get_language_info('de-xx')
  1438. self.assertEqual(li['code'], 'de')
  1439. self.assertEqual(li['name_local'], 'Deutsch')
  1440. self.assertEqual(li['name'], 'German')
  1441. self.assertEqual(li['bidi'], False)
  1442. def test_unknown_language_code_and_country_code(self):
  1443. six.assertRaisesRegex(self, KeyError, r"Unknown language code xx-xx and xx\.", get_language_info, 'xx-xx')
  1444. def test_fallback_language_code(self):
  1445. """
  1446. get_language_info return the first fallback language info if the lang_info
  1447. struct does not contain the 'name' key.
  1448. """
  1449. li = get_language_info('zh-my')
  1450. self.assertEqual(li['code'], 'zh-hans')
  1451. li = get_language_info('zh-hans')
  1452. self.assertEqual(li['code'], 'zh-hans')
  1453. class MultipleLocaleActivationTests(SimpleTestCase):
  1454. """
  1455. Tests for template rendering behavior when multiple locales are activated
  1456. during the lifetime of the same process.
  1457. """
  1458. def setUp(self):
  1459. super(MultipleLocaleActivationTests, self).setUp()
  1460. self._old_language = get_language()
  1461. def tearDown(self):
  1462. super(MultipleLocaleActivationTests, self).tearDown()
  1463. activate(self._old_language)
  1464. def test_single_locale_activation(self):
  1465. """
  1466. Simple baseline behavior with one locale for all the supported i18n constructs.
  1467. """
  1468. with translation.override('fr'):
  1469. self.assertEqual(Template("{{ _('Yes') }}").render(Context({})), 'Oui')
  1470. self.assertEqual(Template("{% load i18n %}{% trans 'Yes' %}").render(Context({})), 'Oui')
  1471. self.assertEqual(
  1472. Template("{% load i18n %}{% blocktrans %}Yes{% endblocktrans %}").render(Context({})),
  1473. 'Oui'
  1474. )
  1475. # Literal marked up with _() in a filter expression
  1476. def test_multiple_locale_filter(self):
  1477. with translation.override('de'):
  1478. t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}")
  1479. with translation.override(self._old_language), translation.override('nl'):
  1480. self.assertEqual(t.render(Context({})), 'nee')
  1481. def test_multiple_locale_filter_deactivate(self):
  1482. with translation.override('de', deactivate=True):
  1483. t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}")
  1484. with translation.override('nl'):
  1485. self.assertEqual(t.render(Context({})), 'nee')
  1486. def test_multiple_locale_filter_direct_switch(self):
  1487. with translation.override('de'):
  1488. t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}")
  1489. with translation.override('nl'):
  1490. self.assertEqual(t.render(Context({})), 'nee')
  1491. # Literal marked up with _()
  1492. def test_multiple_locale(self):
  1493. with translation.override('de'):
  1494. t = Template("{{ _('No') }}")
  1495. with translation.override(self._old_language), translation.override('nl'):
  1496. self.assertEqual(t.render(Context({})), 'Nee')
  1497. def test_multiple_locale_deactivate(self):
  1498. with translation.override('de', deactivate=True):
  1499. t = Template("{{ _('No') }}")
  1500. with translation.override('nl'):
  1501. self.assertEqual(t.render(Context({})), 'Nee')
  1502. def test_multiple_locale_direct_switch(self):
  1503. with translation.override('de'):
  1504. t = Template("{{ _('No') }}")
  1505. with translation.override('nl'):
  1506. self.assertEqual(t.render(Context({})), 'Nee')
  1507. # Literal marked up with _(), loading the i18n template tag library
  1508. def test_multiple_locale_loadi18n(self):
  1509. with translation.override('de'):
  1510. t = Template("{% load i18n %}{{ _('No') }}")
  1511. with translation.override(self._old_language), translation.override('nl'):
  1512. self.assertEqual(t.render(Context({})), 'Nee')
  1513. def test_multiple_locale_loadi18n_deactivate(self):
  1514. with translation.override('de', deactivate=True):
  1515. t = Template("{% load i18n %}{{ _('No') }}")
  1516. with translation.override('nl'):
  1517. self.assertEqual(t.render(Context({})), 'Nee')
  1518. def test_multiple_locale_loadi18n_direct_switch(self):
  1519. with translation.override('de'):
  1520. t = Template("{% load i18n %}{{ _('No') }}")
  1521. with translation.override('nl'):
  1522. self.assertEqual(t.render(Context({})), 'Nee')
  1523. # trans i18n tag
  1524. def test_multiple_locale_trans(self):
  1525. with translation.override('de'):
  1526. t = Template("{% load i18n %}{% trans 'No' %}")
  1527. with translation.override(self._old_language), translation.override('nl'):
  1528. self.assertEqual(t.render(Context({})), 'Nee')
  1529. def test_multiple_locale_deactivate_trans(self):
  1530. with translation.override('de', deactivate=True):
  1531. t = Template("{% load i18n %}{% trans 'No' %}")
  1532. with translation.override('nl'):
  1533. self.assertEqual(t.render(Context({})), 'Nee')
  1534. def test_multiple_locale_direct_switch_trans(self):
  1535. with translation.override('de'):
  1536. t = Template("{% load i18n %}{% trans 'No' %}")
  1537. with translation.override('nl'):
  1538. self.assertEqual(t.render(Context({})), 'Nee')
  1539. # blocktrans i18n tag
  1540. def test_multiple_locale_btrans(self):
  1541. with translation.override('de'):
  1542. t = Template("{% load i18n %}{% blocktrans %}No{% endblocktrans %}")
  1543. with translation.override(self._old_language), translation.override('nl'):
  1544. self.assertEqual(t.render(Context({})), 'Nee')
  1545. def test_multiple_locale_deactivate_btrans(self):
  1546. with translation.override('de', deactivate=True):
  1547. t = Template("{% load i18n %}{% blocktrans %}No{% endblocktrans %}")
  1548. with translation.override('nl'):
  1549. self.assertEqual(t.render(Context({})), 'Nee')
  1550. def test_multiple_locale_direct_switch_btrans(self):
  1551. with translation.override('de'):
  1552. t = Template("{% load i18n %}{% blocktrans %}No{% endblocktrans %}")
  1553. with translation.override('nl'):
  1554. self.assertEqual(t.render(Context({})), 'Nee')
  1555. @override_settings(
  1556. USE_I18N=True,
  1557. LANGUAGES=[
  1558. ('en', 'English'),
  1559. ('fr', 'French'),
  1560. ],
  1561. MIDDLEWARE_CLASSES=[
  1562. 'django.middleware.locale.LocaleMiddleware',
  1563. 'django.middleware.common.CommonMiddleware',
  1564. ],
  1565. ROOT_URLCONF='i18n.urls',
  1566. )
  1567. class LocaleMiddlewareTests(TestCase):
  1568. def test_streaming_response(self):
  1569. # Regression test for #5241
  1570. response = self.client.get('/fr/streaming/')
  1571. self.assertContains(response, "Oui/Non")
  1572. response = self.client.get('/en/streaming/')
  1573. self.assertContains(response, "Yes/No")
  1574. @override_settings(
  1575. MIDDLEWARE_CLASSES=[
  1576. 'django.contrib.sessions.middleware.SessionMiddleware',
  1577. 'django.middleware.locale.LocaleMiddleware',
  1578. 'django.middleware.common.CommonMiddleware',
  1579. ],
  1580. )
  1581. def test_language_not_saved_to_session(self):
  1582. """Checks that current language is not automatically saved to
  1583. session on every request."""
  1584. # Regression test for #21473
  1585. self.client.get('/fr/simple/')
  1586. self.assertNotIn(LANGUAGE_SESSION_KEY, self.client.session)
  1587. @override_settings(
  1588. USE_I18N=True,
  1589. LANGUAGES=[
  1590. ('en', 'English'),
  1591. ('fr', 'French'),
  1592. ],
  1593. MIDDLEWARE_CLASSES=[
  1594. 'django.middleware.locale.LocaleMiddleware',
  1595. 'django.middleware.common.CommonMiddleware',
  1596. ],
  1597. ROOT_URLCONF='i18n.urls_default_unprefixed',
  1598. LANGUAGE_CODE='en',
  1599. )
  1600. class UnprefixedDefaultLanguageTests(SimpleTestCase):
  1601. def test_default_lang_without_prefix(self):
  1602. """
  1603. With i18n_patterns(..., prefix_default_language=False), the default
  1604. language (settings.LANGUAGE_CODE) should be accessible without a prefix.
  1605. """
  1606. response = self.client.get('/simple/')
  1607. self.assertEqual(response.content, b'Yes')
  1608. def test_other_lang_with_prefix(self):
  1609. response = self.client.get('/fr/simple/')
  1610. self.assertEqual(response.content, b'Oui')
  1611. def test_unprefixed_language_other_than_accept_language(self):
  1612. response = self.client.get('/simple/', HTTP_ACCEPT_LANGUAGE='fr')
  1613. self.assertEqual(response.content, b'Yes')
  1614. def test_unexpected_kwarg_to_i18n_patterns(self):
  1615. with self.assertRaisesMessage(AssertionError, "Unexpected kwargs for i18n_patterns(): {'foo':"):
  1616. i18n_patterns(object(), foo='bar')
  1617. @override_settings(
  1618. USE_I18N=True,
  1619. LANGUAGES=[
  1620. ('bg', 'Bulgarian'),
  1621. ('en-us', 'English'),
  1622. ('pt-br', 'Portuguese (Brazil)'),
  1623. ],
  1624. MIDDLEWARE_CLASSES=[
  1625. 'django.middleware.locale.LocaleMiddleware',
  1626. 'django.middleware.common.CommonMiddleware',
  1627. ],
  1628. ROOT_URLCONF='i18n.urls'
  1629. )
  1630. class CountrySpecificLanguageTests(SimpleTestCase):
  1631. def setUp(self):
  1632. super(CountrySpecificLanguageTests, self).setUp()
  1633. self.rf = RequestFactory()
  1634. def test_check_for_language(self):
  1635. self.assertTrue(check_for_language('en'))
  1636. self.assertTrue(check_for_language('en-us'))
  1637. self.assertTrue(check_for_language('en-US'))
  1638. self.assertTrue(check_for_language('be'))
  1639. self.assertTrue(check_for_language('be@latin'))
  1640. self.assertTrue(check_for_language('sr-RS@latin'))
  1641. self.assertTrue(check_for_language('sr-RS@12345'))
  1642. self.assertFalse(check_for_language('en-ü'))
  1643. self.assertFalse(check_for_language('en\x00'))
  1644. self.assertFalse(check_for_language(None))
  1645. self.assertFalse(check_for_language('be@ '))
  1646. # Specifying encoding is not supported (Django enforces UTF-8)
  1647. self.assertFalse(check_for_language('tr-TR.UTF-8'))
  1648. self.assertFalse(check_for_language('tr-TR.UTF8'))
  1649. self.assertFalse(check_for_language('de-DE.utf-8'))
  1650. def test_get_language_from_request(self):
  1651. # issue 19919
  1652. r = self.rf.get('/')
  1653. r.COOKIES = {}
  1654. r.META = {'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8,bg;q=0.6,ru;q=0.4'}
  1655. lang = get_language_from_request(r)
  1656. self.assertEqual('en-us', lang)
  1657. r = self.rf.get('/')
  1658. r.COOKIES = {}
  1659. r.META = {'HTTP_ACCEPT_LANGUAGE': 'bg-bg,en-US;q=0.8,en;q=0.6,ru;q=0.4'}
  1660. lang = get_language_from_request(r)
  1661. self.assertEqual('bg', lang)
  1662. def test_specific_language_codes(self):
  1663. # issue 11915
  1664. r = self.rf.get('/')
  1665. r.COOKIES = {}
  1666. r.META = {'HTTP_ACCEPT_LANGUAGE': 'pt,en-US;q=0.8,en;q=0.6,ru;q=0.4'}
  1667. lang = get_language_from_request(r)
  1668. self.assertEqual('pt-br', lang)
  1669. r = self.rf.get('/')
  1670. r.COOKIES = {}
  1671. r.META = {'HTTP_ACCEPT_LANGUAGE': 'pt-pt,en-US;q=0.8,en;q=0.6,ru;q=0.4'}
  1672. lang = get_language_from_request(r)
  1673. self.assertEqual('pt-br', lang)
  1674. class TranslationFilesMissing(SimpleTestCase):
  1675. def setUp(self):
  1676. super(TranslationFilesMissing, self).setUp()
  1677. self.gettext_find_builtin = gettext_module.find
  1678. def tearDown(self):
  1679. gettext_module.find = self.gettext_find_builtin
  1680. super(TranslationFilesMissing, self).tearDown()
  1681. def patchGettextFind(self):
  1682. gettext_module.find = lambda *args, **kw: None
  1683. def test_failure_finding_default_mo_files(self):
  1684. '''
  1685. Ensure IOError is raised if the default language is unparseable.
  1686. Refs: #18192
  1687. '''
  1688. self.patchGettextFind()
  1689. trans_real._translations = {}
  1690. with self.assertRaises(IOError):
  1691. activate('en')
  1692. class NonDjangoLanguageTests(SimpleTestCase):
  1693. """
  1694. A language non present in default Django languages can still be
  1695. installed/used by a Django project.
  1696. """
  1697. @override_settings(
  1698. USE_I18N=True,
  1699. LANGUAGES=[
  1700. ('en-us', 'English'),
  1701. ('xxx', 'Somelanguage'),
  1702. ],
  1703. LANGUAGE_CODE='xxx',
  1704. LOCALE_PATHS=[os.path.join(here, 'commands', 'locale')],
  1705. )
  1706. def test_non_django_language(self):
  1707. self.assertEqual(get_language(), 'xxx')
  1708. self.assertEqual(ugettext("year"), "reay")