tests.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. import datetime
  2. from decimal import Decimal
  3. from django.contrib.humanize.templatetags import humanize
  4. from django.template import Context, Template, defaultfilters
  5. from django.test import SimpleTestCase, modify_settings, override_settings
  6. from django.utils import translation
  7. from django.utils.html import escape
  8. from django.utils.timezone import get_fixed_timezone
  9. from django.utils.translation import gettext as _
  10. # Mock out datetime in some tests so they don't fail occasionally when they
  11. # run too slow. Use a fixed datetime for datetime.now(). DST change in
  12. # America/Chicago (the default time zone) happened on March 11th in 2012.
  13. now = datetime.datetime(2012, 3, 9, 22, 30)
  14. class MockDateTime(datetime.datetime):
  15. @classmethod
  16. def now(cls, tz=None):
  17. if tz is None or tz.utcoffset(now) is None:
  18. return now
  19. else:
  20. # equals now.replace(tzinfo=utc)
  21. return now.replace(tzinfo=tz) + tz.utcoffset(now)
  22. @modify_settings(INSTALLED_APPS={"append": "django.contrib.humanize"})
  23. class HumanizeTests(SimpleTestCase):
  24. def humanize_tester(
  25. self, test_list, result_list, method, normalize_result_func=escape
  26. ):
  27. for test_content, result in zip(test_list, result_list):
  28. with self.subTest(test_content):
  29. t = Template("{%% load humanize %%}{{ test_content|%s }}" % method)
  30. rendered = t.render(Context(locals())).strip()
  31. self.assertEqual(
  32. rendered,
  33. normalize_result_func(result),
  34. msg="%s test failed, produced '%s', should've produced '%s'"
  35. % (method, rendered, result),
  36. )
  37. def test_ordinal(self):
  38. test_list = (
  39. "1",
  40. "2",
  41. "3",
  42. "4",
  43. "11",
  44. "12",
  45. "13",
  46. "101",
  47. "102",
  48. "103",
  49. "111",
  50. "something else",
  51. None,
  52. )
  53. result_list = (
  54. "1st",
  55. "2nd",
  56. "3rd",
  57. "4th",
  58. "11th",
  59. "12th",
  60. "13th",
  61. "101st",
  62. "102nd",
  63. "103rd",
  64. "111th",
  65. "something else",
  66. None,
  67. )
  68. with translation.override("en"):
  69. self.humanize_tester(test_list, result_list, "ordinal")
  70. def test_i18n_html_ordinal(self):
  71. """Allow html in output on i18n strings"""
  72. test_list = (
  73. "1",
  74. "2",
  75. "3",
  76. "4",
  77. "11",
  78. "12",
  79. "13",
  80. "101",
  81. "102",
  82. "103",
  83. "111",
  84. "something else",
  85. None,
  86. )
  87. result_list = (
  88. "1<sup>er</sup>",
  89. "2<sup>e</sup>",
  90. "3<sup>e</sup>",
  91. "4<sup>e</sup>",
  92. "11<sup>e</sup>",
  93. "12<sup>e</sup>",
  94. "13<sup>e</sup>",
  95. "101<sup>er</sup>",
  96. "102<sup>e</sup>",
  97. "103<sup>e</sup>",
  98. "111<sup>e</sup>",
  99. "something else",
  100. "None",
  101. )
  102. with translation.override("fr-fr"):
  103. self.humanize_tester(test_list, result_list, "ordinal", lambda x: x)
  104. def test_intcomma(self):
  105. test_list = (
  106. 100,
  107. 1000,
  108. 10123,
  109. 10311,
  110. 1000000,
  111. 1234567.25,
  112. "100",
  113. "1000",
  114. "10123",
  115. "10311",
  116. "1000000",
  117. "1234567.1234567",
  118. Decimal("1234567.1234567"),
  119. None,
  120. "1234567",
  121. "1234567.12",
  122. )
  123. result_list = (
  124. "100",
  125. "1,000",
  126. "10,123",
  127. "10,311",
  128. "1,000,000",
  129. "1,234,567.25",
  130. "100",
  131. "1,000",
  132. "10,123",
  133. "10,311",
  134. "1,000,000",
  135. "1,234,567.1234567",
  136. "1,234,567.1234567",
  137. None,
  138. "1,234,567",
  139. "1,234,567.12",
  140. )
  141. with translation.override("en"):
  142. self.humanize_tester(test_list, result_list, "intcomma")
  143. def test_l10n_intcomma(self):
  144. test_list = (
  145. 100,
  146. 1000,
  147. 10123,
  148. 10311,
  149. 1000000,
  150. 1234567.25,
  151. "100",
  152. "1000",
  153. "10123",
  154. "10311",
  155. "1000000",
  156. "1234567.1234567",
  157. Decimal("1234567.1234567"),
  158. None,
  159. "1234567",
  160. "1234567.12",
  161. )
  162. result_list = (
  163. "100",
  164. "1,000",
  165. "10,123",
  166. "10,311",
  167. "1,000,000",
  168. "1,234,567.25",
  169. "100",
  170. "1,000",
  171. "10,123",
  172. "10,311",
  173. "1,000,000",
  174. "1,234,567.1234567",
  175. "1,234,567.1234567",
  176. None,
  177. "1,234,567",
  178. "1,234,567.12",
  179. )
  180. with self.settings(USE_THOUSAND_SEPARATOR=False):
  181. with translation.override("en"):
  182. self.humanize_tester(test_list, result_list, "intcomma")
  183. def test_intcomma_without_number_grouping(self):
  184. # Regression for #17414
  185. with translation.override("ja"):
  186. self.humanize_tester([100], ["100"], "intcomma")
  187. def test_intword(self):
  188. # Positive integers.
  189. test_list_positive = (
  190. "100",
  191. "1000000",
  192. "1200000",
  193. "1290000",
  194. "1000000000",
  195. "2000000000",
  196. "6000000000000",
  197. "1300000000000000",
  198. "3500000000000000000000",
  199. "8100000000000000000000000000000000",
  200. ("1" + "0" * 100),
  201. ("1" + "0" * 104),
  202. )
  203. result_list_positive = (
  204. "100",
  205. "1.0 million",
  206. "1.2 million",
  207. "1.3 million",
  208. "1.0 billion",
  209. "2.0 billion",
  210. "6.0 trillion",
  211. "1.3 quadrillion",
  212. "3.5 sextillion",
  213. "8.1 decillion",
  214. "1.0 googol",
  215. ("1" + "0" * 104),
  216. )
  217. # Negative integers.
  218. test_list_negative = ("-" + test for test in test_list_positive)
  219. result_list_negative = ("-" + result for result in result_list_positive)
  220. with translation.override("en"):
  221. self.humanize_tester(
  222. (*test_list_positive, *test_list_negative, None),
  223. (*result_list_positive, *result_list_negative, None),
  224. "intword",
  225. )
  226. def test_i18n_intcomma(self):
  227. test_list = (
  228. 100,
  229. 1000,
  230. 10123,
  231. 10311,
  232. 1000000,
  233. 1234567.25,
  234. "100",
  235. "1000",
  236. "10123",
  237. "10311",
  238. "1000000",
  239. None,
  240. )
  241. result_list = (
  242. "100",
  243. "1.000",
  244. "10.123",
  245. "10.311",
  246. "1.000.000",
  247. "1.234.567,25",
  248. "100",
  249. "1.000",
  250. "10.123",
  251. "10.311",
  252. "1.000.000",
  253. None,
  254. )
  255. with self.settings(USE_THOUSAND_SEPARATOR=True):
  256. with translation.override("de"):
  257. self.humanize_tester(test_list, result_list, "intcomma")
  258. def test_i18n_intword(self):
  259. # Positive integers.
  260. test_list_positive = (
  261. "100",
  262. "1000000",
  263. "1200000",
  264. "1290000",
  265. "1000000000",
  266. "2000000000",
  267. "6000000000000",
  268. )
  269. result_list_positive = (
  270. "100",
  271. "1,0 Million",
  272. "1,2 Millionen",
  273. "1,3 Millionen",
  274. "1,0 Milliarde",
  275. "2,0 Milliarden",
  276. "6,0 Billionen",
  277. )
  278. # Negative integers.
  279. test_list_negative = ("-" + test for test in test_list_positive)
  280. result_list_negative = ("-" + result for result in result_list_positive)
  281. with self.settings(USE_THOUSAND_SEPARATOR=True):
  282. with translation.override("de"):
  283. self.humanize_tester(
  284. (*test_list_positive, *test_list_negative),
  285. (*result_list_positive, *result_list_negative),
  286. "intword",
  287. )
  288. def test_apnumber(self):
  289. test_list = [str(x) for x in range(1, 11)]
  290. test_list.append(None)
  291. result_list = (
  292. "one",
  293. "two",
  294. "three",
  295. "four",
  296. "five",
  297. "six",
  298. "seven",
  299. "eight",
  300. "nine",
  301. "10",
  302. None,
  303. )
  304. with translation.override("en"):
  305. self.humanize_tester(test_list, result_list, "apnumber")
  306. def test_naturalday(self):
  307. today = datetime.date.today()
  308. yesterday = today - datetime.timedelta(days=1)
  309. tomorrow = today + datetime.timedelta(days=1)
  310. someday = today - datetime.timedelta(days=10)
  311. notdate = "I'm not a date value"
  312. test_list = (today, yesterday, tomorrow, someday, notdate, None)
  313. someday_result = defaultfilters.date(someday)
  314. result_list = (
  315. _("today"),
  316. _("yesterday"),
  317. _("tomorrow"),
  318. someday_result,
  319. "I'm not a date value",
  320. None,
  321. )
  322. self.humanize_tester(test_list, result_list, "naturalday")
  323. def test_naturalday_tz(self):
  324. today = datetime.date.today()
  325. tz_one = get_fixed_timezone(-720)
  326. tz_two = get_fixed_timezone(720)
  327. # Can be today or yesterday
  328. date_one = datetime.datetime(today.year, today.month, today.day, tzinfo=tz_one)
  329. naturalday_one = humanize.naturalday(date_one)
  330. # Can be today or tomorrow
  331. date_two = datetime.datetime(today.year, today.month, today.day, tzinfo=tz_two)
  332. naturalday_two = humanize.naturalday(date_two)
  333. # As 24h of difference they will never be the same
  334. self.assertNotEqual(naturalday_one, naturalday_two)
  335. def test_naturalday_uses_localtime(self):
  336. # Regression for #18504
  337. # This is 2012-03-08HT19:30:00-06:00 in America/Chicago
  338. dt = datetime.datetime(2012, 3, 9, 1, 30, tzinfo=datetime.timezone.utc)
  339. orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime
  340. try:
  341. with override_settings(TIME_ZONE="America/Chicago", USE_TZ=True):
  342. with translation.override("en"):
  343. self.humanize_tester([dt], ["yesterday"], "naturalday")
  344. finally:
  345. humanize.datetime = orig_humanize_datetime
  346. def test_naturaltime(self):
  347. class naive(datetime.tzinfo):
  348. def utcoffset(self, dt):
  349. return None
  350. test_list = [
  351. "test",
  352. now,
  353. now - datetime.timedelta(microseconds=1),
  354. now - datetime.timedelta(seconds=1),
  355. now - datetime.timedelta(seconds=30),
  356. now - datetime.timedelta(minutes=1, seconds=30),
  357. now - datetime.timedelta(minutes=2),
  358. now - datetime.timedelta(hours=1, minutes=30, seconds=30),
  359. now - datetime.timedelta(hours=23, minutes=50, seconds=50),
  360. now - datetime.timedelta(days=1),
  361. now - datetime.timedelta(days=500),
  362. now + datetime.timedelta(seconds=1),
  363. now + datetime.timedelta(seconds=30),
  364. now + datetime.timedelta(minutes=1, seconds=30),
  365. now + datetime.timedelta(minutes=2),
  366. now + datetime.timedelta(hours=1, minutes=30, seconds=30),
  367. now + datetime.timedelta(hours=23, minutes=50, seconds=50),
  368. now + datetime.timedelta(days=1),
  369. now + datetime.timedelta(days=2, hours=6),
  370. now + datetime.timedelta(days=500),
  371. now.replace(tzinfo=naive()),
  372. now.replace(tzinfo=datetime.timezone.utc),
  373. ]
  374. result_list = [
  375. "test",
  376. "now",
  377. "now",
  378. "a second ago",
  379. "30\xa0seconds ago",
  380. "a minute ago",
  381. "2\xa0minutes ago",
  382. "an hour ago",
  383. "23\xa0hours ago",
  384. "1\xa0day ago",
  385. "1\xa0year, 4\xa0months ago",
  386. "a second from now",
  387. "30\xa0seconds from now",
  388. "a minute from now",
  389. "2\xa0minutes from now",
  390. "an hour from now",
  391. "23\xa0hours from now",
  392. "1\xa0day from now",
  393. "2\xa0days, 6\xa0hours from now",
  394. "1\xa0year, 4\xa0months from now",
  395. "now",
  396. "now",
  397. ]
  398. # Because of the DST change, 2 days and 6 hours after the chosen
  399. # date in naive arithmetic is only 2 days and 5 hours after in
  400. # aware arithmetic.
  401. result_list_with_tz_support = result_list[:]
  402. assert result_list_with_tz_support[-4] == "2\xa0days, 6\xa0hours from now"
  403. result_list_with_tz_support[-4] == "2\xa0days, 5\xa0hours from now"
  404. orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime
  405. try:
  406. with translation.override("en"):
  407. self.humanize_tester(test_list, result_list, "naturaltime")
  408. with override_settings(USE_TZ=True):
  409. self.humanize_tester(
  410. test_list, result_list_with_tz_support, "naturaltime"
  411. )
  412. finally:
  413. humanize.datetime = orig_humanize_datetime
  414. def test_naturaltime_as_documented(self):
  415. """
  416. #23340 -- Verify the documented behavior of humanize.naturaltime.
  417. """
  418. time_format = "%d %b %Y %H:%M:%S"
  419. documented_now = datetime.datetime.strptime("17 Feb 2007 16:30:00", time_format)
  420. test_data = (
  421. ("17 Feb 2007 16:30:00", "now"),
  422. ("17 Feb 2007 16:29:31", "29 seconds ago"),
  423. ("17 Feb 2007 16:29:00", "a minute ago"),
  424. ("17 Feb 2007 16:25:35", "4 minutes ago"),
  425. ("17 Feb 2007 15:30:29", "59 minutes ago"),
  426. ("17 Feb 2007 15:30:01", "59 minutes ago"),
  427. ("17 Feb 2007 15:30:00", "an hour ago"),
  428. ("17 Feb 2007 13:31:29", "2 hours ago"),
  429. ("16 Feb 2007 13:31:29", "1 day, 2 hours ago"),
  430. ("16 Feb 2007 13:30:01", "1 day, 2 hours ago"),
  431. ("16 Feb 2007 13:30:00", "1 day, 3 hours ago"),
  432. ("17 Feb 2007 16:30:30", "30 seconds from now"),
  433. ("17 Feb 2007 16:30:29", "29 seconds from now"),
  434. ("17 Feb 2007 16:31:00", "a minute from now"),
  435. ("17 Feb 2007 16:34:35", "4 minutes from now"),
  436. ("17 Feb 2007 17:30:29", "an hour from now"),
  437. ("17 Feb 2007 18:31:29", "2 hours from now"),
  438. ("18 Feb 2007 16:31:29", "1 day from now"),
  439. ("26 Feb 2007 18:31:29", "1 week, 2 days from now"),
  440. )
  441. class DocumentedMockDateTime(datetime.datetime):
  442. @classmethod
  443. def now(cls, tz=None):
  444. if tz is None or tz.utcoffset(documented_now) is None:
  445. return documented_now
  446. else:
  447. return documented_now.replace(tzinfo=tz) + tz.utcoffset(now)
  448. orig_humanize_datetime = humanize.datetime
  449. humanize.datetime = DocumentedMockDateTime
  450. try:
  451. for test_time_string, expected_natural_time in test_data:
  452. with self.subTest(test_time_string):
  453. test_time = datetime.datetime.strptime(
  454. test_time_string, time_format
  455. )
  456. natural_time = humanize.naturaltime(test_time).replace("\xa0", " ")
  457. self.assertEqual(expected_natural_time, natural_time)
  458. finally:
  459. humanize.datetime = orig_humanize_datetime
  460. def test_inflection_for_timedelta(self):
  461. """
  462. Translation of '%d day'/'%d month'/… may differ depending on the context
  463. of the string it is inserted in.
  464. """
  465. test_list = [
  466. # "%(delta)s ago" translations
  467. now - datetime.timedelta(days=1),
  468. now - datetime.timedelta(days=2),
  469. now - datetime.timedelta(days=30),
  470. now - datetime.timedelta(days=60),
  471. now - datetime.timedelta(days=500),
  472. now - datetime.timedelta(days=865),
  473. # "%(delta)s from now" translations
  474. now + datetime.timedelta(days=1),
  475. now + datetime.timedelta(days=2),
  476. now + datetime.timedelta(days=30),
  477. now + datetime.timedelta(days=60),
  478. now + datetime.timedelta(days=500),
  479. now + datetime.timedelta(days=865),
  480. ]
  481. result_list = [
  482. "před 1\xa0dnem",
  483. "před 2\xa0dny",
  484. "před 1\xa0měsícem",
  485. "před 2\xa0měsíci",
  486. "před 1\xa0rokem, 4\xa0měsíci",
  487. "před 2\xa0lety, 4\xa0měsíci",
  488. "za 1\xa0den",
  489. "za 2\xa0dny",
  490. "za 1\xa0měsíc",
  491. "za 2\xa0měsíce",
  492. "za 1\xa0rok, 4\xa0měsíce",
  493. "za 2\xa0roky, 4\xa0měsíce",
  494. ]
  495. orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime
  496. try:
  497. # Choose a language with different
  498. # naturaltime-past/naturaltime-future translations.
  499. with translation.override("cs"):
  500. self.humanize_tester(test_list, result_list, "naturaltime")
  501. finally:
  502. humanize.datetime = orig_humanize_datetime