tests.py 72 KB

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