tests.py 76 KB

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