tests.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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, utc
  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(self, test_list, result_list, method, normalize_result_func=escape):
  25. for test_content, result in zip(test_list, result_list):
  26. with self.subTest(test_content):
  27. t = Template('{%% load humanize %%}{{ test_content|%s }}' % method)
  28. rendered = t.render(Context(locals())).strip()
  29. self.assertEqual(
  30. rendered,
  31. normalize_result_func(result),
  32. msg="%s test failed, produced '%s', should've produced '%s'" % (method, rendered, result)
  33. )
  34. def test_ordinal(self):
  35. test_list = ('1', '2', '3', '4', '11', '12',
  36. '13', '101', '102', '103', '111',
  37. 'something else', None)
  38. result_list = ('1st', '2nd', '3rd', '4th', '11th',
  39. '12th', '13th', '101st', '102nd', '103rd',
  40. '111th', 'something else', None)
  41. with translation.override('en'):
  42. self.humanize_tester(test_list, result_list, 'ordinal')
  43. def test_i18n_html_ordinal(self):
  44. """Allow html in output on i18n strings"""
  45. test_list = ('1', '2', '3', '4', '11', '12',
  46. '13', '101', '102', '103', '111',
  47. 'something else', None)
  48. result_list = ('1<sup>er</sup>', '2<sup>e</sup>', '3<sup>e</sup>', '4<sup>e</sup>',
  49. '11<sup>e</sup>', '12<sup>e</sup>', '13<sup>e</sup>', '101<sup>er</sup>',
  50. '102<sup>e</sup>', '103<sup>e</sup>', '111<sup>e</sup>', 'something else',
  51. 'None')
  52. with translation.override('fr-fr'):
  53. self.humanize_tester(test_list, result_list, 'ordinal', lambda x: x)
  54. def test_intcomma(self):
  55. test_list = (
  56. 100, 1000, 10123, 10311, 1000000, 1234567.25, '100', '1000',
  57. '10123', '10311', '1000000', '1234567.1234567',
  58. Decimal('1234567.1234567'), None,
  59. )
  60. result_list = (
  61. '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.25',
  62. '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.1234567',
  63. '1,234,567.1234567', None,
  64. )
  65. with translation.override('en'):
  66. self.humanize_tester(test_list, result_list, 'intcomma')
  67. def test_l10n_intcomma(self):
  68. test_list = (
  69. 100, 1000, 10123, 10311, 1000000, 1234567.25, '100', '1000',
  70. '10123', '10311', '1000000', '1234567.1234567',
  71. Decimal('1234567.1234567'), None,
  72. )
  73. result_list = (
  74. '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.25',
  75. '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.1234567',
  76. '1,234,567.1234567', None,
  77. )
  78. with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=False):
  79. with translation.override('en'):
  80. self.humanize_tester(test_list, result_list, 'intcomma')
  81. def test_intcomma_without_number_grouping(self):
  82. # Regression for #17414
  83. with translation.override('ja'), self.settings(USE_L10N=True):
  84. self.humanize_tester([100], ['100'], 'intcomma')
  85. def test_intword(self):
  86. # Positive integers.
  87. test_list_positive = (
  88. '100', '1000000', '1200000', '1290000', '1000000000', '2000000000',
  89. '6000000000000', '1300000000000000', '3500000000000000000000',
  90. '8100000000000000000000000000000000', ('1' + '0' * 100),
  91. ('1' + '0' * 104),
  92. )
  93. result_list_positive = (
  94. '100', '1.0 million', '1.2 million', '1.3 million', '1.0 billion',
  95. '2.0 billion', '6.0 trillion', '1.3 quadrillion', '3.5 sextillion',
  96. '8.1 decillion', '1.0 googol', ('1' + '0' * 104),
  97. )
  98. # Negative integers.
  99. test_list_negative = ('-' + test for test in test_list_positive)
  100. result_list_negative = ('-' + result for result in result_list_positive)
  101. with translation.override('en'):
  102. self.humanize_tester(
  103. (*test_list_positive, *test_list_negative, None),
  104. (*result_list_positive, *result_list_negative, None),
  105. 'intword',
  106. )
  107. def test_i18n_intcomma(self):
  108. test_list = (100, 1000, 10123, 10311, 1000000, 1234567.25,
  109. '100', '1000', '10123', '10311', '1000000', None)
  110. result_list = ('100', '1.000', '10.123', '10.311', '1.000.000', '1.234.567,25',
  111. '100', '1.000', '10.123', '10.311', '1.000.000', None)
  112. with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True):
  113. with translation.override('de'):
  114. self.humanize_tester(test_list, result_list, 'intcomma')
  115. def test_i18n_intword(self):
  116. # Positive integers.
  117. test_list_positive = (
  118. '100', '1000000', '1200000', '1290000', '1000000000', '2000000000',
  119. '6000000000000',
  120. )
  121. result_list_positive = (
  122. '100', '1,0 Million', '1,2 Millionen', '1,3 Millionen',
  123. '1,0 Milliarde', '2,0 Milliarden', '6,0 Billionen',
  124. )
  125. # Negative integers.
  126. test_list_negative = ('-' + test for test in test_list_positive)
  127. result_list_negative = ('-' + result for result in result_list_positive)
  128. with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True):
  129. with translation.override('de'):
  130. self.humanize_tester(
  131. (*test_list_positive, *test_list_negative),
  132. (*result_list_positive, *result_list_negative),
  133. 'intword',
  134. )
  135. def test_apnumber(self):
  136. test_list = [str(x) for x in range(1, 11)]
  137. test_list.append(None)
  138. result_list = ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', '10', None)
  139. with translation.override('en'):
  140. self.humanize_tester(test_list, result_list, 'apnumber')
  141. def test_naturalday(self):
  142. today = datetime.date.today()
  143. yesterday = today - datetime.timedelta(days=1)
  144. tomorrow = today + datetime.timedelta(days=1)
  145. someday = today - datetime.timedelta(days=10)
  146. notdate = "I'm not a date value"
  147. test_list = (today, yesterday, tomorrow, someday, notdate, None)
  148. someday_result = defaultfilters.date(someday)
  149. result_list = (_('today'), _('yesterday'), _('tomorrow'),
  150. someday_result, "I'm not a date value", None)
  151. self.humanize_tester(test_list, result_list, 'naturalday')
  152. def test_naturalday_tz(self):
  153. today = datetime.date.today()
  154. tz_one = get_fixed_timezone(-720)
  155. tz_two = get_fixed_timezone(720)
  156. # Can be today or yesterday
  157. date_one = datetime.datetime(today.year, today.month, today.day, tzinfo=tz_one)
  158. naturalday_one = humanize.naturalday(date_one)
  159. # Can be today or tomorrow
  160. date_two = datetime.datetime(today.year, today.month, today.day, tzinfo=tz_two)
  161. naturalday_two = humanize.naturalday(date_two)
  162. # As 24h of difference they will never be the same
  163. self.assertNotEqual(naturalday_one, naturalday_two)
  164. def test_naturalday_uses_localtime(self):
  165. # Regression for #18504
  166. # This is 2012-03-08HT19:30:00-06:00 in America/Chicago
  167. dt = datetime.datetime(2012, 3, 9, 1, 30, tzinfo=utc)
  168. orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime
  169. try:
  170. with override_settings(TIME_ZONE="America/Chicago", USE_TZ=True):
  171. with translation.override('en'):
  172. self.humanize_tester([dt], ['yesterday'], 'naturalday')
  173. finally:
  174. humanize.datetime = orig_humanize_datetime
  175. def test_naturaltime(self):
  176. class naive(datetime.tzinfo):
  177. def utcoffset(self, dt):
  178. return None
  179. test_list = [
  180. 'test',
  181. now,
  182. now - datetime.timedelta(microseconds=1),
  183. now - datetime.timedelta(seconds=1),
  184. now - datetime.timedelta(seconds=30),
  185. now - datetime.timedelta(minutes=1, seconds=30),
  186. now - datetime.timedelta(minutes=2),
  187. now - datetime.timedelta(hours=1, minutes=30, seconds=30),
  188. now - datetime.timedelta(hours=23, minutes=50, seconds=50),
  189. now - datetime.timedelta(days=1),
  190. now - datetime.timedelta(days=500),
  191. now + datetime.timedelta(seconds=1),
  192. now + datetime.timedelta(seconds=30),
  193. now + datetime.timedelta(minutes=1, seconds=30),
  194. now + datetime.timedelta(minutes=2),
  195. now + datetime.timedelta(hours=1, minutes=30, seconds=30),
  196. now + datetime.timedelta(hours=23, minutes=50, seconds=50),
  197. now + datetime.timedelta(days=1),
  198. now + datetime.timedelta(days=2, hours=6),
  199. now + datetime.timedelta(days=500),
  200. now.replace(tzinfo=naive()),
  201. now.replace(tzinfo=utc),
  202. ]
  203. result_list = [
  204. 'test',
  205. 'now',
  206. 'now',
  207. 'a second ago',
  208. '30\xa0seconds ago',
  209. 'a minute ago',
  210. '2\xa0minutes ago',
  211. 'an hour ago',
  212. '23\xa0hours ago',
  213. '1\xa0day ago',
  214. '1\xa0year, 4\xa0months ago',
  215. 'a second from now',
  216. '30\xa0seconds from now',
  217. 'a minute from now',
  218. '2\xa0minutes from now',
  219. 'an hour from now',
  220. '23\xa0hours from now',
  221. '1\xa0day from now',
  222. '2\xa0days, 6\xa0hours from now',
  223. '1\xa0year, 4\xa0months from now',
  224. 'now',
  225. 'now',
  226. ]
  227. # Because of the DST change, 2 days and 6 hours after the chosen
  228. # date in naive arithmetic is only 2 days and 5 hours after in
  229. # aware arithmetic.
  230. result_list_with_tz_support = result_list[:]
  231. assert result_list_with_tz_support[-4] == '2\xa0days, 6\xa0hours from now'
  232. result_list_with_tz_support[-4] == '2\xa0days, 5\xa0hours from now'
  233. orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime
  234. try:
  235. with translation.override('en'):
  236. self.humanize_tester(test_list, result_list, 'naturaltime')
  237. with override_settings(USE_TZ=True):
  238. self.humanize_tester(
  239. test_list, result_list_with_tz_support, 'naturaltime')
  240. finally:
  241. humanize.datetime = orig_humanize_datetime
  242. def test_naturaltime_as_documented(self):
  243. """
  244. #23340 -- Verify the documented behavior of humanize.naturaltime.
  245. """
  246. time_format = '%d %b %Y %H:%M:%S'
  247. documented_now = datetime.datetime.strptime('17 Feb 2007 16:30:00', time_format)
  248. test_data = (
  249. ('17 Feb 2007 16:30:00', 'now'),
  250. ('17 Feb 2007 16:29:31', '29 seconds ago'),
  251. ('17 Feb 2007 16:29:00', 'a minute ago'),
  252. ('17 Feb 2007 16:25:35', '4 minutes ago'),
  253. ('17 Feb 2007 15:30:29', '59 minutes ago'),
  254. ('17 Feb 2007 15:30:01', '59 minutes ago'),
  255. ('17 Feb 2007 15:30:00', 'an hour ago'),
  256. ('17 Feb 2007 13:31:29', '2 hours ago'),
  257. ('16 Feb 2007 13:31:29', '1 day, 2 hours ago'),
  258. ('16 Feb 2007 13:30:01', '1 day, 2 hours ago'),
  259. ('16 Feb 2007 13:30:00', '1 day, 3 hours ago'),
  260. ('17 Feb 2007 16:30:30', '30 seconds from now'),
  261. ('17 Feb 2007 16:30:29', '29 seconds from now'),
  262. ('17 Feb 2007 16:31:00', 'a minute from now'),
  263. ('17 Feb 2007 16:34:35', '4 minutes from now'),
  264. ('17 Feb 2007 17:30:29', 'an hour from now'),
  265. ('17 Feb 2007 18:31:29', '2 hours from now'),
  266. ('18 Feb 2007 16:31:29', '1 day from now'),
  267. ('26 Feb 2007 18:31:29', '1 week, 2 days from now'),
  268. )
  269. class DocumentedMockDateTime(datetime.datetime):
  270. @classmethod
  271. def now(cls, tz=None):
  272. if tz is None or tz.utcoffset(documented_now) is None:
  273. return documented_now
  274. else:
  275. return documented_now.replace(tzinfo=tz) + tz.utcoffset(now)
  276. orig_humanize_datetime = humanize.datetime
  277. humanize.datetime = DocumentedMockDateTime
  278. try:
  279. for test_time_string, expected_natural_time in test_data:
  280. with self.subTest(test_time_string):
  281. test_time = datetime.datetime.strptime(test_time_string, time_format)
  282. natural_time = humanize.naturaltime(test_time).replace('\xa0', ' ')
  283. self.assertEqual(expected_natural_time, natural_time)
  284. finally:
  285. humanize.datetime = orig_humanize_datetime
  286. def test_inflection_for_timedelta(self):
  287. """
  288. Translation of '%d day'/'%d month'/… may differ depending on the context
  289. of the string it is inserted in.
  290. """
  291. test_list = [
  292. # "%(delta)s ago" translations
  293. now - datetime.timedelta(days=1),
  294. now - datetime.timedelta(days=2),
  295. now - datetime.timedelta(days=30),
  296. now - datetime.timedelta(days=60),
  297. now - datetime.timedelta(days=500),
  298. now - datetime.timedelta(days=865),
  299. # "%(delta)s from now" translations
  300. now + datetime.timedelta(days=1),
  301. now + datetime.timedelta(days=2),
  302. now + datetime.timedelta(days=30),
  303. now + datetime.timedelta(days=60),
  304. now + datetime.timedelta(days=500),
  305. now + datetime.timedelta(days=865),
  306. ]
  307. result_list = [
  308. 'před 1\xa0dnem',
  309. 'před 2\xa0dny',
  310. 'před 1\xa0měsícem',
  311. 'před 2\xa0měsíci',
  312. 'před 1\xa0rokem, 4\xa0měsíci',
  313. 'před 2\xa0lety, 4\xa0měsíci',
  314. 'za 1\xa0den',
  315. 'za 2\xa0dny',
  316. 'za 1\xa0měsíc',
  317. 'za 2\xa0měsíce',
  318. 'za 1\xa0rok, 4\xa0měsíce',
  319. 'za 2\xa0roky, 4\xa0měsíce',
  320. ]
  321. orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime
  322. try:
  323. # Choose a language with different naturaltime-past/naturaltime-future translations
  324. with translation.override('cs'), self.settings(USE_L10N=True):
  325. self.humanize_tester(test_list, result_list, 'naturaltime')
  326. finally:
  327. humanize.datetime = orig_humanize_datetime