tests.py 73 KB

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