tests.py 63 KB

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