tests.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. from __future__ import unicode_literals
  2. import datetime
  3. from decimal import Decimal
  4. from django.contrib.humanize.templatetags import humanize
  5. from django.template import Context, Template, defaultfilters
  6. from django.test import SimpleTestCase, modify_settings, override_settings
  7. from django.utils import translation
  8. from django.utils.html import escape
  9. from django.utils.timezone import get_fixed_timezone, utc
  10. from django.utils.translation import ugettext as _
  11. # Mock out datetime in some tests so they don't fail occasionally when they
  12. # run too slow. Use a fixed datetime for datetime.now(). DST change in
  13. # America/Chicago (the default time zone) happened on March 11th in 2012.
  14. now = datetime.datetime(2012, 3, 9, 22, 30)
  15. class MockDateTime(datetime.datetime):
  16. @classmethod
  17. def now(cls, tz=None):
  18. if tz is None or tz.utcoffset(now) is None:
  19. return now
  20. else:
  21. # equals now.replace(tzinfo=utc)
  22. return now.replace(tzinfo=tz) + tz.utcoffset(now)
  23. @modify_settings(INSTALLED_APPS={'append': 'django.contrib.humanize'})
  24. class HumanizeTests(SimpleTestCase):
  25. def humanize_tester(self, test_list, result_list, method, normalize_result_func=escape):
  26. for test_content, result in zip(test_list, result_list):
  27. t = Template('{%% load humanize %%}{{ test_content|%s }}' % method)
  28. rendered = t.render(Context(locals())).strip()
  29. self.assertEqual(rendered, normalize_result_func(result),
  30. msg="%s test failed, produced '%s', should've produced '%s'" % (method, rendered, result))
  31. def test_ordinal(self):
  32. test_list = ('1', '2', '3', '4', '11', '12',
  33. '13', '101', '102', '103', '111',
  34. 'something else', None)
  35. result_list = ('1st', '2nd', '3rd', '4th', '11th',
  36. '12th', '13th', '101st', '102nd', '103rd',
  37. '111th', 'something else', None)
  38. with translation.override('en'):
  39. self.humanize_tester(test_list, result_list, 'ordinal')
  40. def test_i18n_html_ordinal(self):
  41. """Allow html in output on i18n strings"""
  42. test_list = ('1', '2', '3', '4', '11', '12',
  43. '13', '101', '102', '103', '111',
  44. 'something else', None)
  45. result_list = ('1<sup>er</sup>', '2<sup>e</sup>', '3<sup>e</sup>', '4<sup>e</sup>',
  46. '11<sup>e</sup>', '12<sup>e</sup>', '13<sup>e</sup>', '101<sup>er</sup>',
  47. '102<sup>e</sup>', '103<sup>e</sup>', '111<sup>e</sup>', 'something else',
  48. 'None')
  49. with translation.override('fr-fr'):
  50. self.humanize_tester(test_list, result_list, 'ordinal', lambda x: x)
  51. def test_intcomma(self):
  52. test_list = (
  53. 100, 1000, 10123, 10311, 1000000, 1234567.25, '100', '1000',
  54. '10123', '10311', '1000000', '1234567.1234567',
  55. Decimal('1234567.1234567'), None,
  56. )
  57. result_list = (
  58. '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.25',
  59. '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.1234567',
  60. '1,234,567.1234567', None,
  61. )
  62. with translation.override('en'):
  63. self.humanize_tester(test_list, result_list, 'intcomma')
  64. def test_l10n_intcomma(self):
  65. test_list = (
  66. 100, 1000, 10123, 10311, 1000000, 1234567.25, '100', '1000',
  67. '10123', '10311', '1000000', '1234567.1234567',
  68. Decimal('1234567.1234567'), None,
  69. )
  70. result_list = (
  71. '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.25',
  72. '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.1234567',
  73. '1,234,567.1234567', None,
  74. )
  75. with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=False):
  76. with translation.override('en'):
  77. self.humanize_tester(test_list, result_list, 'intcomma')
  78. def test_intcomma_without_number_grouping(self):
  79. # Regression for #17414
  80. with translation.override('ja'), self.settings(USE_L10N=True):
  81. self.humanize_tester([100], ['100'], 'intcomma')
  82. def test_intword(self):
  83. test_list = (
  84. '100', '1000000', '1200000', '1290000', '1000000000', '2000000000',
  85. '6000000000000', '1300000000000000', '3500000000000000000000',
  86. '8100000000000000000000000000000000', None,
  87. )
  88. result_list = (
  89. '100', '1.0 million', '1.2 million', '1.3 million', '1.0 billion',
  90. '2.0 billion', '6.0 trillion', '1.3 quadrillion', '3.5 sextillion',
  91. '8.1 decillion', None,
  92. )
  93. with translation.override('en'):
  94. self.humanize_tester(test_list, result_list, 'intword')
  95. def test_i18n_intcomma(self):
  96. test_list = (100, 1000, 10123, 10311, 1000000, 1234567.25,
  97. '100', '1000', '10123', '10311', '1000000', None)
  98. result_list = ('100', '1.000', '10.123', '10.311', '1.000.000', '1.234.567,25',
  99. '100', '1.000', '10.123', '10.311', '1.000.000', None)
  100. with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True):
  101. with translation.override('de'):
  102. self.humanize_tester(test_list, result_list, 'intcomma')
  103. def test_i18n_intword(self):
  104. test_list = (
  105. '100', '1000000', '1200000', '1290000', '1000000000', '2000000000',
  106. '6000000000000',
  107. )
  108. result_list = (
  109. '100', '1,0 Million', '1,2 Millionen', '1,3 Millionen',
  110. '1,0 Milliarde', '2,0 Milliarden', '6,0 Billionen',
  111. )
  112. with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True):
  113. with translation.override('de'):
  114. self.humanize_tester(test_list, result_list, 'intword')
  115. def test_apnumber(self):
  116. test_list = [str(x) for x in range(1, 11)]
  117. test_list.append(None)
  118. result_list = ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', '10', None)
  119. with translation.override('en'):
  120. self.humanize_tester(test_list, result_list, 'apnumber')
  121. def test_naturalday(self):
  122. today = datetime.date.today()
  123. yesterday = today - datetime.timedelta(days=1)
  124. tomorrow = today + datetime.timedelta(days=1)
  125. someday = today - datetime.timedelta(days=10)
  126. notdate = "I'm not a date value"
  127. test_list = (today, yesterday, tomorrow, someday, notdate, None)
  128. someday_result = defaultfilters.date(someday)
  129. result_list = (_('today'), _('yesterday'), _('tomorrow'),
  130. someday_result, "I'm not a date value", None)
  131. self.humanize_tester(test_list, result_list, 'naturalday')
  132. def test_naturalday_tz(self):
  133. today = datetime.date.today()
  134. tz_one = get_fixed_timezone(-720)
  135. tz_two = get_fixed_timezone(720)
  136. # Can be today or yesterday
  137. date_one = datetime.datetime(today.year, today.month, today.day, tzinfo=tz_one)
  138. naturalday_one = humanize.naturalday(date_one)
  139. # Can be today or tomorrow
  140. date_two = datetime.datetime(today.year, today.month, today.day, tzinfo=tz_two)
  141. naturalday_two = humanize.naturalday(date_two)
  142. # As 24h of difference they will never be the same
  143. self.assertNotEqual(naturalday_one, naturalday_two)
  144. def test_naturalday_uses_localtime(self):
  145. # Regression for #18504
  146. # This is 2012-03-08HT19:30:00-06:00 in America/Chicago
  147. dt = datetime.datetime(2012, 3, 9, 1, 30, tzinfo=utc)
  148. orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime
  149. try:
  150. with override_settings(TIME_ZONE="America/Chicago", USE_TZ=True):
  151. with translation.override('en'):
  152. self.humanize_tester([dt], ['yesterday'], 'naturalday')
  153. finally:
  154. humanize.datetime = orig_humanize_datetime
  155. def test_naturaltime(self):
  156. class naive(datetime.tzinfo):
  157. def utcoffset(self, dt):
  158. return None
  159. test_list = [
  160. now,
  161. now - datetime.timedelta(seconds=1),
  162. now - datetime.timedelta(seconds=30),
  163. now - datetime.timedelta(minutes=1, seconds=30),
  164. now - datetime.timedelta(minutes=2),
  165. now - datetime.timedelta(hours=1, minutes=30, seconds=30),
  166. now - datetime.timedelta(hours=23, minutes=50, seconds=50),
  167. now - datetime.timedelta(days=1),
  168. now - datetime.timedelta(days=500),
  169. now + datetime.timedelta(seconds=1),
  170. now + datetime.timedelta(seconds=30),
  171. now + datetime.timedelta(minutes=1, seconds=30),
  172. now + datetime.timedelta(minutes=2),
  173. now + datetime.timedelta(hours=1, minutes=30, seconds=30),
  174. now + datetime.timedelta(hours=23, minutes=50, seconds=50),
  175. now + datetime.timedelta(days=1),
  176. now + datetime.timedelta(days=2, hours=6),
  177. now + datetime.timedelta(days=500),
  178. now.replace(tzinfo=naive()),
  179. now.replace(tzinfo=utc),
  180. ]
  181. result_list = [
  182. 'now',
  183. 'a second ago',
  184. '30\xa0seconds ago',
  185. 'a minute ago',
  186. '2\xa0minutes ago',
  187. 'an hour ago',
  188. '23\xa0hours ago',
  189. '1\xa0day ago',
  190. '1\xa0year, 4\xa0months ago',
  191. 'a second from now',
  192. '30\xa0seconds from now',
  193. 'a minute from now',
  194. '2\xa0minutes from now',
  195. 'an hour from now',
  196. '23\xa0hours from now',
  197. '1\xa0day from now',
  198. '2\xa0days, 6\xa0hours from now',
  199. '1\xa0year, 4\xa0months from now',
  200. 'now',
  201. 'now',
  202. ]
  203. # Because of the DST change, 2 days and 6 hours after the chosen
  204. # date in naive arithmetic is only 2 days and 5 hours after in
  205. # aware arithmetic.
  206. result_list_with_tz_support = result_list[:]
  207. assert result_list_with_tz_support[-4] == '2\xa0days, 6\xa0hours from now'
  208. result_list_with_tz_support[-4] == '2\xa0days, 5\xa0hours from now'
  209. orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime
  210. try:
  211. with translation.override('en'):
  212. self.humanize_tester(test_list, result_list, 'naturaltime')
  213. with override_settings(USE_TZ=True):
  214. self.humanize_tester(
  215. test_list, result_list_with_tz_support, 'naturaltime')
  216. finally:
  217. humanize.datetime = orig_humanize_datetime
  218. def test_naturaltime_as_documented(self):
  219. """
  220. #23340 -- Verify the documented behavior of humanize.naturaltime.
  221. """
  222. time_format = '%d %b %Y %H:%M:%S'
  223. documented_now = datetime.datetime.strptime('17 Feb 2007 16:30:00', time_format)
  224. test_data = (
  225. ('17 Feb 2007 16:30:00', 'now'),
  226. ('17 Feb 2007 16:29:31', '29 seconds ago'),
  227. ('17 Feb 2007 16:29:00', 'a minute ago'),
  228. ('17 Feb 2007 16:25:35', '4 minutes ago'),
  229. ('17 Feb 2007 15:30:29', '59 minutes ago'),
  230. ('17 Feb 2007 15:30:01', '59 minutes ago'),
  231. ('17 Feb 2007 15:30:00', 'an hour ago'),
  232. ('17 Feb 2007 13:31:29', '2 hours ago'),
  233. ('16 Feb 2007 13:31:29', '1 day, 2 hours ago'),
  234. ('16 Feb 2007 13:30:01', '1 day, 2 hours ago'),
  235. ('16 Feb 2007 13:30:00', '1 day, 3 hours ago'),
  236. ('17 Feb 2007 16:30:30', '30 seconds from now'),
  237. ('17 Feb 2007 16:30:29', '29 seconds from now'),
  238. ('17 Feb 2007 16:31:00', 'a minute from now'),
  239. ('17 Feb 2007 16:34:35', '4 minutes from now'),
  240. ('17 Feb 2007 17:30:29', 'an hour from now'),
  241. ('17 Feb 2007 18:31:29', '2 hours from now'),
  242. ('18 Feb 2007 16:31:29', '1 day from now'),
  243. ('26 Feb 2007 18:31:29', '1 week, 2 days from now'),
  244. )
  245. class DocumentedMockDateTime(datetime.datetime):
  246. @classmethod
  247. def now(cls, tz=None):
  248. if tz is None or tz.utcoffset(documented_now) is None:
  249. return documented_now
  250. else:
  251. return documented_now.replace(tzinfo=tz) + tz.utcoffset(now)
  252. orig_humanize_datetime = humanize.datetime
  253. humanize.datetime = DocumentedMockDateTime
  254. try:
  255. for test_time_string, expected_natural_time in test_data:
  256. test_time = datetime.datetime.strptime(test_time_string, time_format)
  257. natural_time = humanize.naturaltime(test_time).replace('\xa0', ' ')
  258. self.assertEqual(expected_natural_time, natural_time)
  259. finally:
  260. humanize.datetime = orig_humanize_datetime