tests.py 15 KB

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