tests.py 72 KB

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