tests.py 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204
  1. import datetime
  2. import decimal
  3. import gettext as gettext_module
  4. import os
  5. import pickle
  6. import re
  7. import tempfile
  8. from contextlib import contextmanager
  9. from importlib import import_module
  10. from pathlib import Path
  11. from unittest import mock
  12. from asgiref.local import Local
  13. from django import forms
  14. from django.apps import AppConfig
  15. from django.conf import settings
  16. from django.conf.locale import LANG_INFO
  17. from django.conf.urls.i18n import i18n_patterns
  18. from django.template import Context, Template
  19. from django.test import RequestFactory, SimpleTestCase, TestCase, override_settings
  20. from django.utils import translation
  21. from django.utils.formats import (
  22. date_format,
  23. get_format,
  24. iter_format_modules,
  25. localize,
  26. localize_input,
  27. reset_format_cache,
  28. sanitize_separators,
  29. sanitize_strftime_format,
  30. time_format,
  31. )
  32. from django.utils.numberformat import format as nformat
  33. from django.utils.safestring import SafeString, mark_safe
  34. from django.utils.translation import (
  35. activate,
  36. check_for_language,
  37. deactivate,
  38. get_language,
  39. get_language_bidi,
  40. get_language_from_request,
  41. get_language_info,
  42. gettext,
  43. gettext_lazy,
  44. ngettext,
  45. ngettext_lazy,
  46. npgettext,
  47. npgettext_lazy,
  48. pgettext,
  49. round_away_from_one,
  50. to_language,
  51. to_locale,
  52. trans_null,
  53. trans_real,
  54. )
  55. from django.utils.translation.reloader import (
  56. translation_file_changed,
  57. watch_for_translation_changes,
  58. )
  59. from django.utils.translation.trans_real import LANGUAGE_CODE_MAX_LENGTH
  60. from .forms import CompanyForm, I18nForm, SelectDateForm
  61. from .models import Company, TestModel
  62. here = os.path.dirname(os.path.abspath(__file__))
  63. extended_locale_paths = settings.LOCALE_PATHS + [
  64. os.path.join(here, "other", "locale"),
  65. ]
  66. class AppModuleStub:
  67. def __init__(self, **kwargs):
  68. self.__dict__.update(kwargs)
  69. @contextmanager
  70. def patch_formats(lang, **settings):
  71. from django.utils.formats import _format_cache
  72. # Populate _format_cache with temporary values
  73. for key, value in settings.items():
  74. _format_cache[(key, lang)] = value
  75. try:
  76. yield
  77. finally:
  78. reset_format_cache()
  79. class TranslationTests(SimpleTestCase):
  80. @translation.override("fr")
  81. def test_plural(self):
  82. """
  83. Test plurals with ngettext. French differs from English in that 0 is singular.
  84. """
  85. self.assertEqual(
  86. ngettext("%(num)d year", "%(num)d years", 0) % {"num": 0},
  87. "0 année",
  88. )
  89. self.assertEqual(
  90. ngettext("%(num)d year", "%(num)d years", 2) % {"num": 2},
  91. "2 années",
  92. )
  93. self.assertEqual(
  94. ngettext("%(size)d byte", "%(size)d bytes", 0) % {"size": 0}, "0 octet"
  95. )
  96. self.assertEqual(
  97. ngettext("%(size)d byte", "%(size)d bytes", 2) % {"size": 2}, "2 octets"
  98. )
  99. def test_plural_null(self):
  100. g = trans_null.ngettext
  101. self.assertEqual(g("%(num)d year", "%(num)d years", 0) % {"num": 0}, "0 years")
  102. self.assertEqual(g("%(num)d year", "%(num)d years", 1) % {"num": 1}, "1 year")
  103. self.assertEqual(g("%(num)d year", "%(num)d years", 2) % {"num": 2}, "2 years")
  104. @override_settings(LOCALE_PATHS=extended_locale_paths)
  105. @translation.override("fr")
  106. def test_multiple_plurals_per_language(self):
  107. """
  108. Normally, French has 2 plurals. As other/locale/fr/LC_MESSAGES/django.po
  109. has a different plural equation with 3 plurals, this tests if those
  110. plural are honored.
  111. """
  112. self.assertEqual(ngettext("%d singular", "%d plural", 0) % 0, "0 pluriel1")
  113. self.assertEqual(ngettext("%d singular", "%d plural", 1) % 1, "1 singulier")
  114. self.assertEqual(ngettext("%d singular", "%d plural", 2) % 2, "2 pluriel2")
  115. french = trans_real.catalog()
  116. # Internal _catalog can query subcatalogs (from different po files).
  117. self.assertEqual(french._catalog[("%d singular", 0)], "%d singulier")
  118. self.assertEqual(french._catalog[("%(num)d hour", 0)], "%(num)d heure")
  119. def test_override(self):
  120. activate("de")
  121. try:
  122. with translation.override("pl"):
  123. self.assertEqual(get_language(), "pl")
  124. self.assertEqual(get_language(), "de")
  125. with translation.override(None):
  126. self.assertIsNone(get_language())
  127. with translation.override("pl"):
  128. pass
  129. self.assertIsNone(get_language())
  130. self.assertEqual(get_language(), "de")
  131. finally:
  132. deactivate()
  133. def test_override_decorator(self):
  134. @translation.override("pl")
  135. def func_pl():
  136. self.assertEqual(get_language(), "pl")
  137. @translation.override(None)
  138. def func_none():
  139. self.assertIsNone(get_language())
  140. try:
  141. activate("de")
  142. func_pl()
  143. self.assertEqual(get_language(), "de")
  144. func_none()
  145. self.assertEqual(get_language(), "de")
  146. finally:
  147. deactivate()
  148. def test_override_exit(self):
  149. """
  150. The language restored is the one used when the function was
  151. called, not the one used when the decorator was initialized (#23381).
  152. """
  153. activate("fr")
  154. @translation.override("pl")
  155. def func_pl():
  156. pass
  157. deactivate()
  158. try:
  159. activate("en")
  160. func_pl()
  161. self.assertEqual(get_language(), "en")
  162. finally:
  163. deactivate()
  164. def test_lazy_objects(self):
  165. """
  166. Format string interpolation should work with *_lazy objects.
  167. """
  168. s = gettext_lazy("Add %(name)s")
  169. d = {"name": "Ringo"}
  170. self.assertEqual("Add Ringo", s % d)
  171. with translation.override("de", deactivate=True):
  172. self.assertEqual("Ringo hinzuf\xfcgen", s % d)
  173. with translation.override("pl"):
  174. self.assertEqual("Dodaj Ringo", s % d)
  175. # It should be possible to compare *_lazy objects.
  176. s1 = gettext_lazy("Add %(name)s")
  177. self.assertEqual(s, s1)
  178. s2 = gettext_lazy("Add %(name)s")
  179. s3 = gettext_lazy("Add %(name)s")
  180. self.assertEqual(s2, s3)
  181. self.assertEqual(s, s2)
  182. s4 = gettext_lazy("Some other string")
  183. self.assertNotEqual(s, s4)
  184. def test_lazy_pickle(self):
  185. s1 = gettext_lazy("test")
  186. self.assertEqual(str(s1), "test")
  187. s2 = pickle.loads(pickle.dumps(s1))
  188. self.assertEqual(str(s2), "test")
  189. @override_settings(LOCALE_PATHS=extended_locale_paths)
  190. def test_ngettext_lazy(self):
  191. simple_with_format = ngettext_lazy("%d good result", "%d good results")
  192. simple_context_with_format = npgettext_lazy(
  193. "Exclamation", "%d good result", "%d good results"
  194. )
  195. simple_without_format = ngettext_lazy("good result", "good results")
  196. with translation.override("de"):
  197. self.assertEqual(simple_with_format % 1, "1 gutes Resultat")
  198. self.assertEqual(simple_with_format % 4, "4 guten Resultate")
  199. self.assertEqual(simple_context_with_format % 1, "1 gutes Resultat!")
  200. self.assertEqual(simple_context_with_format % 4, "4 guten Resultate!")
  201. self.assertEqual(simple_without_format % 1, "gutes Resultat")
  202. self.assertEqual(simple_without_format % 4, "guten Resultate")
  203. complex_nonlazy = ngettext_lazy(
  204. "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", 4
  205. )
  206. complex_deferred = ngettext_lazy(
  207. "Hi %(name)s, %(num)d good result",
  208. "Hi %(name)s, %(num)d good results",
  209. "num",
  210. )
  211. complex_context_nonlazy = npgettext_lazy(
  212. "Greeting",
  213. "Hi %(name)s, %(num)d good result",
  214. "Hi %(name)s, %(num)d good results",
  215. 4,
  216. )
  217. complex_context_deferred = npgettext_lazy(
  218. "Greeting",
  219. "Hi %(name)s, %(num)d good result",
  220. "Hi %(name)s, %(num)d good results",
  221. "num",
  222. )
  223. with translation.override("de"):
  224. self.assertEqual(
  225. complex_nonlazy % {"num": 4, "name": "Jim"},
  226. "Hallo Jim, 4 guten Resultate",
  227. )
  228. self.assertEqual(
  229. complex_deferred % {"name": "Jim", "num": 1},
  230. "Hallo Jim, 1 gutes Resultat",
  231. )
  232. self.assertEqual(
  233. complex_deferred % {"name": "Jim", "num": 5},
  234. "Hallo Jim, 5 guten Resultate",
  235. )
  236. with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"):
  237. complex_deferred % {"name": "Jim"}
  238. self.assertEqual(
  239. complex_context_nonlazy % {"num": 4, "name": "Jim"},
  240. "Willkommen Jim, 4 guten Resultate",
  241. )
  242. self.assertEqual(
  243. complex_context_deferred % {"name": "Jim", "num": 1},
  244. "Willkommen Jim, 1 gutes Resultat",
  245. )
  246. self.assertEqual(
  247. complex_context_deferred % {"name": "Jim", "num": 5},
  248. "Willkommen Jim, 5 guten Resultate",
  249. )
  250. with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"):
  251. complex_context_deferred % {"name": "Jim"}
  252. @override_settings(LOCALE_PATHS=extended_locale_paths)
  253. def test_ngettext_lazy_format_style(self):
  254. simple_with_format = ngettext_lazy("{} good result", "{} good results")
  255. simple_context_with_format = npgettext_lazy(
  256. "Exclamation", "{} good result", "{} good results"
  257. )
  258. with translation.override("de"):
  259. self.assertEqual(simple_with_format.format(1), "1 gutes Resultat")
  260. self.assertEqual(simple_with_format.format(4), "4 guten Resultate")
  261. self.assertEqual(simple_context_with_format.format(1), "1 gutes Resultat!")
  262. self.assertEqual(simple_context_with_format.format(4), "4 guten Resultate!")
  263. complex_nonlazy = ngettext_lazy(
  264. "Hi {name}, {num} good result", "Hi {name}, {num} good results", 4
  265. )
  266. complex_deferred = ngettext_lazy(
  267. "Hi {name}, {num} good result", "Hi {name}, {num} good results", "num"
  268. )
  269. complex_context_nonlazy = npgettext_lazy(
  270. "Greeting",
  271. "Hi {name}, {num} good result",
  272. "Hi {name}, {num} good results",
  273. 4,
  274. )
  275. complex_context_deferred = npgettext_lazy(
  276. "Greeting",
  277. "Hi {name}, {num} good result",
  278. "Hi {name}, {num} good results",
  279. "num",
  280. )
  281. with translation.override("de"):
  282. self.assertEqual(
  283. complex_nonlazy.format(num=4, name="Jim"),
  284. "Hallo Jim, 4 guten Resultate",
  285. )
  286. self.assertEqual(
  287. complex_deferred.format(name="Jim", num=1),
  288. "Hallo Jim, 1 gutes Resultat",
  289. )
  290. self.assertEqual(
  291. complex_deferred.format(name="Jim", num=5),
  292. "Hallo Jim, 5 guten Resultate",
  293. )
  294. with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"):
  295. complex_deferred.format(name="Jim")
  296. self.assertEqual(
  297. complex_context_nonlazy.format(num=4, name="Jim"),
  298. "Willkommen Jim, 4 guten Resultate",
  299. )
  300. self.assertEqual(
  301. complex_context_deferred.format(name="Jim", num=1),
  302. "Willkommen Jim, 1 gutes Resultat",
  303. )
  304. self.assertEqual(
  305. complex_context_deferred.format(name="Jim", num=5),
  306. "Willkommen Jim, 5 guten Resultate",
  307. )
  308. with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"):
  309. complex_context_deferred.format(name="Jim")
  310. def test_ngettext_lazy_bool(self):
  311. self.assertTrue(ngettext_lazy("%d good result", "%d good results"))
  312. self.assertFalse(ngettext_lazy("", ""))
  313. def test_ngettext_lazy_pickle(self):
  314. s1 = ngettext_lazy("%d good result", "%d good results")
  315. self.assertEqual(s1 % 1, "1 good result")
  316. self.assertEqual(s1 % 8, "8 good results")
  317. s2 = pickle.loads(pickle.dumps(s1))
  318. self.assertEqual(s2 % 1, "1 good result")
  319. self.assertEqual(s2 % 8, "8 good results")
  320. @override_settings(LOCALE_PATHS=extended_locale_paths)
  321. def test_pgettext(self):
  322. trans_real._active = Local()
  323. trans_real._translations = {}
  324. with translation.override("de"):
  325. self.assertEqual(pgettext("unexisting", "May"), "May")
  326. self.assertEqual(pgettext("month name", "May"), "Mai")
  327. self.assertEqual(pgettext("verb", "May"), "Kann")
  328. self.assertEqual(
  329. npgettext("search", "%d result", "%d results", 4) % 4, "4 Resultate"
  330. )
  331. def test_empty_value(self):
  332. """Empty value must stay empty after being translated (#23196)."""
  333. with translation.override("de"):
  334. self.assertEqual("", gettext(""))
  335. s = mark_safe("")
  336. self.assertEqual(s, gettext(s))
  337. @override_settings(LOCALE_PATHS=extended_locale_paths)
  338. def test_safe_status(self):
  339. """
  340. Translating a string requiring no auto-escaping with gettext or pgettext
  341. shouldn't change the "safe" status.
  342. """
  343. trans_real._active = Local()
  344. trans_real._translations = {}
  345. s1 = mark_safe("Password")
  346. s2 = mark_safe("May")
  347. with translation.override("de", deactivate=True):
  348. self.assertIs(type(gettext(s1)), SafeString)
  349. self.assertIs(type(pgettext("month name", s2)), SafeString)
  350. self.assertEqual("aPassword", SafeString("a") + s1)
  351. self.assertEqual("Passworda", s1 + SafeString("a"))
  352. self.assertEqual("Passworda", s1 + mark_safe("a"))
  353. self.assertEqual("aPassword", mark_safe("a") + s1)
  354. self.assertEqual("as", mark_safe("a") + mark_safe("s"))
  355. def test_maclines(self):
  356. """
  357. Translations on files with Mac or DOS end of lines will be converted
  358. to unix EOF in .po catalogs.
  359. """
  360. ca_translation = trans_real.translation("ca")
  361. ca_translation._catalog["Mac\nEOF\n"] = "Catalan Mac\nEOF\n"
  362. ca_translation._catalog["Win\nEOF\n"] = "Catalan Win\nEOF\n"
  363. with translation.override("ca", deactivate=True):
  364. self.assertEqual("Catalan Mac\nEOF\n", gettext("Mac\rEOF\r"))
  365. self.assertEqual("Catalan Win\nEOF\n", gettext("Win\r\nEOF\r\n"))
  366. def test_to_locale(self):
  367. tests = (
  368. ("en", "en"),
  369. ("EN", "en"),
  370. ("en-us", "en_US"),
  371. ("EN-US", "en_US"),
  372. ("en_US", "en_US"),
  373. # With > 2 characters after the dash.
  374. ("sr-latn", "sr_Latn"),
  375. ("sr-LATN", "sr_Latn"),
  376. ("sr_Latn", "sr_Latn"),
  377. # 3-char language codes.
  378. ("ber-MA", "ber_MA"),
  379. ("BER-MA", "ber_MA"),
  380. ("BER_MA", "ber_MA"),
  381. ("ber_MA", "ber_MA"),
  382. # With private use subtag (x-informal).
  383. ("nl-nl-x-informal", "nl_NL-x-informal"),
  384. ("NL-NL-X-INFORMAL", "nl_NL-x-informal"),
  385. ("sr-latn-x-informal", "sr_Latn-x-informal"),
  386. ("SR-LATN-X-INFORMAL", "sr_Latn-x-informal"),
  387. )
  388. for lang, locale in tests:
  389. with self.subTest(lang=lang):
  390. self.assertEqual(to_locale(lang), locale)
  391. def test_to_language(self):
  392. self.assertEqual(to_language("en_US"), "en-us")
  393. self.assertEqual(to_language("sr_Lat"), "sr-lat")
  394. def test_language_bidi(self):
  395. self.assertIs(get_language_bidi(), False)
  396. with translation.override(None):
  397. self.assertIs(get_language_bidi(), False)
  398. def test_language_bidi_null(self):
  399. self.assertIs(trans_null.get_language_bidi(), False)
  400. with override_settings(LANGUAGE_CODE="he"):
  401. self.assertIs(get_language_bidi(), True)
  402. class TranslationLoadingTests(SimpleTestCase):
  403. def setUp(self):
  404. """Clear translation state."""
  405. self._old_language = get_language()
  406. self._old_translations = trans_real._translations
  407. deactivate()
  408. trans_real._translations = {}
  409. def tearDown(self):
  410. trans_real._translations = self._old_translations
  411. activate(self._old_language)
  412. @override_settings(
  413. USE_I18N=True,
  414. LANGUAGE_CODE="en",
  415. LANGUAGES=[
  416. ("en", "English"),
  417. ("en-ca", "English (Canada)"),
  418. ("en-nz", "English (New Zealand)"),
  419. ("en-au", "English (Australia)"),
  420. ],
  421. LOCALE_PATHS=[os.path.join(here, "loading")],
  422. INSTALLED_APPS=["i18n.loading_app"],
  423. )
  424. def test_translation_loading(self):
  425. """
  426. "loading_app" does not have translations for all languages provided by
  427. "loading". Catalogs are merged correctly.
  428. """
  429. tests = [
  430. ("en", "local country person"),
  431. ("en_AU", "aussie"),
  432. ("en_NZ", "kiwi"),
  433. ("en_CA", "canuck"),
  434. ]
  435. # Load all relevant translations.
  436. for language, _ in tests:
  437. activate(language)
  438. # Catalogs are merged correctly.
  439. for language, nickname in tests:
  440. with self.subTest(language=language):
  441. activate(language)
  442. self.assertEqual(gettext("local country person"), nickname)
  443. class TranslationThreadSafetyTests(SimpleTestCase):
  444. def setUp(self):
  445. self._old_language = get_language()
  446. self._translations = trans_real._translations
  447. # here we rely on .split() being called inside the _fetch()
  448. # in trans_real.translation()
  449. class sideeffect_str(str):
  450. def split(self, *args, **kwargs):
  451. res = str.split(self, *args, **kwargs)
  452. trans_real._translations["en-YY"] = None
  453. return res
  454. trans_real._translations = {sideeffect_str("en-XX"): None}
  455. def tearDown(self):
  456. trans_real._translations = self._translations
  457. activate(self._old_language)
  458. def test_bug14894_translation_activate_thread_safety(self):
  459. translation_count = len(trans_real._translations)
  460. # May raise RuntimeError if translation.activate() isn't thread-safe.
  461. translation.activate("pl")
  462. # make sure sideeffect_str actually added a new translation
  463. self.assertLess(translation_count, len(trans_real._translations))
  464. class FormattingTests(SimpleTestCase):
  465. def setUp(self):
  466. super().setUp()
  467. self.n = decimal.Decimal("66666.666")
  468. self.f = 99999.999
  469. self.d = datetime.date(2009, 12, 31)
  470. self.dt = datetime.datetime(2009, 12, 31, 20, 50)
  471. self.t = datetime.time(10, 15, 48)
  472. self.long = 10000
  473. self.ctxt = Context(
  474. {
  475. "n": self.n,
  476. "t": self.t,
  477. "d": self.d,
  478. "dt": self.dt,
  479. "f": self.f,
  480. "l": self.long,
  481. }
  482. )
  483. def test_all_format_strings(self):
  484. all_locales = LANG_INFO.keys()
  485. some_date = datetime.date(2017, 10, 14)
  486. some_datetime = datetime.datetime(2017, 10, 14, 10, 23)
  487. for locale in all_locales:
  488. with self.subTest(locale=locale), translation.override(locale):
  489. self.assertIn(
  490. "2017", date_format(some_date)
  491. ) # Uses DATE_FORMAT by default
  492. self.assertIn(
  493. "23", time_format(some_datetime)
  494. ) # Uses TIME_FORMAT by default
  495. self.assertIn("2017", date_format(some_datetime, "DATETIME_FORMAT"))
  496. self.assertIn("2017", date_format(some_date, "YEAR_MONTH_FORMAT"))
  497. self.assertIn("14", date_format(some_date, "MONTH_DAY_FORMAT"))
  498. self.assertIn("2017", date_format(some_date, "SHORT_DATE_FORMAT"))
  499. self.assertIn(
  500. "2017",
  501. date_format(some_datetime, "SHORT_DATETIME_FORMAT"),
  502. )
  503. def test_locale_independent(self):
  504. """
  505. Localization of numbers
  506. """
  507. with self.settings(USE_THOUSAND_SEPARATOR=False):
  508. self.assertEqual(
  509. "66666.66",
  510. nformat(
  511. self.n, decimal_sep=".", decimal_pos=2, grouping=3, thousand_sep=","
  512. ),
  513. )
  514. self.assertEqual(
  515. "66666A6",
  516. nformat(
  517. self.n, decimal_sep="A", decimal_pos=1, grouping=1, thousand_sep="B"
  518. ),
  519. )
  520. self.assertEqual(
  521. "66666",
  522. nformat(
  523. self.n, decimal_sep="X", decimal_pos=0, grouping=1, thousand_sep="Y"
  524. ),
  525. )
  526. with self.settings(USE_THOUSAND_SEPARATOR=True):
  527. self.assertEqual(
  528. "66,666.66",
  529. nformat(
  530. self.n, decimal_sep=".", decimal_pos=2, grouping=3, thousand_sep=","
  531. ),
  532. )
  533. self.assertEqual(
  534. "6B6B6B6B6A6",
  535. nformat(
  536. self.n, decimal_sep="A", decimal_pos=1, grouping=1, thousand_sep="B"
  537. ),
  538. )
  539. self.assertEqual(
  540. "-66666.6", nformat(-66666.666, decimal_sep=".", decimal_pos=1)
  541. )
  542. self.assertEqual(
  543. "-66666.0", nformat(int("-66666"), decimal_sep=".", decimal_pos=1)
  544. )
  545. self.assertEqual(
  546. "10000.0", nformat(self.long, decimal_sep=".", decimal_pos=1)
  547. )
  548. self.assertEqual(
  549. "10,00,00,000.00",
  550. nformat(
  551. 100000000.00,
  552. decimal_sep=".",
  553. decimal_pos=2,
  554. grouping=(3, 2, 0),
  555. thousand_sep=",",
  556. ),
  557. )
  558. self.assertEqual(
  559. "1,0,00,000,0000.00",
  560. nformat(
  561. 10000000000.00,
  562. decimal_sep=".",
  563. decimal_pos=2,
  564. grouping=(4, 3, 2, 1, 0),
  565. thousand_sep=",",
  566. ),
  567. )
  568. self.assertEqual(
  569. "10000,00,000.00",
  570. nformat(
  571. 1000000000.00,
  572. decimal_sep=".",
  573. decimal_pos=2,
  574. grouping=(3, 2, -1),
  575. thousand_sep=",",
  576. ),
  577. )
  578. # This unusual grouping/force_grouping combination may be triggered
  579. # by the intcomma filter.
  580. self.assertEqual(
  581. "10000",
  582. nformat(
  583. self.long,
  584. decimal_sep=".",
  585. decimal_pos=0,
  586. grouping=0,
  587. force_grouping=True,
  588. ),
  589. )
  590. # date filter
  591. self.assertEqual(
  592. "31.12.2009 в 20:50",
  593. Template('{{ dt|date:"d.m.Y в H:i" }}').render(self.ctxt),
  594. )
  595. self.assertEqual(
  596. "⌚ 10:15", Template('{{ t|time:"⌚ H:i" }}').render(self.ctxt)
  597. )
  598. def test_false_like_locale_formats(self):
  599. """
  600. The active locale's formats take precedence over the default settings
  601. even if they would be interpreted as False in a conditional test
  602. (e.g. 0 or empty string) (#16938).
  603. """
  604. with translation.override("fr"):
  605. with self.settings(USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="!"):
  606. self.assertEqual("\xa0", get_format("THOUSAND_SEPARATOR"))
  607. # Even a second time (after the format has been cached)...
  608. self.assertEqual("\xa0", get_format("THOUSAND_SEPARATOR"))
  609. with self.settings(FIRST_DAY_OF_WEEK=0):
  610. self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK"))
  611. # Even a second time (after the format has been cached)...
  612. self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK"))
  613. def test_l10n_enabled(self):
  614. self.maxDiff = 3000
  615. # Catalan locale
  616. with translation.override("ca", deactivate=True):
  617. self.assertEqual(r"j E \d\e Y", get_format("DATE_FORMAT"))
  618. self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK"))
  619. self.assertEqual(",", get_format("DECIMAL_SEPARATOR"))
  620. self.assertEqual("10:15", time_format(self.t))
  621. self.assertEqual("31 desembre de 2009", date_format(self.d))
  622. self.assertEqual("1 abril de 2009", date_format(datetime.date(2009, 4, 1)))
  623. self.assertEqual(
  624. "desembre del 2009", date_format(self.d, "YEAR_MONTH_FORMAT")
  625. )
  626. self.assertEqual(
  627. "31/12/2009 20:50", date_format(self.dt, "SHORT_DATETIME_FORMAT")
  628. )
  629. self.assertEqual("No localizable", localize("No localizable"))
  630. with self.settings(USE_THOUSAND_SEPARATOR=True):
  631. self.assertEqual("66.666,666", localize(self.n))
  632. self.assertEqual("99.999,999", localize(self.f))
  633. self.assertEqual("10.000", localize(self.long))
  634. self.assertEqual("True", localize(True))
  635. with self.settings(USE_THOUSAND_SEPARATOR=False):
  636. self.assertEqual("66666,666", localize(self.n))
  637. self.assertEqual("99999,999", localize(self.f))
  638. self.assertEqual("10000", localize(self.long))
  639. self.assertEqual("31 desembre de 2009", localize(self.d))
  640. self.assertEqual("31 desembre de 2009 a les 20:50", localize(self.dt))
  641. with self.settings(USE_THOUSAND_SEPARATOR=True):
  642. self.assertEqual("66.666,666", Template("{{ n }}").render(self.ctxt))
  643. self.assertEqual("99.999,999", Template("{{ f }}").render(self.ctxt))
  644. self.assertEqual("10.000", Template("{{ l }}").render(self.ctxt))
  645. with self.settings(USE_THOUSAND_SEPARATOR=True):
  646. form3 = I18nForm(
  647. {
  648. "decimal_field": "66.666,666",
  649. "float_field": "99.999,999",
  650. "date_field": "31/12/2009",
  651. "datetime_field": "31/12/2009 20:50",
  652. "time_field": "20:50",
  653. "integer_field": "1.234",
  654. }
  655. )
  656. self.assertTrue(form3.is_valid())
  657. self.assertEqual(
  658. decimal.Decimal("66666.666"), form3.cleaned_data["decimal_field"]
  659. )
  660. self.assertEqual(99999.999, form3.cleaned_data["float_field"])
  661. self.assertEqual(
  662. datetime.date(2009, 12, 31), form3.cleaned_data["date_field"]
  663. )
  664. self.assertEqual(
  665. datetime.datetime(2009, 12, 31, 20, 50),
  666. form3.cleaned_data["datetime_field"],
  667. )
  668. self.assertEqual(
  669. datetime.time(20, 50), form3.cleaned_data["time_field"]
  670. )
  671. self.assertEqual(1234, form3.cleaned_data["integer_field"])
  672. with self.settings(USE_THOUSAND_SEPARATOR=False):
  673. self.assertEqual("66666,666", Template("{{ n }}").render(self.ctxt))
  674. self.assertEqual("99999,999", Template("{{ f }}").render(self.ctxt))
  675. self.assertEqual(
  676. "31 desembre de 2009", Template("{{ d }}").render(self.ctxt)
  677. )
  678. self.assertEqual(
  679. "31 desembre de 2009 a les 20:50",
  680. Template("{{ dt }}").render(self.ctxt),
  681. )
  682. self.assertEqual(
  683. "66666,67", Template("{{ n|floatformat:2 }}").render(self.ctxt)
  684. )
  685. self.assertEqual(
  686. "100000,0", Template("{{ f|floatformat }}").render(self.ctxt)
  687. )
  688. self.assertEqual(
  689. "66.666,67",
  690. Template('{{ n|floatformat:"2g" }}').render(self.ctxt),
  691. )
  692. self.assertEqual(
  693. "100.000,0",
  694. Template('{{ f|floatformat:"g" }}').render(self.ctxt),
  695. )
  696. self.assertEqual(
  697. "10:15", Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt)
  698. )
  699. self.assertEqual(
  700. "31/12/2009",
  701. Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt),
  702. )
  703. self.assertEqual(
  704. "31/12/2009 20:50",
  705. Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt),
  706. )
  707. self.assertEqual(
  708. date_format(datetime.datetime.now()),
  709. Template('{% now "DATE_FORMAT" %}').render(self.ctxt),
  710. )
  711. with self.settings(USE_THOUSAND_SEPARATOR=False):
  712. form4 = I18nForm(
  713. {
  714. "decimal_field": "66666,666",
  715. "float_field": "99999,999",
  716. "date_field": "31/12/2009",
  717. "datetime_field": "31/12/2009 20:50",
  718. "time_field": "20:50",
  719. "integer_field": "1234",
  720. }
  721. )
  722. self.assertTrue(form4.is_valid())
  723. self.assertEqual(
  724. decimal.Decimal("66666.666"), form4.cleaned_data["decimal_field"]
  725. )
  726. self.assertEqual(99999.999, form4.cleaned_data["float_field"])
  727. self.assertEqual(
  728. datetime.date(2009, 12, 31), form4.cleaned_data["date_field"]
  729. )
  730. self.assertEqual(
  731. datetime.datetime(2009, 12, 31, 20, 50),
  732. form4.cleaned_data["datetime_field"],
  733. )
  734. self.assertEqual(
  735. datetime.time(20, 50), form4.cleaned_data["time_field"]
  736. )
  737. self.assertEqual(1234, form4.cleaned_data["integer_field"])
  738. form5 = SelectDateForm(
  739. {
  740. "date_field_month": "12",
  741. "date_field_day": "31",
  742. "date_field_year": "2009",
  743. }
  744. )
  745. self.assertTrue(form5.is_valid())
  746. self.assertEqual(
  747. datetime.date(2009, 12, 31), form5.cleaned_data["date_field"]
  748. )
  749. self.assertHTMLEqual(
  750. '<select name="mydate_day" id="id_mydate_day">'
  751. '<option value="">---</option>'
  752. '<option value="1">1</option>'
  753. '<option value="2">2</option>'
  754. '<option value="3">3</option>'
  755. '<option value="4">4</option>'
  756. '<option value="5">5</option>'
  757. '<option value="6">6</option>'
  758. '<option value="7">7</option>'
  759. '<option value="8">8</option>'
  760. '<option value="9">9</option>'
  761. '<option value="10">10</option>'
  762. '<option value="11">11</option>'
  763. '<option value="12">12</option>'
  764. '<option value="13">13</option>'
  765. '<option value="14">14</option>'
  766. '<option value="15">15</option>'
  767. '<option value="16">16</option>'
  768. '<option value="17">17</option>'
  769. '<option value="18">18</option>'
  770. '<option value="19">19</option>'
  771. '<option value="20">20</option>'
  772. '<option value="21">21</option>'
  773. '<option value="22">22</option>'
  774. '<option value="23">23</option>'
  775. '<option value="24">24</option>'
  776. '<option value="25">25</option>'
  777. '<option value="26">26</option>'
  778. '<option value="27">27</option>'
  779. '<option value="28">28</option>'
  780. '<option value="29">29</option>'
  781. '<option value="30">30</option>'
  782. '<option value="31" selected>31</option>'
  783. "</select>"
  784. '<select name="mydate_month" id="id_mydate_month">'
  785. '<option value="">---</option>'
  786. '<option value="1">gener</option>'
  787. '<option value="2">febrer</option>'
  788. '<option value="3">mar\xe7</option>'
  789. '<option value="4">abril</option>'
  790. '<option value="5">maig</option>'
  791. '<option value="6">juny</option>'
  792. '<option value="7">juliol</option>'
  793. '<option value="8">agost</option>'
  794. '<option value="9">setembre</option>'
  795. '<option value="10">octubre</option>'
  796. '<option value="11">novembre</option>'
  797. '<option value="12" selected>desembre</option>'
  798. "</select>"
  799. '<select name="mydate_year" id="id_mydate_year">'
  800. '<option value="">---</option>'
  801. '<option value="2009" selected>2009</option>'
  802. '<option value="2010">2010</option>'
  803. '<option value="2011">2011</option>'
  804. '<option value="2012">2012</option>'
  805. '<option value="2013">2013</option>'
  806. '<option value="2014">2014</option>'
  807. '<option value="2015">2015</option>'
  808. '<option value="2016">2016</option>'
  809. '<option value="2017">2017</option>'
  810. '<option value="2018">2018</option>'
  811. "</select>",
  812. forms.SelectDateWidget(years=range(2009, 2019)).render(
  813. "mydate", datetime.date(2009, 12, 31)
  814. ),
  815. )
  816. # Russian locale (with E as month)
  817. with translation.override("ru", deactivate=True):
  818. self.assertHTMLEqual(
  819. '<select name="mydate_day" id="id_mydate_day">'
  820. '<option value="">---</option>'
  821. '<option value="1">1</option>'
  822. '<option value="2">2</option>'
  823. '<option value="3">3</option>'
  824. '<option value="4">4</option>'
  825. '<option value="5">5</option>'
  826. '<option value="6">6</option>'
  827. '<option value="7">7</option>'
  828. '<option value="8">8</option>'
  829. '<option value="9">9</option>'
  830. '<option value="10">10</option>'
  831. '<option value="11">11</option>'
  832. '<option value="12">12</option>'
  833. '<option value="13">13</option>'
  834. '<option value="14">14</option>'
  835. '<option value="15">15</option>'
  836. '<option value="16">16</option>'
  837. '<option value="17">17</option>'
  838. '<option value="18">18</option>'
  839. '<option value="19">19</option>'
  840. '<option value="20">20</option>'
  841. '<option value="21">21</option>'
  842. '<option value="22">22</option>'
  843. '<option value="23">23</option>'
  844. '<option value="24">24</option>'
  845. '<option value="25">25</option>'
  846. '<option value="26">26</option>'
  847. '<option value="27">27</option>'
  848. '<option value="28">28</option>'
  849. '<option value="29">29</option>'
  850. '<option value="30">30</option>'
  851. '<option value="31" selected>31</option>'
  852. "</select>"
  853. '<select name="mydate_month" id="id_mydate_month">'
  854. '<option value="">---</option>'
  855. '<option value="1">\u042f\u043d\u0432\u0430\u0440\u044c</option>'
  856. '<option value="2">\u0424\u0435\u0432\u0440\u0430\u043b\u044c</option>'
  857. '<option value="3">\u041c\u0430\u0440\u0442</option>'
  858. '<option value="4">\u0410\u043f\u0440\u0435\u043b\u044c</option>'
  859. '<option value="5">\u041c\u0430\u0439</option>'
  860. '<option value="6">\u0418\u044e\u043d\u044c</option>'
  861. '<option value="7">\u0418\u044e\u043b\u044c</option>'
  862. '<option value="8">\u0410\u0432\u0433\u0443\u0441\u0442</option>'
  863. '<option value="9">\u0421\u0435\u043d\u0442\u044f\u0431\u0440\u044c'
  864. "</option>"
  865. '<option value="10">\u041e\u043a\u0442\u044f\u0431\u0440\u044c</option>'
  866. '<option value="11">\u041d\u043e\u044f\u0431\u0440\u044c</option>'
  867. '<option value="12" selected>\u0414\u0435\u043a\u0430\u0431\u0440\u044c'
  868. "</option>"
  869. "</select>"
  870. '<select name="mydate_year" id="id_mydate_year">'
  871. '<option value="">---</option>'
  872. '<option value="2009" selected>2009</option>'
  873. '<option value="2010">2010</option>'
  874. '<option value="2011">2011</option>'
  875. '<option value="2012">2012</option>'
  876. '<option value="2013">2013</option>'
  877. '<option value="2014">2014</option>'
  878. '<option value="2015">2015</option>'
  879. '<option value="2016">2016</option>'
  880. '<option value="2017">2017</option>'
  881. '<option value="2018">2018</option>'
  882. "</select>",
  883. forms.SelectDateWidget(years=range(2009, 2019)).render(
  884. "mydate", datetime.date(2009, 12, 31)
  885. ),
  886. )
  887. # English locale
  888. with translation.override("en", deactivate=True):
  889. self.assertEqual("N j, Y", get_format("DATE_FORMAT"))
  890. self.assertEqual(0, get_format("FIRST_DAY_OF_WEEK"))
  891. self.assertEqual(".", get_format("DECIMAL_SEPARATOR"))
  892. self.assertEqual("Dec. 31, 2009", date_format(self.d))
  893. self.assertEqual("December 2009", date_format(self.d, "YEAR_MONTH_FORMAT"))
  894. self.assertEqual(
  895. "12/31/2009 8:50 p.m.", date_format(self.dt, "SHORT_DATETIME_FORMAT")
  896. )
  897. self.assertEqual("No localizable", localize("No localizable"))
  898. with self.settings(USE_THOUSAND_SEPARATOR=True):
  899. self.assertEqual("66,666.666", localize(self.n))
  900. self.assertEqual("99,999.999", localize(self.f))
  901. self.assertEqual("10,000", localize(self.long))
  902. with self.settings(USE_THOUSAND_SEPARATOR=False):
  903. self.assertEqual("66666.666", localize(self.n))
  904. self.assertEqual("99999.999", localize(self.f))
  905. self.assertEqual("10000", localize(self.long))
  906. self.assertEqual("Dec. 31, 2009", localize(self.d))
  907. self.assertEqual("Dec. 31, 2009, 8:50 p.m.", localize(self.dt))
  908. with self.settings(USE_THOUSAND_SEPARATOR=True):
  909. self.assertEqual("66,666.666", Template("{{ n }}").render(self.ctxt))
  910. self.assertEqual("99,999.999", Template("{{ f }}").render(self.ctxt))
  911. self.assertEqual("10,000", Template("{{ l }}").render(self.ctxt))
  912. with self.settings(USE_THOUSAND_SEPARATOR=False):
  913. self.assertEqual("66666.666", Template("{{ n }}").render(self.ctxt))
  914. self.assertEqual("99999.999", Template("{{ f }}").render(self.ctxt))
  915. self.assertEqual("Dec. 31, 2009", Template("{{ d }}").render(self.ctxt))
  916. self.assertEqual(
  917. "Dec. 31, 2009, 8:50 p.m.", Template("{{ dt }}").render(self.ctxt)
  918. )
  919. self.assertEqual(
  920. "66666.67", Template("{{ n|floatformat:2 }}").render(self.ctxt)
  921. )
  922. self.assertEqual(
  923. "100000.0", Template("{{ f|floatformat }}").render(self.ctxt)
  924. )
  925. self.assertEqual(
  926. "66,666.67",
  927. Template('{{ n|floatformat:"2g" }}').render(self.ctxt),
  928. )
  929. self.assertEqual(
  930. "100,000.0",
  931. Template('{{ f|floatformat:"g" }}').render(self.ctxt),
  932. )
  933. self.assertEqual(
  934. "12/31/2009",
  935. Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt),
  936. )
  937. self.assertEqual(
  938. "12/31/2009 8:50 p.m.",
  939. Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt),
  940. )
  941. form5 = I18nForm(
  942. {
  943. "decimal_field": "66666.666",
  944. "float_field": "99999.999",
  945. "date_field": "12/31/2009",
  946. "datetime_field": "12/31/2009 20:50",
  947. "time_field": "20:50",
  948. "integer_field": "1234",
  949. }
  950. )
  951. self.assertTrue(form5.is_valid())
  952. self.assertEqual(
  953. decimal.Decimal("66666.666"), form5.cleaned_data["decimal_field"]
  954. )
  955. self.assertEqual(99999.999, form5.cleaned_data["float_field"])
  956. self.assertEqual(
  957. datetime.date(2009, 12, 31), form5.cleaned_data["date_field"]
  958. )
  959. self.assertEqual(
  960. datetime.datetime(2009, 12, 31, 20, 50),
  961. form5.cleaned_data["datetime_field"],
  962. )
  963. self.assertEqual(datetime.time(20, 50), form5.cleaned_data["time_field"])
  964. self.assertEqual(1234, form5.cleaned_data["integer_field"])
  965. form6 = SelectDateForm(
  966. {
  967. "date_field_month": "12",
  968. "date_field_day": "31",
  969. "date_field_year": "2009",
  970. }
  971. )
  972. self.assertTrue(form6.is_valid())
  973. self.assertEqual(
  974. datetime.date(2009, 12, 31), form6.cleaned_data["date_field"]
  975. )
  976. self.assertHTMLEqual(
  977. '<select name="mydate_month" id="id_mydate_month">'
  978. '<option value="">---</option>'
  979. '<option value="1">January</option>'
  980. '<option value="2">February</option>'
  981. '<option value="3">March</option>'
  982. '<option value="4">April</option>'
  983. '<option value="5">May</option>'
  984. '<option value="6">June</option>'
  985. '<option value="7">July</option>'
  986. '<option value="8">August</option>'
  987. '<option value="9">September</option>'
  988. '<option value="10">October</option>'
  989. '<option value="11">November</option>'
  990. '<option value="12" selected>December</option>'
  991. "</select>"
  992. '<select name="mydate_day" id="id_mydate_day">'
  993. '<option value="">---</option>'
  994. '<option value="1">1</option>'
  995. '<option value="2">2</option>'
  996. '<option value="3">3</option>'
  997. '<option value="4">4</option>'
  998. '<option value="5">5</option>'
  999. '<option value="6">6</option>'
  1000. '<option value="7">7</option>'
  1001. '<option value="8">8</option>'
  1002. '<option value="9">9</option>'
  1003. '<option value="10">10</option>'
  1004. '<option value="11">11</option>'
  1005. '<option value="12">12</option>'
  1006. '<option value="13">13</option>'
  1007. '<option value="14">14</option>'
  1008. '<option value="15">15</option>'
  1009. '<option value="16">16</option>'
  1010. '<option value="17">17</option>'
  1011. '<option value="18">18</option>'
  1012. '<option value="19">19</option>'
  1013. '<option value="20">20</option>'
  1014. '<option value="21">21</option>'
  1015. '<option value="22">22</option>'
  1016. '<option value="23">23</option>'
  1017. '<option value="24">24</option>'
  1018. '<option value="25">25</option>'
  1019. '<option value="26">26</option>'
  1020. '<option value="27">27</option>'
  1021. '<option value="28">28</option>'
  1022. '<option value="29">29</option>'
  1023. '<option value="30">30</option>'
  1024. '<option value="31" selected>31</option>'
  1025. "</select>"
  1026. '<select name="mydate_year" id="id_mydate_year">'
  1027. '<option value="">---</option>'
  1028. '<option value="2009" selected>2009</option>'
  1029. '<option value="2010">2010</option>'
  1030. '<option value="2011">2011</option>'
  1031. '<option value="2012">2012</option>'
  1032. '<option value="2013">2013</option>'
  1033. '<option value="2014">2014</option>'
  1034. '<option value="2015">2015</option>'
  1035. '<option value="2016">2016</option>'
  1036. '<option value="2017">2017</option>'
  1037. '<option value="2018">2018</option>'
  1038. "</select>",
  1039. forms.SelectDateWidget(years=range(2009, 2019)).render(
  1040. "mydate", datetime.date(2009, 12, 31)
  1041. ),
  1042. )
  1043. def test_sub_locales(self):
  1044. """
  1045. Check if sublocales fall back to the main locale
  1046. """
  1047. with self.settings(USE_THOUSAND_SEPARATOR=True):
  1048. with translation.override("de-at", deactivate=True):
  1049. self.assertEqual("66.666,666", Template("{{ n }}").render(self.ctxt))
  1050. with translation.override("es-us", deactivate=True):
  1051. self.assertEqual("31 de diciembre de 2009", date_format(self.d))
  1052. def test_localized_input(self):
  1053. """
  1054. Tests if form input is correctly localized
  1055. """
  1056. self.maxDiff = 1200
  1057. with translation.override("de-at", deactivate=True):
  1058. form6 = CompanyForm(
  1059. {
  1060. "name": "acme",
  1061. "date_added": datetime.datetime(2009, 12, 31, 6, 0, 0),
  1062. "cents_paid": decimal.Decimal("59.47"),
  1063. "products_delivered": 12000,
  1064. }
  1065. )
  1066. self.assertTrue(form6.is_valid())
  1067. self.assertHTMLEqual(
  1068. form6.as_ul(),
  1069. '<li><label for="id_name">Name:</label>'
  1070. '<input id="id_name" type="text" name="name" value="acme" '
  1071. ' maxlength="50" required></li>'
  1072. '<li><label for="id_date_added">Date added:</label>'
  1073. '<input type="text" name="date_added" value="31.12.2009 06:00:00" '
  1074. ' id="id_date_added" required></li>'
  1075. '<li><label for="id_cents_paid">Cents paid:</label>'
  1076. '<input type="text" name="cents_paid" value="59,47" id="id_cents_paid" '
  1077. " required></li>"
  1078. '<li><label for="id_products_delivered">Products delivered:</label>'
  1079. '<input type="text" name="products_delivered" value="12000" '
  1080. ' id="id_products_delivered" required>'
  1081. "</li>",
  1082. )
  1083. self.assertEqual(
  1084. localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)),
  1085. "31.12.2009 06:00:00",
  1086. )
  1087. self.assertEqual(
  1088. datetime.datetime(2009, 12, 31, 6, 0, 0),
  1089. form6.cleaned_data["date_added"],
  1090. )
  1091. with self.settings(USE_THOUSAND_SEPARATOR=True):
  1092. # Checking for the localized "products_delivered" field
  1093. self.assertInHTML(
  1094. '<input type="text" name="products_delivered" '
  1095. 'value="12.000" id="id_products_delivered" required>',
  1096. form6.as_ul(),
  1097. )
  1098. def test_localized_input_func(self):
  1099. tests = (
  1100. (True, "True"),
  1101. (datetime.date(1, 1, 1), "0001-01-01"),
  1102. (datetime.datetime(1, 1, 1), "0001-01-01 00:00:00"),
  1103. )
  1104. with self.settings(USE_THOUSAND_SEPARATOR=True):
  1105. for value, expected in tests:
  1106. with self.subTest(value=value):
  1107. self.assertEqual(localize_input(value), expected)
  1108. def test_sanitize_strftime_format(self):
  1109. for year in (1, 99, 999, 1000):
  1110. dt = datetime.date(year, 1, 1)
  1111. for fmt, expected in [
  1112. ("%C", "%02d" % (year // 100)),
  1113. ("%F", "%04d-01-01" % year),
  1114. ("%G", "%04d" % year),
  1115. ("%Y", "%04d" % year),
  1116. ]:
  1117. with self.subTest(year=year, fmt=fmt):
  1118. fmt = sanitize_strftime_format(fmt)
  1119. self.assertEqual(dt.strftime(fmt), expected)
  1120. def test_sanitize_strftime_format_with_escaped_percent(self):
  1121. dt = datetime.date(1, 1, 1)
  1122. for fmt, expected in [
  1123. ("%%C", "%C"),
  1124. ("%%F", "%F"),
  1125. ("%%G", "%G"),
  1126. ("%%Y", "%Y"),
  1127. ("%%%%C", "%%C"),
  1128. ("%%%%F", "%%F"),
  1129. ("%%%%G", "%%G"),
  1130. ("%%%%Y", "%%Y"),
  1131. ]:
  1132. with self.subTest(fmt=fmt):
  1133. fmt = sanitize_strftime_format(fmt)
  1134. self.assertEqual(dt.strftime(fmt), expected)
  1135. for year in (1, 99, 999, 1000):
  1136. dt = datetime.date(year, 1, 1)
  1137. for fmt, expected in [
  1138. ("%%%C", "%%%02d" % (year // 100)),
  1139. ("%%%F", "%%%04d-01-01" % year),
  1140. ("%%%G", "%%%04d" % year),
  1141. ("%%%Y", "%%%04d" % year),
  1142. ("%%%%%C", "%%%%%02d" % (year // 100)),
  1143. ("%%%%%F", "%%%%%04d-01-01" % year),
  1144. ("%%%%%G", "%%%%%04d" % year),
  1145. ("%%%%%Y", "%%%%%04d" % year),
  1146. ]:
  1147. with self.subTest(year=year, fmt=fmt):
  1148. fmt = sanitize_strftime_format(fmt)
  1149. self.assertEqual(dt.strftime(fmt), expected)
  1150. def test_sanitize_separators(self):
  1151. """
  1152. Tests django.utils.formats.sanitize_separators.
  1153. """
  1154. # Non-strings are untouched
  1155. self.assertEqual(sanitize_separators(123), 123)
  1156. with translation.override("ru", deactivate=True):
  1157. # Russian locale has non-breaking space (\xa0) as thousand separator
  1158. # Usual space is accepted too when sanitizing inputs
  1159. with self.settings(USE_THOUSAND_SEPARATOR=True):
  1160. self.assertEqual(sanitize_separators("1\xa0234\xa0567"), "1234567")
  1161. self.assertEqual(sanitize_separators("77\xa0777,777"), "77777.777")
  1162. self.assertEqual(sanitize_separators("12 345"), "12345")
  1163. self.assertEqual(sanitize_separators("77 777,777"), "77777.777")
  1164. with translation.override(None):
  1165. with self.settings(USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="."):
  1166. self.assertEqual(sanitize_separators("12\xa0345"), "12\xa0345")
  1167. with self.settings(USE_THOUSAND_SEPARATOR=True):
  1168. with patch_formats(
  1169. get_language(), THOUSAND_SEPARATOR=".", DECIMAL_SEPARATOR=","
  1170. ):
  1171. self.assertEqual(sanitize_separators("10.234"), "10234")
  1172. # Suspicion that user entered dot as decimal separator (#22171)
  1173. self.assertEqual(sanitize_separators("10.10"), "10.10")
  1174. with translation.override(None):
  1175. with self.settings(DECIMAL_SEPARATOR=","):
  1176. self.assertEqual(sanitize_separators("1001,10"), "1001.10")
  1177. self.assertEqual(sanitize_separators("1001.10"), "1001.10")
  1178. with self.settings(
  1179. DECIMAL_SEPARATOR=",",
  1180. THOUSAND_SEPARATOR=".",
  1181. USE_THOUSAND_SEPARATOR=True,
  1182. ):
  1183. self.assertEqual(sanitize_separators("1.001,10"), "1001.10")
  1184. self.assertEqual(sanitize_separators("1001,10"), "1001.10")
  1185. self.assertEqual(sanitize_separators("1001.10"), "1001.10")
  1186. # Invalid output.
  1187. self.assertEqual(sanitize_separators("1,001.10"), "1.001.10")
  1188. def test_iter_format_modules(self):
  1189. """
  1190. Tests the iter_format_modules function.
  1191. """
  1192. # Importing some format modules so that we can compare the returned
  1193. # modules with these expected modules
  1194. default_mod = import_module("django.conf.locale.de.formats")
  1195. test_mod = import_module("i18n.other.locale.de.formats")
  1196. test_mod2 = import_module("i18n.other2.locale.de.formats")
  1197. with translation.override("de-at", deactivate=True):
  1198. # Should return the correct default module when no setting is set
  1199. self.assertEqual(list(iter_format_modules("de")), [default_mod])
  1200. # When the setting is a string, should return the given module and
  1201. # the default module
  1202. self.assertEqual(
  1203. list(iter_format_modules("de", "i18n.other.locale")),
  1204. [test_mod, default_mod],
  1205. )
  1206. # When setting is a list of strings, should return the given
  1207. # modules and the default module
  1208. self.assertEqual(
  1209. list(
  1210. iter_format_modules(
  1211. "de", ["i18n.other.locale", "i18n.other2.locale"]
  1212. )
  1213. ),
  1214. [test_mod, test_mod2, default_mod],
  1215. )
  1216. def test_iter_format_modules_stability(self):
  1217. """
  1218. Tests the iter_format_modules function always yields format modules in
  1219. a stable and correct order in presence of both base ll and ll_CC formats.
  1220. """
  1221. en_format_mod = import_module("django.conf.locale.en.formats")
  1222. en_gb_format_mod = import_module("django.conf.locale.en_GB.formats")
  1223. self.assertEqual(
  1224. list(iter_format_modules("en-gb")), [en_gb_format_mod, en_format_mod]
  1225. )
  1226. def test_get_format_modules_lang(self):
  1227. with translation.override("de", deactivate=True):
  1228. self.assertEqual(".", get_format("DECIMAL_SEPARATOR", lang="en"))
  1229. def test_get_format_lazy_format(self):
  1230. self.assertEqual(get_format(gettext_lazy("DATE_FORMAT")), "N j, Y")
  1231. def test_localize_templatetag_and_filter(self):
  1232. """
  1233. Test the {% localize %} templatetag and the localize/unlocalize filters.
  1234. """
  1235. context = Context(
  1236. {"int": 1455, "float": 3.14, "date": datetime.date(2016, 12, 31)}
  1237. )
  1238. template1 = Template(
  1239. "{% load l10n %}{% localize %}"
  1240. "{{ int }}/{{ float }}/{{ date }}{% endlocalize %}; "
  1241. "{% localize on %}{{ int }}/{{ float }}/{{ date }}{% endlocalize %}"
  1242. )
  1243. template2 = Template(
  1244. "{% load l10n %}{{ int }}/{{ float }}/{{ date }}; "
  1245. "{% localize off %}{{ int }}/{{ float }}/{{ date }};{% endlocalize %} "
  1246. "{{ int }}/{{ float }}/{{ date }}"
  1247. )
  1248. template3 = Template(
  1249. "{% load l10n %}{{ int }}/{{ float }}/{{ date }}; "
  1250. "{{ int|unlocalize }}/{{ float|unlocalize }}/{{ date|unlocalize }}"
  1251. )
  1252. expected_localized = "1.455/3,14/31. Dezember 2016"
  1253. expected_unlocalized = "1455/3.14/Dez. 31, 2016"
  1254. output1 = "; ".join([expected_localized, expected_localized])
  1255. output2 = "; ".join(
  1256. [expected_localized, expected_unlocalized, expected_localized]
  1257. )
  1258. output3 = "; ".join([expected_localized, expected_unlocalized])
  1259. with translation.override("de", deactivate=True):
  1260. with self.settings(USE_THOUSAND_SEPARATOR=True):
  1261. self.assertEqual(template1.render(context), output1)
  1262. self.assertEqual(template2.render(context), output2)
  1263. self.assertEqual(template3.render(context), output3)
  1264. def test_localized_off_numbers(self):
  1265. """A string representation is returned for unlocalized numbers."""
  1266. template = Template(
  1267. "{% load l10n %}{% localize off %}"
  1268. "{{ int }}/{{ float }}/{{ decimal }}{% endlocalize %}"
  1269. )
  1270. context = Context(
  1271. {"int": 1455, "float": 3.14, "decimal": decimal.Decimal("24.1567")}
  1272. )
  1273. with self.settings(
  1274. DECIMAL_SEPARATOR=",",
  1275. USE_THOUSAND_SEPARATOR=True,
  1276. THOUSAND_SEPARATOR="°",
  1277. NUMBER_GROUPING=2,
  1278. ):
  1279. self.assertEqual(template.render(context), "1455/3.14/24.1567")
  1280. def test_localized_as_text_as_hidden_input(self):
  1281. """
  1282. Form input with 'as_hidden' or 'as_text' is correctly localized.
  1283. """
  1284. self.maxDiff = 1200
  1285. with translation.override("de-at", deactivate=True):
  1286. template = Template(
  1287. "{% load l10n %}{{ form.date_added }}; {{ form.cents_paid }}"
  1288. )
  1289. template_as_text = Template(
  1290. "{% load l10n %}"
  1291. "{{ form.date_added.as_text }}; {{ form.cents_paid.as_text }}"
  1292. )
  1293. template_as_hidden = Template(
  1294. "{% load l10n %}"
  1295. "{{ form.date_added.as_hidden }}; {{ form.cents_paid.as_hidden }}"
  1296. )
  1297. form = CompanyForm(
  1298. {
  1299. "name": "acme",
  1300. "date_added": datetime.datetime(2009, 12, 31, 6, 0, 0),
  1301. "cents_paid": decimal.Decimal("59.47"),
  1302. "products_delivered": 12000,
  1303. }
  1304. )
  1305. context = Context({"form": form})
  1306. self.assertTrue(form.is_valid())
  1307. self.assertHTMLEqual(
  1308. template.render(context),
  1309. '<input id="id_date_added" name="date_added" type="text" '
  1310. 'value="31.12.2009 06:00:00" required>;'
  1311. '<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" '
  1312. "required>",
  1313. )
  1314. self.assertHTMLEqual(
  1315. template_as_text.render(context),
  1316. '<input id="id_date_added" name="date_added" type="text" '
  1317. 'value="31.12.2009 06:00:00" required>;'
  1318. '<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" '
  1319. "required>",
  1320. )
  1321. self.assertHTMLEqual(
  1322. template_as_hidden.render(context),
  1323. '<input id="id_date_added" name="date_added" type="hidden" '
  1324. 'value="31.12.2009 06:00:00">;'
  1325. '<input id="id_cents_paid" name="cents_paid" type="hidden" '
  1326. 'value="59,47">',
  1327. )
  1328. def test_format_arbitrary_settings(self):
  1329. self.assertEqual(get_format("DEBUG"), "DEBUG")
  1330. def test_get_custom_format(self):
  1331. reset_format_cache()
  1332. with self.settings(FORMAT_MODULE_PATH="i18n.other.locale"):
  1333. with translation.override("fr", deactivate=True):
  1334. self.assertEqual("d/m/Y CUSTOM", get_format("CUSTOM_DAY_FORMAT"))
  1335. def test_admin_javascript_supported_input_formats(self):
  1336. """
  1337. The first input format for DATE_INPUT_FORMATS, TIME_INPUT_FORMATS, and
  1338. DATETIME_INPUT_FORMATS must not contain %f since that's unsupported by
  1339. the admin's time picker widget.
  1340. """
  1341. regex = re.compile("%([^BcdHImMpSwxXyY%])")
  1342. for language_code, language_name in settings.LANGUAGES:
  1343. for format_name in (
  1344. "DATE_INPUT_FORMATS",
  1345. "TIME_INPUT_FORMATS",
  1346. "DATETIME_INPUT_FORMATS",
  1347. ):
  1348. with self.subTest(language=language_code, format=format_name):
  1349. formatter = get_format(format_name, lang=language_code)[0]
  1350. self.assertEqual(
  1351. regex.findall(formatter),
  1352. [],
  1353. "%s locale's %s uses an unsupported format code."
  1354. % (language_code, format_name),
  1355. )
  1356. class MiscTests(SimpleTestCase):
  1357. rf = RequestFactory()
  1358. @override_settings(LANGUAGE_CODE="de")
  1359. def test_english_fallback(self):
  1360. """
  1361. With a non-English LANGUAGE_CODE and if the active language is English
  1362. or one of its variants, the untranslated string should be returned
  1363. (instead of falling back to LANGUAGE_CODE) (See #24413).
  1364. """
  1365. self.assertEqual(gettext("Image"), "Bild")
  1366. with translation.override("en"):
  1367. self.assertEqual(gettext("Image"), "Image")
  1368. with translation.override("en-us"):
  1369. self.assertEqual(gettext("Image"), "Image")
  1370. with translation.override("en-ca"):
  1371. self.assertEqual(gettext("Image"), "Image")
  1372. def test_parse_spec_http_header(self):
  1373. """
  1374. Testing HTTP header parsing. First, we test that we can parse the
  1375. values according to the spec (and that we extract all the pieces in
  1376. the right order).
  1377. """
  1378. tests = [
  1379. # Good headers
  1380. ("de", [("de", 1.0)]),
  1381. ("en-AU", [("en-au", 1.0)]),
  1382. ("es-419", [("es-419", 1.0)]),
  1383. ("*;q=1.00", [("*", 1.0)]),
  1384. ("en-AU;q=0.123", [("en-au", 0.123)]),
  1385. ("en-au;q=0.5", [("en-au", 0.5)]),
  1386. ("en-au;q=1.0", [("en-au", 1.0)]),
  1387. ("da, en-gb;q=0.25, en;q=0.5", [("da", 1.0), ("en", 0.5), ("en-gb", 0.25)]),
  1388. ("en-au-xx", [("en-au-xx", 1.0)]),
  1389. (
  1390. "de,en-au;q=0.75,en-us;q=0.5,en;q=0.25,es;q=0.125,fa;q=0.125",
  1391. [
  1392. ("de", 1.0),
  1393. ("en-au", 0.75),
  1394. ("en-us", 0.5),
  1395. ("en", 0.25),
  1396. ("es", 0.125),
  1397. ("fa", 0.125),
  1398. ],
  1399. ),
  1400. ("*", [("*", 1.0)]),
  1401. ("de;q=0.", [("de", 0.0)]),
  1402. ("en; q=1,", [("en", 1.0)]),
  1403. ("en; q=1.0, * ; q=0.5", [("en", 1.0), ("*", 0.5)]),
  1404. (
  1405. "en" + "-x" * 20,
  1406. [("en-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x", 1.0)],
  1407. ),
  1408. (
  1409. ", ".join(["en; q=1.0"] * 20),
  1410. [("en", 1.0)] * 20,
  1411. ),
  1412. # Bad headers
  1413. ("en-gb;q=1.0000", []),
  1414. ("en;q=0.1234", []),
  1415. ("en;q=.2", []),
  1416. ("abcdefghi-au", []),
  1417. ("**", []),
  1418. ("en,,gb", []),
  1419. ("en-au;q=0.1.0", []),
  1420. (("X" * 97) + "Z,en", []),
  1421. ("da, en-gb;q=0.8, en;q=0.7,#", []),
  1422. ("de;q=2.0", []),
  1423. ("de;q=0.a", []),
  1424. ("12-345", []),
  1425. ("", []),
  1426. ("en;q=1e0", []),
  1427. ("en-au;q=1.0", []),
  1428. # Invalid as language-range value too long.
  1429. ("xxxxxxxx" + "-xxxxxxxx" * 500, []),
  1430. # Header value too long, only parse up to limit.
  1431. (", ".join(["en; q=1.0"] * 500), [("en", 1.0)] * 45),
  1432. ]
  1433. for value, expected in tests:
  1434. with self.subTest(value=value):
  1435. self.assertEqual(
  1436. trans_real.parse_accept_lang_header(value), tuple(expected)
  1437. )
  1438. def test_parse_literal_http_header(self):
  1439. tests = [
  1440. ("pt-br", "pt-br"),
  1441. ("pt", "pt"),
  1442. ("es,de", "es"),
  1443. ("es-a,de", "es"),
  1444. # There isn't a Django translation to a US variation of the Spanish
  1445. # language, a safe assumption. When the user sets it as the
  1446. # preferred language, the main 'es' translation should be selected
  1447. # instead.
  1448. ("es-us", "es"),
  1449. # There isn't a main language (zh) translation of Django but there
  1450. # is a translation to variation (zh-hans) the user sets zh-hans as
  1451. # the preferred language, it should be selected without falling
  1452. # back nor ignoring it.
  1453. ("zh-hans,de", "zh-hans"),
  1454. ("NL", "nl"),
  1455. ("fy", "fy"),
  1456. ("ia", "ia"),
  1457. ("sr-latn", "sr-latn"),
  1458. ("zh-hans", "zh-hans"),
  1459. ("zh-hant", "zh-hant"),
  1460. ]
  1461. for header, expected in tests:
  1462. with self.subTest(header=header):
  1463. request = self.rf.get("/", headers={"accept-language": header})
  1464. self.assertEqual(get_language_from_request(request), expected)
  1465. @override_settings(
  1466. LANGUAGES=[
  1467. ("en", "English"),
  1468. ("zh-hans", "Simplified Chinese"),
  1469. ("zh-hant", "Traditional Chinese"),
  1470. ]
  1471. )
  1472. def test_support_for_deprecated_chinese_language_codes(self):
  1473. """
  1474. Some browsers (Firefox, IE, etc.) use deprecated language codes. As these
  1475. language codes will be removed in Django 1.9, these will be incorrectly
  1476. matched. For example zh-tw (traditional) will be interpreted as zh-hans
  1477. (simplified), which is wrong. So we should also accept these deprecated
  1478. language codes.
  1479. refs #18419 -- this is explicitly for browser compatibility
  1480. """
  1481. g = get_language_from_request
  1482. request = self.rf.get("/", headers={"accept-language": "zh-cn,en"})
  1483. self.assertEqual(g(request), "zh-hans")
  1484. request = self.rf.get("/", headers={"accept-language": "zh-tw,en"})
  1485. self.assertEqual(g(request), "zh-hant")
  1486. def test_special_fallback_language(self):
  1487. """
  1488. Some languages may have special fallbacks that don't follow the simple
  1489. 'fr-ca' -> 'fr' logic (notably Chinese codes).
  1490. """
  1491. request = self.rf.get("/", headers={"accept-language": "zh-my,en"})
  1492. self.assertEqual(get_language_from_request(request), "zh-hans")
  1493. def test_subsequent_code_fallback_language(self):
  1494. """
  1495. Subsequent language codes should be used when the language code is not
  1496. supported.
  1497. """
  1498. tests = [
  1499. ("zh-Hans-CN", "zh-hans"),
  1500. ("zh-hans-mo", "zh-hans"),
  1501. ("zh-hans-HK", "zh-hans"),
  1502. ("zh-Hant-HK", "zh-hant"),
  1503. ("zh-hant-tw", "zh-hant"),
  1504. ("zh-hant-SG", "zh-hant"),
  1505. ]
  1506. for value, expected in tests:
  1507. with self.subTest(value=value):
  1508. request = self.rf.get("/", headers={"accept-language": f"{value},en"})
  1509. self.assertEqual(get_language_from_request(request), expected)
  1510. def test_parse_language_cookie(self):
  1511. g = get_language_from_request
  1512. request = self.rf.get("/")
  1513. request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "pt-br"
  1514. self.assertEqual("pt-br", g(request))
  1515. request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "pt"
  1516. self.assertEqual("pt", g(request))
  1517. request = self.rf.get("/", headers={"accept-language": "de"})
  1518. request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "es"
  1519. self.assertEqual("es", g(request))
  1520. # There isn't a Django translation to a US variation of the Spanish
  1521. # language, a safe assumption. When the user sets it as the preferred
  1522. # language, the main 'es' translation should be selected instead.
  1523. request = self.rf.get("/")
  1524. request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "es-us"
  1525. self.assertEqual(g(request), "es")
  1526. # There isn't a main language (zh) translation of Django but there is a
  1527. # translation to variation (zh-hans) the user sets zh-hans as the
  1528. # preferred language, it should be selected without falling back nor
  1529. # ignoring it.
  1530. request = self.rf.get("/", headers={"accept-language": "de"})
  1531. request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "zh-hans"
  1532. self.assertEqual(g(request), "zh-hans")
  1533. @override_settings(
  1534. USE_I18N=True,
  1535. LANGUAGES=[
  1536. ("en", "English"),
  1537. ("ar-dz", "Algerian Arabic"),
  1538. ("de", "German"),
  1539. ("de-at", "Austrian German"),
  1540. ("pt-BR", "Portuguese (Brazil)"),
  1541. ],
  1542. )
  1543. def test_get_supported_language_variant_real(self):
  1544. g = trans_real.get_supported_language_variant
  1545. self.assertEqual(g("en"), "en")
  1546. self.assertEqual(g("en-gb"), "en")
  1547. self.assertEqual(g("de"), "de")
  1548. self.assertEqual(g("de-at"), "de-at")
  1549. self.assertEqual(g("de-ch"), "de")
  1550. self.assertEqual(g("pt-br"), "pt-br")
  1551. self.assertEqual(g("pt-BR"), "pt-BR")
  1552. self.assertEqual(g("pt"), "pt-br")
  1553. self.assertEqual(g("pt-pt"), "pt-br")
  1554. self.assertEqual(g("ar-dz"), "ar-dz")
  1555. self.assertEqual(g("ar-DZ"), "ar-DZ")
  1556. with self.assertRaises(LookupError):
  1557. g("pt", strict=True)
  1558. with self.assertRaises(LookupError):
  1559. g("pt-pt", strict=True)
  1560. with self.assertRaises(LookupError):
  1561. g("xyz")
  1562. with self.assertRaises(LookupError):
  1563. g("xy-zz")
  1564. with self.assertRaises(LookupError):
  1565. g("x" * LANGUAGE_CODE_MAX_LENGTH)
  1566. with self.assertRaises(LookupError):
  1567. g("x" * (LANGUAGE_CODE_MAX_LENGTH + 1))
  1568. # 167 * 3 = 501 which is LANGUAGE_CODE_MAX_LENGTH + 1.
  1569. self.assertEqual(g("en-" * 167), "en")
  1570. with self.assertRaises(LookupError):
  1571. g("en-" * 167, strict=True)
  1572. self.assertEqual(g("en-" * 30000), "en") # catastrophic test
  1573. def test_get_supported_language_variant_null(self):
  1574. g = trans_null.get_supported_language_variant
  1575. self.assertEqual(g(settings.LANGUAGE_CODE), settings.LANGUAGE_CODE)
  1576. with self.assertRaises(LookupError):
  1577. g("pt")
  1578. with self.assertRaises(LookupError):
  1579. g("de")
  1580. with self.assertRaises(LookupError):
  1581. g("de-at")
  1582. with self.assertRaises(LookupError):
  1583. g("de", strict=True)
  1584. with self.assertRaises(LookupError):
  1585. g("de-at", strict=True)
  1586. with self.assertRaises(LookupError):
  1587. g("xyz")
  1588. @override_settings(
  1589. LANGUAGES=[
  1590. ("en", "English"),
  1591. ("en-latn-us", "Latin English"),
  1592. ("de", "German"),
  1593. ("de-1996", "German, orthography of 1996"),
  1594. ("de-at", "Austrian German"),
  1595. ("de-ch-1901", "German, Swiss variant, traditional orthography"),
  1596. ("i-mingo", "Mingo"),
  1597. ("kl-tunumiit", "Tunumiisiut"),
  1598. ("nan-hani-tw", "Hanji"),
  1599. ("pl", "Polish"),
  1600. ],
  1601. )
  1602. def test_get_language_from_path_real(self):
  1603. g = trans_real.get_language_from_path
  1604. tests = [
  1605. ("/pl/", "pl"),
  1606. ("/pl", "pl"),
  1607. ("/xyz/", None),
  1608. ("/en/", "en"),
  1609. ("/en-gb/", "en"),
  1610. ("/en-latn-us/", "en-latn-us"),
  1611. ("/en-Latn-US/", "en-Latn-US"),
  1612. ("/de/", "de"),
  1613. ("/de-1996/", "de-1996"),
  1614. ("/de-at/", "de-at"),
  1615. ("/de-AT/", "de-AT"),
  1616. ("/de-ch/", "de"),
  1617. ("/de-ch-1901/", "de-ch-1901"),
  1618. ("/de-simple-page-test/", None),
  1619. ("/i-mingo/", "i-mingo"),
  1620. ("/kl-tunumiit/", "kl-tunumiit"),
  1621. ("/nan-hani-tw/", "nan-hani-tw"),
  1622. (f"/{'a' * 501}/", None),
  1623. ]
  1624. for path, language in tests:
  1625. with self.subTest(path=path):
  1626. self.assertEqual(g(path), language)
  1627. def test_get_language_from_path_null(self):
  1628. g = trans_null.get_language_from_path
  1629. self.assertIsNone(g("/pl/"))
  1630. self.assertIsNone(g("/pl"))
  1631. self.assertIsNone(g("/xyz/"))
  1632. def test_cache_resetting(self):
  1633. """
  1634. After setting LANGUAGE, the cache should be cleared and languages
  1635. previously valid should not be used (#14170).
  1636. """
  1637. g = get_language_from_request
  1638. request = self.rf.get("/", headers={"accept-language": "pt-br"})
  1639. self.assertEqual("pt-br", g(request))
  1640. with self.settings(LANGUAGES=[("en", "English")]):
  1641. self.assertNotEqual("pt-br", g(request))
  1642. def test_i18n_patterns_returns_list(self):
  1643. with override_settings(USE_I18N=False):
  1644. self.assertIsInstance(i18n_patterns([]), list)
  1645. with override_settings(USE_I18N=True):
  1646. self.assertIsInstance(i18n_patterns([]), list)
  1647. class ResolutionOrderI18NTests(SimpleTestCase):
  1648. def setUp(self):
  1649. super().setUp()
  1650. activate("de")
  1651. def tearDown(self):
  1652. deactivate()
  1653. super().tearDown()
  1654. def assertGettext(self, msgid, msgstr):
  1655. result = gettext(msgid)
  1656. self.assertIn(
  1657. msgstr,
  1658. result,
  1659. "The string '%s' isn't in the translation of '%s'; the actual result is "
  1660. "'%s'." % (msgstr, msgid, result),
  1661. )
  1662. class AppResolutionOrderI18NTests(ResolutionOrderI18NTests):
  1663. @override_settings(LANGUAGE_CODE="de")
  1664. def test_app_translation(self):
  1665. # Original translation.
  1666. self.assertGettext("Date/time", "Datum/Zeit")
  1667. # Different translation.
  1668. with self.modify_settings(INSTALLED_APPS={"append": "i18n.resolution"}):
  1669. # Force refreshing translations.
  1670. activate("de")
  1671. # Doesn't work because it's added later in the list.
  1672. self.assertGettext("Date/time", "Datum/Zeit")
  1673. with self.modify_settings(
  1674. INSTALLED_APPS={"remove": "django.contrib.admin.apps.SimpleAdminConfig"}
  1675. ):
  1676. # Force refreshing translations.
  1677. activate("de")
  1678. # Unless the original is removed from the list.
  1679. self.assertGettext("Date/time", "Datum/Zeit (APP)")
  1680. @override_settings(LOCALE_PATHS=extended_locale_paths)
  1681. class LocalePathsResolutionOrderI18NTests(ResolutionOrderI18NTests):
  1682. def test_locale_paths_translation(self):
  1683. self.assertGettext("Time", "LOCALE_PATHS")
  1684. def test_locale_paths_override_app_translation(self):
  1685. with self.settings(INSTALLED_APPS=["i18n.resolution"]):
  1686. self.assertGettext("Time", "LOCALE_PATHS")
  1687. class DjangoFallbackResolutionOrderI18NTests(ResolutionOrderI18NTests):
  1688. def test_django_fallback(self):
  1689. self.assertEqual(gettext("Date/time"), "Datum/Zeit")
  1690. @override_settings(INSTALLED_APPS=["i18n.territorial_fallback"])
  1691. class TranslationFallbackI18NTests(ResolutionOrderI18NTests):
  1692. def test_sparse_territory_catalog(self):
  1693. """
  1694. Untranslated strings for territorial language variants use the
  1695. translations of the generic language. In this case, the de-de
  1696. translation falls back to de.
  1697. """
  1698. with translation.override("de-de"):
  1699. self.assertGettext("Test 1 (en)", "(de-de)")
  1700. self.assertGettext("Test 2 (en)", "(de)")
  1701. class TestModels(TestCase):
  1702. def test_lazy(self):
  1703. tm = TestModel()
  1704. tm.save()
  1705. def test_safestr(self):
  1706. c = Company(cents_paid=12, products_delivered=1)
  1707. c.name = SafeString("Iñtërnâtiônàlizætiøn1")
  1708. c.save()
  1709. class TestLanguageInfo(SimpleTestCase):
  1710. def test_localized_language_info(self):
  1711. li = get_language_info("de")
  1712. self.assertEqual(li["code"], "de")
  1713. self.assertEqual(li["name_local"], "Deutsch")
  1714. self.assertEqual(li["name"], "German")
  1715. self.assertIs(li["bidi"], False)
  1716. def test_unknown_language_code(self):
  1717. with self.assertRaisesMessage(KeyError, "Unknown language code xx"):
  1718. get_language_info("xx")
  1719. with translation.override("xx"):
  1720. # A language with no translation catalogs should fallback to the
  1721. # untranslated string.
  1722. self.assertEqual(gettext("Title"), "Title")
  1723. def test_unknown_only_country_code(self):
  1724. li = get_language_info("de-xx")
  1725. self.assertEqual(li["code"], "de")
  1726. self.assertEqual(li["name_local"], "Deutsch")
  1727. self.assertEqual(li["name"], "German")
  1728. self.assertIs(li["bidi"], False)
  1729. def test_unknown_language_code_and_country_code(self):
  1730. with self.assertRaisesMessage(KeyError, "Unknown language code xx-xx and xx"):
  1731. get_language_info("xx-xx")
  1732. def test_fallback_language_code(self):
  1733. """
  1734. get_language_info return the first fallback language info if the lang_info
  1735. struct does not contain the 'name' key.
  1736. """
  1737. li = get_language_info("zh-my")
  1738. self.assertEqual(li["code"], "zh-hans")
  1739. li = get_language_info("zh-hans")
  1740. self.assertEqual(li["code"], "zh-hans")
  1741. @override_settings(
  1742. USE_I18N=True,
  1743. LANGUAGES=[
  1744. ("en", "English"),
  1745. ("fr", "French"),
  1746. ],
  1747. MIDDLEWARE=[
  1748. "django.middleware.locale.LocaleMiddleware",
  1749. "django.middleware.common.CommonMiddleware",
  1750. ],
  1751. ROOT_URLCONF="i18n.urls",
  1752. )
  1753. class LocaleMiddlewareTests(TestCase):
  1754. def test_streaming_response(self):
  1755. # Regression test for #5241
  1756. response = self.client.get("/fr/streaming/")
  1757. self.assertContains(response, "Oui/Non")
  1758. response = self.client.get("/en/streaming/")
  1759. self.assertContains(response, "Yes/No")
  1760. @override_settings(
  1761. USE_I18N=True,
  1762. LANGUAGES=[
  1763. ("en", "English"),
  1764. ("de", "German"),
  1765. ("fr", "French"),
  1766. ],
  1767. MIDDLEWARE=[
  1768. "django.middleware.locale.LocaleMiddleware",
  1769. "django.middleware.common.CommonMiddleware",
  1770. ],
  1771. ROOT_URLCONF="i18n.urls_default_unprefixed",
  1772. LANGUAGE_CODE="en",
  1773. )
  1774. class UnprefixedDefaultLanguageTests(SimpleTestCase):
  1775. def test_default_lang_without_prefix(self):
  1776. """
  1777. With i18n_patterns(..., prefix_default_language=False), the default
  1778. language (settings.LANGUAGE_CODE) should be accessible without a prefix.
  1779. """
  1780. response = self.client.get("/simple/")
  1781. self.assertEqual(response.content, b"Yes")
  1782. @override_settings(LANGUAGE_CODE="en-us")
  1783. def test_default_lang_fallback_without_prefix(self):
  1784. response = self.client.get("/simple/")
  1785. self.assertEqual(response.status_code, 200)
  1786. self.assertEqual(response.content, b"Yes")
  1787. def test_other_lang_with_prefix(self):
  1788. response = self.client.get("/fr/simple/")
  1789. self.assertEqual(response.content, b"Oui")
  1790. def test_unprefixed_language_other_than_accept_language(self):
  1791. response = self.client.get("/simple/", HTTP_ACCEPT_LANGUAGE="fr")
  1792. self.assertEqual(response.content, b"Yes")
  1793. def test_page_with_dash(self):
  1794. # A page starting with /de* shouldn't match the 'de' language code.
  1795. response = self.client.get("/de-simple-page-test/")
  1796. self.assertEqual(response.content, b"Yes")
  1797. def test_no_redirect_on_404(self):
  1798. """
  1799. A request for a nonexistent URL shouldn't cause a redirect to
  1800. /<default_language>/<request_url> when prefix_default_language=False and
  1801. /<default_language>/<request_url> has a URL match (#27402).
  1802. """
  1803. # A match for /group1/group2/ must exist for this to act as a
  1804. # regression test.
  1805. response = self.client.get("/group1/group2/")
  1806. self.assertEqual(response.status_code, 200)
  1807. response = self.client.get("/nonexistent/")
  1808. self.assertEqual(response.status_code, 404)
  1809. @override_settings(
  1810. USE_I18N=True,
  1811. LANGUAGES=[
  1812. ("bg", "Bulgarian"),
  1813. ("en-us", "English"),
  1814. ("pt-br", "Portuguese (Brazil)"),
  1815. ],
  1816. MIDDLEWARE=[
  1817. "django.middleware.locale.LocaleMiddleware",
  1818. "django.middleware.common.CommonMiddleware",
  1819. ],
  1820. ROOT_URLCONF="i18n.urls",
  1821. )
  1822. class CountrySpecificLanguageTests(SimpleTestCase):
  1823. rf = RequestFactory()
  1824. def test_check_for_language(self):
  1825. self.assertTrue(check_for_language("en"))
  1826. self.assertTrue(check_for_language("en-us"))
  1827. self.assertTrue(check_for_language("en-US"))
  1828. self.assertFalse(check_for_language("en_US"))
  1829. self.assertTrue(check_for_language("be"))
  1830. self.assertTrue(check_for_language("be@latin"))
  1831. self.assertTrue(check_for_language("sr-RS@latin"))
  1832. self.assertTrue(check_for_language("sr-RS@12345"))
  1833. self.assertFalse(check_for_language("en-ü"))
  1834. self.assertFalse(check_for_language("en\x00"))
  1835. self.assertFalse(check_for_language(None))
  1836. self.assertFalse(check_for_language("be@ "))
  1837. # Specifying encoding is not supported (Django enforces UTF-8)
  1838. self.assertFalse(check_for_language("tr-TR.UTF-8"))
  1839. self.assertFalse(check_for_language("tr-TR.UTF8"))
  1840. self.assertFalse(check_for_language("de-DE.utf-8"))
  1841. def test_check_for_language_null(self):
  1842. self.assertIs(trans_null.check_for_language("en"), True)
  1843. def test_get_language_from_request(self):
  1844. # issue 19919
  1845. request = self.rf.get(
  1846. "/", headers={"accept-language": "en-US,en;q=0.8,bg;q=0.6,ru;q=0.4"}
  1847. )
  1848. lang = get_language_from_request(request)
  1849. self.assertEqual("en-us", lang)
  1850. request = self.rf.get(
  1851. "/", headers={"accept-language": "bg-bg,en-US;q=0.8,en;q=0.6,ru;q=0.4"}
  1852. )
  1853. lang = get_language_from_request(request)
  1854. self.assertEqual("bg", lang)
  1855. def test_get_language_from_request_code_too_long(self):
  1856. request = self.rf.get("/", headers={"accept-language": "a" * 501})
  1857. lang = get_language_from_request(request)
  1858. self.assertEqual("en-us", lang)
  1859. def test_get_language_from_request_null(self):
  1860. lang = trans_null.get_language_from_request(None)
  1861. self.assertEqual(lang, "en")
  1862. with override_settings(LANGUAGE_CODE="de"):
  1863. lang = trans_null.get_language_from_request(None)
  1864. self.assertEqual(lang, "de")
  1865. def test_specific_language_codes(self):
  1866. # issue 11915
  1867. request = self.rf.get(
  1868. "/", headers={"accept-language": "pt,en-US;q=0.8,en;q=0.6,ru;q=0.4"}
  1869. )
  1870. lang = get_language_from_request(request)
  1871. self.assertEqual("pt-br", lang)
  1872. request = self.rf.get(
  1873. "/", headers={"accept-language": "pt-pt,en-US;q=0.8,en;q=0.6,ru;q=0.4"}
  1874. )
  1875. lang = get_language_from_request(request)
  1876. self.assertEqual("pt-br", lang)
  1877. class TranslationFilesMissing(SimpleTestCase):
  1878. def setUp(self):
  1879. super().setUp()
  1880. self.gettext_find_builtin = gettext_module.find
  1881. def tearDown(self):
  1882. gettext_module.find = self.gettext_find_builtin
  1883. super().tearDown()
  1884. def patchGettextFind(self):
  1885. gettext_module.find = lambda *args, **kw: None
  1886. def test_failure_finding_default_mo_files(self):
  1887. """OSError is raised if the default language is unparseable."""
  1888. self.patchGettextFind()
  1889. trans_real._translations = {}
  1890. with self.assertRaises(OSError):
  1891. activate("en")
  1892. class NonDjangoLanguageTests(SimpleTestCase):
  1893. """
  1894. A language non present in default Django languages can still be
  1895. installed/used by a Django project.
  1896. """
  1897. @override_settings(
  1898. USE_I18N=True,
  1899. LANGUAGES=[
  1900. ("en-us", "English"),
  1901. ("xxx", "Somelanguage"),
  1902. ],
  1903. LANGUAGE_CODE="xxx",
  1904. LOCALE_PATHS=[os.path.join(here, "commands", "locale")],
  1905. )
  1906. def test_non_django_language(self):
  1907. self.assertEqual(get_language(), "xxx")
  1908. self.assertEqual(gettext("year"), "reay")
  1909. @override_settings(USE_I18N=True)
  1910. def test_check_for_language(self):
  1911. with tempfile.TemporaryDirectory() as app_dir:
  1912. os.makedirs(os.path.join(app_dir, "locale", "dummy_Lang", "LC_MESSAGES"))
  1913. open(
  1914. os.path.join(
  1915. app_dir, "locale", "dummy_Lang", "LC_MESSAGES", "django.mo"
  1916. ),
  1917. "w",
  1918. ).close()
  1919. app_config = AppConfig("dummy_app", AppModuleStub(__path__=[app_dir]))
  1920. with mock.patch(
  1921. "django.apps.apps.get_app_configs", return_value=[app_config]
  1922. ):
  1923. self.assertIs(check_for_language("dummy-lang"), True)
  1924. @override_settings(
  1925. USE_I18N=True,
  1926. LANGUAGES=[
  1927. ("en-us", "English"),
  1928. # xyz language has no locale files
  1929. ("xyz", "XYZ"),
  1930. ],
  1931. )
  1932. @translation.override("xyz")
  1933. def test_plural_non_django_language(self):
  1934. self.assertEqual(get_language(), "xyz")
  1935. self.assertEqual(ngettext("year", "years", 2), "years")
  1936. @override_settings(USE_I18N=True)
  1937. class WatchForTranslationChangesTests(SimpleTestCase):
  1938. @override_settings(USE_I18N=False)
  1939. def test_i18n_disabled(self):
  1940. mocked_sender = mock.MagicMock()
  1941. watch_for_translation_changes(mocked_sender)
  1942. mocked_sender.watch_dir.assert_not_called()
  1943. def test_i18n_enabled(self):
  1944. mocked_sender = mock.MagicMock()
  1945. watch_for_translation_changes(mocked_sender)
  1946. self.assertGreater(mocked_sender.watch_dir.call_count, 1)
  1947. def test_i18n_locale_paths(self):
  1948. mocked_sender = mock.MagicMock()
  1949. with tempfile.TemporaryDirectory() as app_dir:
  1950. with self.settings(LOCALE_PATHS=[app_dir]):
  1951. watch_for_translation_changes(mocked_sender)
  1952. mocked_sender.watch_dir.assert_any_call(Path(app_dir), "**/*.mo")
  1953. def test_i18n_app_dirs(self):
  1954. mocked_sender = mock.MagicMock()
  1955. with self.settings(INSTALLED_APPS=["i18n.sampleproject"]):
  1956. watch_for_translation_changes(mocked_sender)
  1957. project_dir = Path(__file__).parent / "sampleproject" / "locale"
  1958. mocked_sender.watch_dir.assert_any_call(project_dir, "**/*.mo")
  1959. def test_i18n_app_dirs_ignore_django_apps(self):
  1960. mocked_sender = mock.MagicMock()
  1961. with self.settings(INSTALLED_APPS=["django.contrib.admin"]):
  1962. watch_for_translation_changes(mocked_sender)
  1963. mocked_sender.watch_dir.assert_called_once_with(Path("locale"), "**/*.mo")
  1964. def test_i18n_local_locale(self):
  1965. mocked_sender = mock.MagicMock()
  1966. watch_for_translation_changes(mocked_sender)
  1967. locale_dir = Path(__file__).parent / "locale"
  1968. mocked_sender.watch_dir.assert_any_call(locale_dir, "**/*.mo")
  1969. class TranslationFileChangedTests(SimpleTestCase):
  1970. def setUp(self):
  1971. self.gettext_translations = gettext_module._translations.copy()
  1972. self.trans_real_translations = trans_real._translations.copy()
  1973. def tearDown(self):
  1974. gettext._translations = self.gettext_translations
  1975. trans_real._translations = self.trans_real_translations
  1976. def test_ignores_non_mo_files(self):
  1977. gettext_module._translations = {"foo": "bar"}
  1978. path = Path("test.py")
  1979. self.assertIsNone(translation_file_changed(None, path))
  1980. self.assertEqual(gettext_module._translations, {"foo": "bar"})
  1981. def test_resets_cache_with_mo_files(self):
  1982. gettext_module._translations = {"foo": "bar"}
  1983. trans_real._translations = {"foo": "bar"}
  1984. trans_real._default = 1
  1985. trans_real._active = False
  1986. path = Path("test.mo")
  1987. self.assertIs(translation_file_changed(None, path), True)
  1988. self.assertEqual(gettext_module._translations, {})
  1989. self.assertEqual(trans_real._translations, {})
  1990. self.assertIsNone(trans_real._default)
  1991. self.assertIsInstance(trans_real._active, Local)
  1992. class UtilsTests(SimpleTestCase):
  1993. def test_round_away_from_one(self):
  1994. tests = [
  1995. (0, 0),
  1996. (0.0, 0),
  1997. (0.25, 0),
  1998. (0.5, 0),
  1999. (0.75, 0),
  2000. (1, 1),
  2001. (1.0, 1),
  2002. (1.25, 2),
  2003. (1.5, 2),
  2004. (1.75, 2),
  2005. (-0.0, 0),
  2006. (-0.25, -1),
  2007. (-0.5, -1),
  2008. (-0.75, -1),
  2009. (-1, -1),
  2010. (-1.0, -1),
  2011. (-1.25, -2),
  2012. (-1.5, -2),
  2013. (-1.75, -2),
  2014. ]
  2015. for value, expected in tests:
  2016. with self.subTest(value=value):
  2017. self.assertEqual(round_away_from_one(value), expected)