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