test_strptime.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. """PyUnit testing against strptime"""
  2. import unittest
  3. import time
  4. import locale
  5. import re
  6. import os
  7. import sys
  8. from test import test_support as support
  9. from datetime import date as datetime_date
  10. import _strptime
  11. class getlang_Tests(unittest.TestCase):
  12. """Test _getlang"""
  13. def test_basic(self):
  14. self.assertEqual(_strptime._getlang(), locale.getlocale(locale.LC_TIME))
  15. class LocaleTime_Tests(unittest.TestCase):
  16. """Tests for _strptime.LocaleTime.
  17. All values are lower-cased when stored in LocaleTime, so make sure to
  18. compare values after running ``lower`` on them.
  19. """
  20. def setUp(self):
  21. """Create time tuple based on current time."""
  22. self.time_tuple = time.localtime()
  23. self.LT_ins = _strptime.LocaleTime()
  24. def compare_against_time(self, testing, directive, tuple_position,
  25. error_msg):
  26. """Helper method that tests testing against directive based on the
  27. tuple_position of time_tuple. Uses error_msg as error message.
  28. """
  29. strftime_output = time.strftime(directive, self.time_tuple).lower()
  30. comparison = testing[self.time_tuple[tuple_position]]
  31. self.assertIn(strftime_output, testing,
  32. "%s: not found in tuple" % error_msg)
  33. self.assertEqual(comparison, strftime_output,
  34. "%s: position within tuple incorrect; %s != %s" %
  35. (error_msg, comparison, strftime_output))
  36. def test_weekday(self):
  37. # Make sure that full and abbreviated weekday names are correct in
  38. # both string and position with tuple
  39. self.compare_against_time(self.LT_ins.f_weekday, '%A', 6,
  40. "Testing of full weekday name failed")
  41. self.compare_against_time(self.LT_ins.a_weekday, '%a', 6,
  42. "Testing of abbreviated weekday name failed")
  43. def test_month(self):
  44. # Test full and abbreviated month names; both string and position
  45. # within the tuple
  46. self.compare_against_time(self.LT_ins.f_month, '%B', 1,
  47. "Testing against full month name failed")
  48. self.compare_against_time(self.LT_ins.a_month, '%b', 1,
  49. "Testing against abbreviated month name failed")
  50. def test_am_pm(self):
  51. # Make sure AM/PM representation done properly
  52. strftime_output = time.strftime("%p", self.time_tuple).lower()
  53. self.assertIn(strftime_output, self.LT_ins.am_pm,
  54. "AM/PM representation not in tuple")
  55. if self.time_tuple[3] < 12: position = 0
  56. else: position = 1
  57. self.assertEqual(self.LT_ins.am_pm[position], strftime_output,
  58. "AM/PM representation in the wrong position within the tuple")
  59. def test_timezone(self):
  60. # Make sure timezone is correct
  61. timezone = time.strftime("%Z", self.time_tuple).lower()
  62. if timezone:
  63. self.assertTrue(timezone in self.LT_ins.timezone[0] or
  64. timezone in self.LT_ins.timezone[1],
  65. "timezone %s not found in %s" %
  66. (timezone, self.LT_ins.timezone))
  67. def test_date_time(self):
  68. # Check that LC_date_time, LC_date, and LC_time are correct
  69. # the magic date is used so as to not have issues with %c when day of
  70. # the month is a single digit and has a leading space. This is not an
  71. # issue since strptime still parses it correctly. The problem is
  72. # testing these directives for correctness by comparing strftime
  73. # output.
  74. magic_date = (1999, 3, 17, 22, 44, 55, 2, 76, 0)
  75. strftime_output = time.strftime("%c", magic_date)
  76. self.assertEqual(time.strftime(self.LT_ins.LC_date_time, magic_date),
  77. strftime_output, "LC_date_time incorrect")
  78. strftime_output = time.strftime("%x", magic_date)
  79. self.assertEqual(time.strftime(self.LT_ins.LC_date, magic_date),
  80. strftime_output, "LC_date incorrect")
  81. strftime_output = time.strftime("%X", magic_date)
  82. self.assertEqual(time.strftime(self.LT_ins.LC_time, magic_date),
  83. strftime_output, "LC_time incorrect")
  84. LT = _strptime.LocaleTime()
  85. LT.am_pm = ('', '')
  86. self.assertTrue(LT.LC_time, "LocaleTime's LC directives cannot handle "
  87. "empty strings")
  88. def test_lang(self):
  89. # Make sure lang is set to what _getlang() returns
  90. # Assuming locale has not changed between now and when self.LT_ins was created
  91. self.assertEqual(self.LT_ins.lang, _strptime._getlang())
  92. class TimeRETests(unittest.TestCase):
  93. """Tests for TimeRE."""
  94. def setUp(self):
  95. """Construct generic TimeRE object."""
  96. self.time_re = _strptime.TimeRE()
  97. self.locale_time = _strptime.LocaleTime()
  98. def test_pattern(self):
  99. # Test TimeRE.pattern
  100. pattern_string = self.time_re.pattern(r"%a %A %d")
  101. self.assertTrue(pattern_string.find(self.locale_time.a_weekday[2]) != -1,
  102. "did not find abbreviated weekday in pattern string '%s'" %
  103. pattern_string)
  104. self.assertTrue(pattern_string.find(self.locale_time.f_weekday[4]) != -1,
  105. "did not find full weekday in pattern string '%s'" %
  106. pattern_string)
  107. self.assertTrue(pattern_string.find(self.time_re['d']) != -1,
  108. "did not find 'd' directive pattern string '%s'" %
  109. pattern_string)
  110. def test_pattern_escaping(self):
  111. # Make sure any characters in the format string that might be taken as
  112. # regex syntax is escaped.
  113. pattern_string = self.time_re.pattern("\d+")
  114. self.assertIn(r"\\d\+", pattern_string,
  115. "%s does not have re characters escaped properly" %
  116. pattern_string)
  117. def test_compile(self):
  118. # Check that compiled regex is correct
  119. found = self.time_re.compile(r"%A").match(self.locale_time.f_weekday[6])
  120. self.assertTrue(found and found.group('A') == self.locale_time.f_weekday[6],
  121. "re object for '%A' failed")
  122. compiled = self.time_re.compile(r"%a %b")
  123. found = compiled.match("%s %s" % (self.locale_time.a_weekday[4],
  124. self.locale_time.a_month[4]))
  125. self.assertTrue(found,
  126. "Match failed with '%s' regex and '%s' string" %
  127. (compiled.pattern, "%s %s" % (self.locale_time.a_weekday[4],
  128. self.locale_time.a_month[4])))
  129. self.assertTrue(found.group('a') == self.locale_time.a_weekday[4] and
  130. found.group('b') == self.locale_time.a_month[4],
  131. "re object couldn't find the abbreviated weekday month in "
  132. "'%s' using '%s'; group 'a' = '%s', group 'b' = %s'" %
  133. (found.string, found.re.pattern, found.group('a'),
  134. found.group('b')))
  135. for directive in ('a','A','b','B','c','d','H','I','j','m','M','p','S',
  136. 'U','w','W','x','X','y','Y','Z','%'):
  137. compiled = self.time_re.compile("%" + directive)
  138. found = compiled.match(time.strftime("%" + directive))
  139. self.assertTrue(found, "Matching failed on '%s' using '%s' regex" %
  140. (time.strftime("%" + directive),
  141. compiled.pattern))
  142. def test_blankpattern(self):
  143. # Make sure when tuple or something has no values no regex is generated.
  144. # Fixes bug #661354
  145. test_locale = _strptime.LocaleTime()
  146. test_locale.timezone = (frozenset(), frozenset())
  147. self.assertEqual(_strptime.TimeRE(test_locale).pattern("%Z"), '',
  148. "with timezone == ('',''), TimeRE().pattern('%Z') != ''")
  149. def test_matching_with_escapes(self):
  150. # Make sure a format that requires escaping of characters works
  151. compiled_re = self.time_re.compile("\w+ %m")
  152. found = compiled_re.match("\w+ 10")
  153. self.assertTrue(found, "Escaping failed of format '\w+ 10'")
  154. def test_locale_data_w_regex_metacharacters(self):
  155. # Check that if locale data contains regex metacharacters they are
  156. # escaped properly.
  157. # Discovered by bug #1039270 .
  158. locale_time = _strptime.LocaleTime()
  159. locale_time.timezone = (frozenset(("utc", "gmt",
  160. "Tokyo (standard time)")),
  161. frozenset("Tokyo (daylight time)"))
  162. time_re = _strptime.TimeRE(locale_time)
  163. self.assertTrue(time_re.compile("%Z").match("Tokyo (standard time)"),
  164. "locale data that contains regex metacharacters is not"
  165. " properly escaped")
  166. def test_whitespace_substitution(self):
  167. # When pattern contains whitespace, make sure it is taken into account
  168. # so as to not allow subpatterns to end up next to each other and
  169. # "steal" characters from each other.
  170. pattern = self.time_re.pattern('%j %H')
  171. self.assertFalse(re.match(pattern, "180"))
  172. self.assertTrue(re.match(pattern, "18 0"))
  173. class StrptimeTests(unittest.TestCase):
  174. """Tests for _strptime.strptime."""
  175. def setUp(self):
  176. """Create testing time tuple."""
  177. self.time_tuple = time.gmtime()
  178. def test_ValueError(self):
  179. # Make sure ValueError is raised when match fails or format is bad
  180. self.assertRaises(ValueError, _strptime._strptime_time, data_string="%d",
  181. format="%A")
  182. for bad_format in ("%", "% ", "%e"):
  183. try:
  184. _strptime._strptime_time("2005", bad_format)
  185. except ValueError:
  186. continue
  187. except Exception, err:
  188. self.fail("'%s' raised %s, not ValueError" %
  189. (bad_format, err.__class__.__name__))
  190. else:
  191. self.fail("'%s' did not raise ValueError" % bad_format)
  192. def test_unconverteddata(self):
  193. # Check ValueError is raised when there is unconverted data
  194. self.assertRaises(ValueError, _strptime._strptime_time, "10 12", "%m")
  195. def helper(self, directive, position):
  196. """Helper fxn in testing."""
  197. strf_output = time.strftime("%" + directive, self.time_tuple)
  198. strp_output = _strptime._strptime_time(strf_output, "%" + directive)
  199. self.assertTrue(strp_output[position] == self.time_tuple[position],
  200. "testing of '%s' directive failed; '%s' -> %s != %s" %
  201. (directive, strf_output, strp_output[position],
  202. self.time_tuple[position]))
  203. def test_year(self):
  204. # Test that the year is handled properly
  205. for directive in ('y', 'Y'):
  206. self.helper(directive, 0)
  207. # Must also make sure %y values are correct for bounds set by Open Group
  208. for century, bounds in ((1900, ('69', '99')), (2000, ('00', '68'))):
  209. for bound in bounds:
  210. strp_output = _strptime._strptime_time(bound, '%y')
  211. expected_result = century + int(bound)
  212. self.assertTrue(strp_output[0] == expected_result,
  213. "'y' test failed; passed in '%s' "
  214. "and returned '%s'" % (bound, strp_output[0]))
  215. def test_month(self):
  216. # Test for month directives
  217. for directive in ('B', 'b', 'm'):
  218. self.helper(directive, 1)
  219. def test_day(self):
  220. # Test for day directives
  221. self.helper('d', 2)
  222. def test_hour(self):
  223. # Test hour directives
  224. self.helper('H', 3)
  225. strf_output = time.strftime("%I %p", self.time_tuple)
  226. strp_output = _strptime._strptime_time(strf_output, "%I %p")
  227. self.assertTrue(strp_output[3] == self.time_tuple[3],
  228. "testing of '%%I %%p' directive failed; '%s' -> %s != %s" %
  229. (strf_output, strp_output[3], self.time_tuple[3]))
  230. def test_minute(self):
  231. # Test minute directives
  232. self.helper('M', 4)
  233. def test_second(self):
  234. # Test second directives
  235. self.helper('S', 5)
  236. def test_fraction(self):
  237. # Test microseconds
  238. import datetime
  239. d = datetime.datetime(2012, 12, 20, 12, 34, 56, 78987)
  240. tup, frac = _strptime._strptime(str(d), format="%Y-%m-%d %H:%M:%S.%f")
  241. self.assertEqual(frac, d.microsecond)
  242. def test_weekday(self):
  243. # Test weekday directives
  244. for directive in ('A', 'a', 'w'):
  245. self.helper(directive,6)
  246. def test_julian(self):
  247. # Test julian directives
  248. self.helper('j', 7)
  249. def test_timezone(self):
  250. # Test timezone directives.
  251. # When gmtime() is used with %Z, entire result of strftime() is empty.
  252. # Check for equal timezone names deals with bad locale info when this
  253. # occurs; first found in FreeBSD 4.4.
  254. strp_output = _strptime._strptime_time("UTC", "%Z")
  255. self.assertEqual(strp_output.tm_isdst, 0)
  256. strp_output = _strptime._strptime_time("GMT", "%Z")
  257. self.assertEqual(strp_output.tm_isdst, 0)
  258. time_tuple = time.localtime()
  259. strf_output = time.strftime("%Z") #UTC does not have a timezone
  260. strp_output = _strptime._strptime_time(strf_output, "%Z")
  261. locale_time = _strptime.LocaleTime()
  262. if time.tzname[0] != time.tzname[1] or not time.daylight:
  263. self.assertTrue(strp_output[8] == time_tuple[8],
  264. "timezone check failed; '%s' -> %s != %s" %
  265. (strf_output, strp_output[8], time_tuple[8]))
  266. else:
  267. self.assertTrue(strp_output[8] == -1,
  268. "LocaleTime().timezone has duplicate values and "
  269. "time.daylight but timezone value not set to -1")
  270. def test_bad_timezone(self):
  271. # Explicitly test possibility of bad timezone;
  272. # when time.tzname[0] == time.tzname[1] and time.daylight
  273. tz_name = time.tzname[0]
  274. if tz_name.upper() in ("UTC", "GMT"):
  275. self.skipTest('need non-UTC/GMT timezone')
  276. with support.swap_attr(time, 'tzname', (tz_name, tz_name)), \
  277. support.swap_attr(time, 'daylight', 1), \
  278. support.swap_attr(time, 'tzset', lambda: None):
  279. time.tzname = (tz_name, tz_name)
  280. time.daylight = 1
  281. tz_value = _strptime._strptime_time(tz_name, "%Z")[8]
  282. self.assertEqual(tz_value, -1,
  283. "%s lead to a timezone value of %s instead of -1 when "
  284. "time.daylight set to %s and passing in %s" %
  285. (time.tzname, tz_value, time.daylight, tz_name))
  286. def test_date_time(self):
  287. # Test %c directive
  288. for position in range(6):
  289. self.helper('c', position)
  290. def test_date(self):
  291. # Test %x directive
  292. for position in range(0,3):
  293. self.helper('x', position)
  294. def test_time(self):
  295. # Test %X directive
  296. for position in range(3,6):
  297. self.helper('X', position)
  298. def test_percent(self):
  299. # Make sure % signs are handled properly
  300. strf_output = time.strftime("%m %% %Y", self.time_tuple)
  301. strp_output = _strptime._strptime_time(strf_output, "%m %% %Y")
  302. self.assertTrue(strp_output[0] == self.time_tuple[0] and
  303. strp_output[1] == self.time_tuple[1],
  304. "handling of percent sign failed")
  305. def test_caseinsensitive(self):
  306. # Should handle names case-insensitively.
  307. strf_output = time.strftime("%B", self.time_tuple)
  308. self.assertTrue(_strptime._strptime_time(strf_output.upper(), "%B"),
  309. "strptime does not handle ALL-CAPS names properly")
  310. self.assertTrue(_strptime._strptime_time(strf_output.lower(), "%B"),
  311. "strptime does not handle lowercase names properly")
  312. self.assertTrue(_strptime._strptime_time(strf_output.capitalize(), "%B"),
  313. "strptime does not handle capword names properly")
  314. def test_defaults(self):
  315. # Default return value should be (1900, 1, 1, 0, 0, 0, 0, 1, 0)
  316. defaults = (1900, 1, 1, 0, 0, 0, 0, 1, -1)
  317. strp_output = _strptime._strptime_time('1', '%m')
  318. self.assertTrue(strp_output == defaults,
  319. "Default values for strptime() are incorrect;"
  320. " %s != %s" % (strp_output, defaults))
  321. def test_escaping(self):
  322. # Make sure all characters that have regex significance are escaped.
  323. # Parentheses are in a purposeful order; will cause an error of
  324. # unbalanced parentheses when the regex is compiled if they are not
  325. # escaped.
  326. # Test instigated by bug #796149 .
  327. need_escaping = ".^$*+?{}\[]|)("
  328. self.assertTrue(_strptime._strptime_time(need_escaping, need_escaping))
  329. def test_feb29_on_leap_year_without_year(self):
  330. time.strptime("Feb 29", "%b %d")
  331. def test_mar1_comes_after_feb29_even_when_omitting_the_year(self):
  332. self.assertLess(
  333. time.strptime("Feb 29", "%b %d"),
  334. time.strptime("Mar 1", "%b %d"))
  335. class Strptime12AMPMTests(unittest.TestCase):
  336. """Test a _strptime regression in '%I %p' at 12 noon (12 PM)"""
  337. def test_twelve_noon_midnight(self):
  338. eq = self.assertEqual
  339. eq(time.strptime('12 PM', '%I %p')[3], 12)
  340. eq(time.strptime('12 AM', '%I %p')[3], 0)
  341. eq(_strptime._strptime_time('12 PM', '%I %p')[3], 12)
  342. eq(_strptime._strptime_time('12 AM', '%I %p')[3], 0)
  343. class JulianTests(unittest.TestCase):
  344. """Test a _strptime regression that all julian (1-366) are accepted"""
  345. def test_all_julian_days(self):
  346. eq = self.assertEqual
  347. for i in range(1, 367):
  348. # use 2004, since it is a leap year, we have 366 days
  349. eq(_strptime._strptime_time('%d 2004' % i, '%j %Y')[7], i)
  350. class CalculationTests(unittest.TestCase):
  351. """Test that strptime() fills in missing info correctly"""
  352. def setUp(self):
  353. self.time_tuple = time.gmtime()
  354. def test_julian_calculation(self):
  355. # Make sure that when Julian is missing that it is calculated
  356. format_string = "%Y %m %d %H %M %S %w %Z"
  357. result = _strptime._strptime_time(time.strftime(format_string, self.time_tuple),
  358. format_string)
  359. self.assertTrue(result.tm_yday == self.time_tuple.tm_yday,
  360. "Calculation of tm_yday failed; %s != %s" %
  361. (result.tm_yday, self.time_tuple.tm_yday))
  362. def test_gregorian_calculation(self):
  363. # Test that Gregorian date can be calculated from Julian day
  364. format_string = "%Y %H %M %S %w %j %Z"
  365. result = _strptime._strptime_time(time.strftime(format_string, self.time_tuple),
  366. format_string)
  367. self.assertTrue(result.tm_year == self.time_tuple.tm_year and
  368. result.tm_mon == self.time_tuple.tm_mon and
  369. result.tm_mday == self.time_tuple.tm_mday,
  370. "Calculation of Gregorian date failed;"
  371. "%s-%s-%s != %s-%s-%s" %
  372. (result.tm_year, result.tm_mon, result.tm_mday,
  373. self.time_tuple.tm_year, self.time_tuple.tm_mon,
  374. self.time_tuple.tm_mday))
  375. def test_day_of_week_calculation(self):
  376. # Test that the day of the week is calculated as needed
  377. format_string = "%Y %m %d %H %S %j %Z"
  378. result = _strptime._strptime_time(time.strftime(format_string, self.time_tuple),
  379. format_string)
  380. self.assertTrue(result.tm_wday == self.time_tuple.tm_wday,
  381. "Calculation of day of the week failed;"
  382. "%s != %s" % (result.tm_wday, self.time_tuple.tm_wday))
  383. def test_week_of_year_and_day_of_week_calculation(self):
  384. # Should be able to infer date if given year, week of year (%U or %W)
  385. # and day of the week
  386. def test_helper(ymd_tuple, test_reason):
  387. for directive in ('W', 'U'):
  388. format_string = "%%Y %%%s %%w" % directive
  389. dt_date = datetime_date(*ymd_tuple)
  390. strp_input = dt_date.strftime(format_string)
  391. strp_output = _strptime._strptime_time(strp_input, format_string)
  392. self.assertTrue(strp_output[:3] == ymd_tuple,
  393. "%s(%s) test failed w/ '%s': %s != %s (%s != %s)" %
  394. (test_reason, directive, strp_input,
  395. strp_output[:3], ymd_tuple,
  396. strp_output[7], dt_date.timetuple()[7]))
  397. test_helper((1901, 1, 3), "week 0")
  398. test_helper((1901, 1, 8), "common case")
  399. test_helper((1901, 1, 13), "day on Sunday")
  400. test_helper((1901, 1, 14), "day on Monday")
  401. test_helper((1905, 1, 1), "Jan 1 on Sunday")
  402. test_helper((1906, 1, 1), "Jan 1 on Monday")
  403. test_helper((1906, 1, 7), "first Sunday in a year starting on Monday")
  404. test_helper((1905, 12, 31), "Dec 31 on Sunday")
  405. test_helper((1906, 12, 31), "Dec 31 on Monday")
  406. test_helper((2008, 12, 29), "Monday in the last week of the year")
  407. test_helper((2008, 12, 22), "Monday in the second-to-last week of the "
  408. "year")
  409. test_helper((1978, 10, 23), "randomly chosen date")
  410. test_helper((2004, 12, 18), "randomly chosen date")
  411. test_helper((1978, 10, 23), "year starting and ending on Monday while "
  412. "date not on Sunday or Monday")
  413. test_helper((1917, 12, 17), "year starting and ending on Monday with "
  414. "a Monday not at the beginning or end "
  415. "of the year")
  416. test_helper((1917, 12, 31), "Dec 31 on Monday with year starting and "
  417. "ending on Monday")
  418. test_helper((2007, 01, 07), "First Sunday of 2007")
  419. test_helper((2007, 01, 14), "Second Sunday of 2007")
  420. test_helper((2006, 12, 31), "Last Sunday of 2006")
  421. test_helper((2006, 12, 24), "Second to last Sunday of 2006")
  422. def test_week_0(self):
  423. def check(value, format, *expected):
  424. self.assertEqual(_strptime._strptime_time(value, format)[:-1], expected)
  425. check('2015 0 0', '%Y %U %w', 2014, 12, 28, 0, 0, 0, 6, 362)
  426. check('2015 0 0', '%Y %W %w', 2015, 1, 4, 0, 0, 0, 6, 4)
  427. check('2015 0 1', '%Y %U %w', 2014, 12, 29, 0, 0, 0, 0, 363)
  428. check('2015 0 1', '%Y %W %w', 2014, 12, 29, 0, 0, 0, 0, 363)
  429. check('2015 0 2', '%Y %U %w', 2014, 12, 30, 0, 0, 0, 1, 364)
  430. check('2015 0 2', '%Y %W %w', 2014, 12, 30, 0, 0, 0, 1, 364)
  431. check('2015 0 3', '%Y %U %w', 2014, 12, 31, 0, 0, 0, 2, 365)
  432. check('2015 0 3', '%Y %W %w', 2014, 12, 31, 0, 0, 0, 2, 365)
  433. check('2015 0 4', '%Y %U %w', 2015, 1, 1, 0, 0, 0, 3, 1)
  434. check('2015 0 4', '%Y %W %w', 2015, 1, 1, 0, 0, 0, 3, 1)
  435. check('2015 0 5', '%Y %U %w', 2015, 1, 2, 0, 0, 0, 4, 2)
  436. check('2015 0 5', '%Y %W %w', 2015, 1, 2, 0, 0, 0, 4, 2)
  437. check('2015 0 6', '%Y %U %w', 2015, 1, 3, 0, 0, 0, 5, 3)
  438. check('2015 0 6', '%Y %W %w', 2015, 1, 3, 0, 0, 0, 5, 3)
  439. check('2009 0 0', '%Y %U %w', 2008, 12, 28, 0, 0, 0, 6, 363)
  440. check('2009 0 0', '%Y %W %w', 2009, 1, 4, 0, 0, 0, 6, 4)
  441. check('2009 0 1', '%Y %U %w', 2008, 12, 29, 0, 0, 0, 0, 364)
  442. check('2009 0 1', '%Y %W %w', 2008, 12, 29, 0, 0, 0, 0, 364)
  443. check('2009 0 2', '%Y %U %w', 2008, 12, 30, 0, 0, 0, 1, 365)
  444. check('2009 0 2', '%Y %W %w', 2008, 12, 30, 0, 0, 0, 1, 365)
  445. check('2009 0 3', '%Y %U %w', 2008, 12, 31, 0, 0, 0, 2, 366)
  446. check('2009 0 3', '%Y %W %w', 2008, 12, 31, 0, 0, 0, 2, 366)
  447. check('2009 0 4', '%Y %U %w', 2009, 1, 1, 0, 0, 0, 3, 1)
  448. check('2009 0 4', '%Y %W %w', 2009, 1, 1, 0, 0, 0, 3, 1)
  449. check('2009 0 5', '%Y %U %w', 2009, 1, 2, 0, 0, 0, 4, 2)
  450. check('2009 0 5', '%Y %W %w', 2009, 1, 2, 0, 0, 0, 4, 2)
  451. check('2009 0 6', '%Y %U %w', 2009, 1, 3, 0, 0, 0, 5, 3)
  452. check('2009 0 6', '%Y %W %w', 2009, 1, 3, 0, 0, 0, 5, 3)
  453. class CacheTests(unittest.TestCase):
  454. """Test that caching works properly."""
  455. def test_time_re_recreation(self):
  456. # Make sure cache is recreated when current locale does not match what
  457. # cached object was created with.
  458. _strptime._strptime_time("10", "%d")
  459. _strptime._strptime_time("2005", "%Y")
  460. _strptime._TimeRE_cache.locale_time.lang = "Ni"
  461. original_time_re = _strptime._TimeRE_cache
  462. _strptime._strptime_time("10", "%d")
  463. self.assertIsNot(original_time_re, _strptime._TimeRE_cache)
  464. self.assertEqual(len(_strptime._regex_cache), 1)
  465. def test_regex_cleanup(self):
  466. # Make sure cached regexes are discarded when cache becomes "full".
  467. try:
  468. del _strptime._regex_cache['%d']
  469. except KeyError:
  470. pass
  471. bogus_key = 0
  472. while len(_strptime._regex_cache) <= _strptime._CACHE_MAX_SIZE:
  473. _strptime._regex_cache[bogus_key] = None
  474. bogus_key += 1
  475. _strptime._strptime_time("10", "%d")
  476. self.assertEqual(len(_strptime._regex_cache), 1)
  477. def test_new_localetime(self):
  478. # A new LocaleTime instance should be created when a new TimeRE object
  479. # is created.
  480. locale_time_id = _strptime._TimeRE_cache.locale_time
  481. _strptime._TimeRE_cache.locale_time.lang = "Ni"
  482. _strptime._strptime_time("10", "%d")
  483. self.assertIsNot(locale_time_id, _strptime._TimeRE_cache.locale_time)
  484. def test_TimeRE_recreation_locale(self):
  485. # The TimeRE instance should be recreated upon changing the locale.
  486. locale_info = locale.getlocale(locale.LC_TIME)
  487. try:
  488. locale.setlocale(locale.LC_TIME, ('en_US', 'UTF8'))
  489. except locale.Error:
  490. self.skipTest('test needs en_US.UTF8 locale')
  491. try:
  492. _strptime._strptime_time('10', '%d')
  493. # Get id of current cache object.
  494. first_time_re = _strptime._TimeRE_cache
  495. try:
  496. # Change the locale and force a recreation of the cache.
  497. locale.setlocale(locale.LC_TIME, ('de_DE', 'UTF8'))
  498. _strptime._strptime_time('10', '%d')
  499. # Get the new cache object's id.
  500. second_time_re = _strptime._TimeRE_cache
  501. # They should not be equal.
  502. self.assertIsNot(first_time_re, second_time_re)
  503. # Possible test locale is not supported while initial locale is.
  504. # If this is the case just suppress the exception and fall-through
  505. # to the resetting to the original locale.
  506. except locale.Error:
  507. self.skipTest('test needs de_DE.UTF8 locale')
  508. # Make sure we don't trample on the locale setting once we leave the
  509. # test.
  510. finally:
  511. locale.setlocale(locale.LC_TIME, locale_info)
  512. @support.run_with_tz('STD-1DST')
  513. def test_TimeRE_recreation_timezone(self):
  514. # The TimeRE instance should be recreated upon changing the timezone.
  515. oldtzname = time.tzname
  516. tm = _strptime._strptime_time(time.tzname[0], '%Z')
  517. self.assertEqual(tm.tm_isdst, 0)
  518. tm = _strptime._strptime_time(time.tzname[1], '%Z')
  519. self.assertEqual(tm.tm_isdst, 1)
  520. # Get id of current cache object.
  521. first_time_re = _strptime._TimeRE_cache
  522. # Change the timezone and force a recreation of the cache.
  523. os.environ['TZ'] = 'EST+05EDT,M3.2.0,M11.1.0'
  524. time.tzset()
  525. tm = _strptime._strptime_time(time.tzname[0], '%Z')
  526. self.assertEqual(tm.tm_isdst, 0)
  527. tm = _strptime._strptime_time(time.tzname[1], '%Z')
  528. self.assertEqual(tm.tm_isdst, 1)
  529. # Get the new cache object's id.
  530. second_time_re = _strptime._TimeRE_cache
  531. # They should not be equal.
  532. self.assertIsNot(first_time_re, second_time_re)
  533. # Make sure old names no longer accepted.
  534. with self.assertRaises(ValueError):
  535. _strptime._strptime_time(oldtzname[0], '%Z')
  536. with self.assertRaises(ValueError):
  537. _strptime._strptime_time(oldtzname[1], '%Z')
  538. def test_main():
  539. support.run_unittest(
  540. getlang_Tests,
  541. LocaleTime_Tests,
  542. TimeRETests,
  543. StrptimeTests,
  544. Strptime12AMPMTests,
  545. JulianTests,
  546. CalculationTests,
  547. CacheTests
  548. )
  549. if __name__ == '__main__':
  550. test_main()