tests.py 63 KB

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