0001 """PyUnit testing against strptime""" 0002 0003 import unittest 0004 import time 0005 import locale 0006 import re 0007 import sys 0008 from test import test_support 0009 from datetime import date as datetime_date 0010 0011 import _strptime 0012 0013 class getlang_Tests(unittest.TestCase): 0014 """Test _getlang""" 0015 def test_basic(self): 0016 self.failUnlessEqual(_strptime._getlang(), locale.getlocale(locale.LC_TIME)) 0017 0018 class LocaleTime_Tests(unittest.TestCase): 0019 """Tests for _strptime.LocaleTime. 0020 0021 All values are lower-cased when stored in LocaleTime, so make sure to 0022 compare values after running ``lower`` on them. 0023 0024 """ 0025 0026 def setUp(self): 0027 """Create time tuple based on current time.""" 0028 self.time_tuple = time.localtime() 0029 self.LT_ins = _strptime.LocaleTime() 0030 0031 def compare_against_time(self, testing, directive, tuple_position, 0032 error_msg): 0033 """Helper method that tests testing against directive based on the 0034 tuple_position of time_tuple. Uses error_msg as error message. 0035 0036 """ 0037 strftime_output = time.strftime(directive, self.time_tuple).lower() 0038 comparison = testing[self.time_tuple[tuple_position]] 0039 self.failUnless(strftime_output in testing, "%s: not found in tuple" % 0040 error_msg) 0041 self.failUnless(comparison == strftime_output, 0042 "%s: position within tuple incorrect; %s != %s" % 0043 (error_msg, comparison, strftime_output)) 0044 0045 def test_weekday(self): 0046 # Make sure that full and abbreviated weekday names are correct in 0047 # both string and position with tuple 0048 self.compare_against_time(self.LT_ins.f_weekday, '%A', 6, 0049 "Testing of full weekday name failed") 0050 self.compare_against_time(self.LT_ins.a_weekday, '%a', 6, 0051 "Testing of abbreviated weekday name failed") 0052 0053 def test_month(self): 0054 # Test full and abbreviated month names; both string and position 0055 # within the tuple 0056 self.compare_against_time(self.LT_ins.f_month, '%B', 1, 0057 "Testing against full month name failed") 0058 self.compare_against_time(self.LT_ins.a_month, '%b', 1, 0059 "Testing against abbreviated month name failed") 0060 0061 def test_am_pm(self): 0062 # Make sure AM/PM representation done properly 0063 strftime_output = time.strftime("%p", self.time_tuple).lower() 0064 self.failUnless(strftime_output in self.LT_ins.am_pm, 0065 "AM/PM representation not in tuple") 0066 if self.time_tuple[3] < 12: position = 0 0067 else: position = 1 0068 self.failUnless(strftime_output == self.LT_ins.am_pm[position], 0069 "AM/PM representation in the wrong position within the tuple") 0070 0071 def test_timezone(self): 0072 # Make sure timezone is correct 0073 timezone = time.strftime("%Z", self.time_tuple).lower() 0074 if timezone: 0075 self.failUnless(timezone in self.LT_ins.timezone[0] or \ 0076 timezone in self.LT_ins.timezone[1], 0077 "timezone %s not found in %s" % 0078 (timezone, self.LT_ins.timezone)) 0079 0080 def test_date_time(self): 0081 # Check that LC_date_time, LC_date, and LC_time are correct 0082 # the magic date is used so as to not have issues with %c when day of 0083 # the month is a single digit and has a leading space. This is not an 0084 # issue since strptime still parses it correctly. The problem is 0085 # testing these directives for correctness by comparing strftime 0086 # output. 0087 magic_date = (1999, 3, 17, 22, 44, 55, 2, 76, 0) 0088 strftime_output = time.strftime("%c", magic_date) 0089 self.failUnless(strftime_output == time.strftime(self.LT_ins.LC_date_time, 0090 magic_date), 0091 "LC_date_time incorrect") 0092 strftime_output = time.strftime("%x", magic_date) 0093 self.failUnless(strftime_output == time.strftime(self.LT_ins.LC_date, 0094 magic_date), 0095 "LC_date incorrect") 0096 strftime_output = time.strftime("%X", magic_date) 0097 self.failUnless(strftime_output == time.strftime(self.LT_ins.LC_time, 0098 magic_date), 0099 "LC_time incorrect") 0100 LT = _strptime.LocaleTime() 0101 LT.am_pm = ('', '') 0102 self.failUnless(LT.LC_time, "LocaleTime's LC directives cannot handle " 0103 "empty strings") 0104 0105 def test_lang(self): 0106 # Make sure lang is set to what _getlang() returns 0107 # Assuming locale has not changed between now and when self.LT_ins was created 0108 self.failUnlessEqual(self.LT_ins.lang, _strptime._getlang()) 0109 0110 0111 class TimeRETests(unittest.TestCase): 0112 """Tests for TimeRE.""" 0113 0114 def setUp(self): 0115 """Construct generic TimeRE object.""" 0116 self.time_re = _strptime.TimeRE() 0117 self.locale_time = _strptime.LocaleTime() 0118 0119 def test_pattern(self): 0120 # Test TimeRE.pattern 0121 pattern_string = self.time_re.pattern(r"%a %A %d") 0122 self.failUnless(pattern_string.find(self.locale_time.a_weekday[2]) != -1, 0123 "did not find abbreviated weekday in pattern string '%s'" % 0124 pattern_string) 0125 self.failUnless(pattern_string.find(self.locale_time.f_weekday[4]) != -1, 0126 "did not find full weekday in pattern string '%s'" % 0127 pattern_string) 0128 self.failUnless(pattern_string.find(self.time_re['d']) != -1, 0129 "did not find 'd' directive pattern string '%s'" % 0130 pattern_string) 0131 0132 def test_pattern_escaping(self): 0133 # Make sure any characters in the format string that might be taken as 0134 # regex syntax is escaped. 0135 pattern_string = self.time_re.pattern("\d+") 0136 self.failUnless(r"\\d\+" in pattern_string, 0137 "%s does not have re characters escaped properly" % 0138 pattern_string) 0139 0140 def test_compile(self): 0141 # Check that compiled regex is correct 0142 found = self.time_re.compile(r"%A").match(self.locale_time.f_weekday[6]) 0143 self.failUnless(found and found.group('A') == self.locale_time.f_weekday[6], 0144 "re object for '%A' failed") 0145 compiled = self.time_re.compile(r"%a %b") 0146 found = compiled.match("%s %s" % (self.locale_time.a_weekday[4], 0147 self.locale_time.a_month[4])) 0148 self.failUnless(found, 0149 "Match failed with '%s' regex and '%s' string" % 0150 (compiled.pattern, "%s %s" % (self.locale_time.a_weekday[4], 0151 self.locale_time.a_month[4]))) 0152 self.failUnless(found.group('a') == self.locale_time.a_weekday[4] and 0153 found.group('b') == self.locale_time.a_month[4], 0154 "re object couldn't find the abbreviated weekday month in " 0155 "'%s' using '%s'; group 'a' = '%s', group 'b' = %s'" % 0156 (found.string, found.re.pattern, found.group('a'), 0157 found.group('b'))) 0158 for directive in ('a','A','b','B','c','d','H','I','j','m','M','p','S', 0159 'U','w','W','x','X','y','Y','Z','%'): 0160 compiled = self.time_re.compile("%" + directive) 0161 found = compiled.match(time.strftime("%" + directive)) 0162 self.failUnless(found, "Matching failed on '%s' using '%s' regex" % 0163 (time.strftime("%" + directive), 0164 compiled.pattern)) 0165 0166 def test_blankpattern(self): 0167 # Make sure when tuple or something has no values no regex is generated. 0168 # Fixes bug #661354 0169 test_locale = _strptime.LocaleTime() 0170 test_locale.timezone = (frozenset(), frozenset()) 0171 self.failUnless(_strptime.TimeRE(test_locale).pattern("%Z") == '', 0172 "with timezone == ('',''), TimeRE().pattern('%Z') != ''") 0173 0174 def test_matching_with_escapes(self): 0175 # Make sure a format that requires escaping of characters works 0176 compiled_re = self.time_re.compile("\w+ %m") 0177 found = compiled_re.match("\w+ 10") 0178 self.failUnless(found, "Escaping failed of format '\w+ 10'") 0179 0180 def test_locale_data_w_regex_metacharacters(self): 0181 # Check that if locale data contains regex metacharacters they are 0182 # escaped properly. 0183 # Discovered by bug #1039270 . 0184 locale_time = _strptime.LocaleTime() 0185 locale_time.timezone = (frozenset(("utc", "gmt", 0186 "Tokyo (standard time)")), 0187 frozenset("Tokyo (daylight time)")) 0188 time_re = _strptime.TimeRE(locale_time) 0189 self.failUnless(time_re.compile("%Z").match("Tokyo (standard time)"), 0190 "locale data that contains regex metacharacters is not" 0191 " properly escaped") 0192 0193 class StrptimeTests(unittest.TestCase): 0194 """Tests for _strptime.strptime.""" 0195 0196 def setUp(self): 0197 """Create testing time tuple.""" 0198 self.time_tuple = time.gmtime() 0199 0200 def test_TypeError(self): 0201 # Make sure ValueError is raised when match fails 0202 self.assertRaises(ValueError, _strptime.strptime, data_string="%d", 0203 format="%A") 0204 0205 def test_unconverteddata(self): 0206 # Check ValueError is raised when there is unconverted data 0207 self.assertRaises(ValueError, _strptime.strptime, "10 12", "%m") 0208 0209 def helper(self, directive, position): 0210 """Helper fxn in testing.""" 0211 strf_output = time.strftime("%" + directive, self.time_tuple) 0212 strp_output = _strptime.strptime(strf_output, "%" + directive) 0213 self.failUnless(strp_output[position] == self.time_tuple[position], 0214 "testing of '%s' directive failed; '%s' -> %s != %s" % 0215 (directive, strf_output, strp_output[position], 0216 self.time_tuple[position])) 0217 0218 def test_year(self): 0219 # Test that the year is handled properly 0220 for directive in ('y', 'Y'): 0221 self.helper(directive, 0) 0222 # Must also make sure %y values are correct for bounds set by Open Group 0223 for century, bounds in ((1900, ('69', '99')), (2000, ('00', '68'))): 0224 for bound in bounds: 0225 strp_output = _strptime.strptime(bound, '%y') 0226 expected_result = century + int(bound) 0227 self.failUnless(strp_output[0] == expected_result, 0228 "'y' test failed; passed in '%s' " 0229 "and returned '%s'" % (bound, strp_output[0])) 0230 0231 def test_month(self): 0232 # Test for month directives 0233 for directive in ('B', 'b', 'm'): 0234 self.helper(directive, 1) 0235 0236 def test_day(self): 0237 # Test for day directives 0238 self.helper('d', 2) 0239 0240 def test_hour(self): 0241 # Test hour directives 0242 self.helper('H', 3) 0243 strf_output = time.strftime("%I %p", self.time_tuple) 0244 strp_output = _strptime.strptime(strf_output, "%I %p") 0245 self.failUnless(strp_output[3] == self.time_tuple[3], 0246 "testing of '%%I %%p' directive failed; '%s' -> %s != %s" % 0247 (strf_output, strp_output[3], self.time_tuple[3])) 0248 0249 def test_minute(self): 0250 # Test minute directives 0251 self.helper('M', 4) 0252 0253 def test_second(self): 0254 # Test second directives 0255 self.helper('S', 5) 0256 0257 def test_weekday(self): 0258 # Test weekday directives 0259 for directive in ('A', 'a', 'w'): 0260 self.helper(directive,6) 0261 0262 def test_julian(self): 0263 # Test julian directives 0264 self.helper('j', 7) 0265 0266 def test_timezone(self): 0267 # Test timezone directives. 0268 # When gmtime() is used with %Z, entire result of strftime() is empty. 0269 # Check for equal timezone names deals with bad locale info when this 0270 # occurs; first found in FreeBSD 4.4. 0271 strp_output = _strptime.strptime("UTC", "%Z") 0272 self.failUnlessEqual(strp_output.tm_isdst, 0) 0273 strp_output = _strptime.strptime("GMT", "%Z") 0274 self.failUnlessEqual(strp_output.tm_isdst, 0) 0275 if sys.platform == "mac": 0276 # Timezones don't really work on MacOS9 0277 return 0278 time_tuple = time.localtime() 0279 strf_output = time.strftime("%Z") #UTC does not have a timezone 0280 strp_output = _strptime.strptime(strf_output, "%Z") 0281 locale_time = _strptime.LocaleTime() 0282 if time.tzname[0] != time.tzname[1] or not time.daylight: 0283 self.failUnless(strp_output[8] == time_tuple[8], 0284 "timezone check failed; '%s' -> %s != %s" % 0285 (strf_output, strp_output[8], time_tuple[8])) 0286 else: 0287 self.failUnless(strp_output[8] == -1, 0288 "LocaleTime().timezone has duplicate values and " 0289 "time.daylight but timezone value not set to -1") 0290 0291 def test_bad_timezone(self): 0292 # Explicitly test possibility of bad timezone; 0293 # when time.tzname[0] == time.tzname[1] and time.daylight 0294 if sys.platform == "mac": 0295 return #MacOS9 has severely broken timezone support. 0296 tz_name = time.tzname[0] 0297 if tz_name.upper() in ("UTC", "GMT"): 0298 return 0299 try: 0300 original_tzname = time.tzname 0301 original_daylight = time.daylight 0302 time.tzname = (tz_name, tz_name) 0303 time.daylight = 1 0304 tz_value = _strptime.strptime(tz_name, "%Z")[8] 0305 self.failUnlessEqual(tz_value, -1, 0306 "%s lead to a timezone value of %s instead of -1 when " 0307 "time.daylight set to %s and passing in %s" % 0308 (time.tzname, tz_value, time.daylight, tz_name)) 0309 finally: 0310 time.tzname = original_tzname 0311 time.daylight = original_daylight 0312 0313 def test_date_time(self): 0314 # Test %c directive 0315 for position in range(6): 0316 self.helper('c', position) 0317 0318 def test_date(self): 0319 # Test %x directive 0320 for position in range(0,3): 0321 self.helper('x', position) 0322 0323 def test_time(self): 0324 # Test %X directive 0325 for position in range(3,6): 0326 self.helper('X', position) 0327 0328 def test_percent(self): 0329 # Make sure % signs are handled properly 0330 strf_output = time.strftime("%m %% %Y", self.time_tuple) 0331 strp_output = _strptime.strptime(strf_output, "%m %% %Y") 0332 self.failUnless(strp_output[0] == self.time_tuple[0] and 0333 strp_output[1] == self.time_tuple[1], 0334 "handling of percent sign failed") 0335 0336 def test_caseinsensitive(self): 0337 # Should handle names case-insensitively. 0338 strf_output = time.strftime("%B", self.time_tuple) 0339 self.failUnless(_strptime.strptime(strf_output.upper(), "%B"), 0340 "strptime does not handle ALL-CAPS names properly") 0341 self.failUnless(_strptime.strptime(strf_output.lower(), "%B"), 0342 "strptime does not handle lowercase names properly") 0343 self.failUnless(_strptime.strptime(strf_output.capitalize(), "%B"), 0344 "strptime does not handle capword names properly") 0345 0346 def test_defaults(self): 0347 # Default return value should be (1900, 1, 1, 0, 0, 0, 0, 1, 0) 0348 defaults = (1900, 1, 1, 0, 0, 0, 0, 1, -1) 0349 strp_output = _strptime.strptime('1', '%m') 0350 self.failUnless(strp_output == defaults, 0351 "Default values for strptime() are incorrect;" 0352 " %s != %s" % (strp_output, defaults)) 0353 0354 def test_escaping(self): 0355 # Make sure all characters that have regex significance are escaped. 0356 # Parentheses are in a purposeful order; will cause an error of 0357 # unbalanced parentheses when the regex is compiled if they are not 0358 # escaped. 0359 # Test instigated by bug #796149 . 0360 need_escaping = ".^$*+?{}\[]|)(" 0361 self.failUnless(_strptime.strptime(need_escaping, need_escaping)) 0362 0363 class Strptime12AMPMTests(unittest.TestCase): 0364 """Test a _strptime regression in '%I %p' at 12 noon (12 PM)""" 0365 0366 def test_twelve_noon_midnight(self): 0367 eq = self.assertEqual 0368 eq(time.strptime('12 PM', '%I %p')[3], 12) 0369 eq(time.strptime('12 AM', '%I %p')[3], 0) 0370 eq(_strptime.strptime('12 PM', '%I %p')[3], 12) 0371 eq(_strptime.strptime('12 AM', '%I %p')[3], 0) 0372 0373 0374 class JulianTests(unittest.TestCase): 0375 """Test a _strptime regression that all julian (1-366) are accepted""" 0376 0377 def test_all_julian_days(self): 0378 eq = self.assertEqual 0379 for i in range(1, 367): 0380 # use 2004, since it is a leap year, we have 366 days 0381 eq(_strptime.strptime('%d 2004' % i, '%j %Y')[7], i) 0382 0383 class CalculationTests(unittest.TestCase): 0384 """Test that strptime() fills in missing info correctly""" 0385 0386 def setUp(self): 0387 self.time_tuple = time.gmtime() 0388 0389 def test_julian_calculation(self): 0390 # Make sure that when Julian is missing that it is calculated 0391 format_string = "%Y %m %d %H %M %S %w %Z" 0392 result = _strptime.strptime(time.strftime(format_string, self.time_tuple), 0393 format_string) 0394 self.failUnless(result.tm_yday == self.time_tuple.tm_yday, 0395 "Calculation of tm_yday failed; %s != %s" % 0396 (result.tm_yday, self.time_tuple.tm_yday)) 0397 0398 def test_gregorian_calculation(self): 0399 # Test that Gregorian date can be calculated from Julian day 0400 format_string = "%Y %H %M %S %w %j %Z" 0401 result = _strptime.strptime(time.strftime(format_string, self.time_tuple), 0402 format_string) 0403 self.failUnless(result.tm_year == self.time_tuple.tm_year and 0404 result.tm_mon == self.time_tuple.tm_mon and 0405 result.tm_mday == self.time_tuple.tm_mday, 0406 "Calculation of Gregorian date failed;" 0407 "%s-%s-%s != %s-%s-%s" % 0408 (result.tm_year, result.tm_mon, result.tm_mday, 0409 self.time_tuple.tm_year, self.time_tuple.tm_mon, 0410 self.time_tuple.tm_mday)) 0411 0412 def test_day_of_week_calculation(self): 0413 # Test that the day of the week is calculated as needed 0414 format_string = "%Y %m %d %H %S %j %Z" 0415 result = _strptime.strptime(time.strftime(format_string, self.time_tuple), 0416 format_string) 0417 self.failUnless(result.tm_wday == self.time_tuple.tm_wday, 0418 "Calculation of day of the week failed;" 0419 "%s != %s" % (result.tm_wday, self.time_tuple.tm_wday)) 0420 0421 def test_week_of_year_and_day_of_week_calculation(self): 0422 # Should be able to infer date if given year, week of year (%U or %W) 0423 # and day of the week 0424 def test_helper(ymd_tuple, test_reason): 0425 for directive in ('W', 'U'): 0426 format_string = "%%Y %%%s %%w" % directive 0427 dt_date = datetime_date(*ymd_tuple) 0428 strp_input = dt_date.strftime(format_string) 0429 strp_output = _strptime.strptime(strp_input, format_string) 0430 self.failUnless(strp_output[:3] == ymd_tuple, 0431 "%s(%s) test failed w/ '%s': %s != %s (%s != %s)" % 0432 (test_reason, directive, strp_input, 0433 strp_output[:3], ymd_tuple, 0434 strp_output[7], dt_date.timetuple()[7])) 0435 test_helper((1901, 1, 3), "week 0") 0436 test_helper((1901, 1, 8), "common case") 0437 test_helper((1901, 1, 13), "day on Sunday") 0438 test_helper((1901, 1, 14), "day on Monday") 0439 test_helper((1905, 1, 1), "Jan 1 on Sunday") 0440 test_helper((1906, 1, 1), "Jan 1 on Monday") 0441 test_helper((1906, 1, 7), "first Sunday in a year starting on Monday") 0442 test_helper((1905, 12, 31), "Dec 31 on Sunday") 0443 test_helper((1906, 12, 31), "Dec 31 on Monday") 0444 test_helper((2008, 12, 29), "Monday in the last week of the year") 0445 test_helper((2008, 12, 22), "Monday in the second-to-last week of the " 0446 "year") 0447 test_helper((1978, 10, 23), "randomly chosen date") 0448 test_helper((2004, 12, 18), "randomly chosen date") 0449 test_helper((1978, 10, 23), "year starting and ending on Monday while " 0450 "date not on Sunday or Monday") 0451 test_helper((1917, 12, 17), "year starting and ending on Monday with " 0452 "a Monday not at the beginning or end " 0453 "of the year") 0454 test_helper((1917, 12, 31), "Dec 31 on Monday with year starting and " 0455 "ending on Monday") 0456 0457 0458 class CacheTests(unittest.TestCase): 0459 """Test that caching works properly.""" 0460 0461 def test_time_re_recreation(self): 0462 # Make sure cache is recreated when current locale does not match what 0463 # cached object was created with. 0464 _strptime.strptime("10", "%d") 0465 _strptime._TimeRE_cache.locale_time.lang = "Ni" 0466 original_time_re = id(_strptime._TimeRE_cache) 0467 _strptime.strptime("10", "%d") 0468 self.failIfEqual(original_time_re, id(_strptime._TimeRE_cache)) 0469 0470 def test_regex_cleanup(self): 0471 # Make sure cached regexes are discarded when cache becomes "full". 0472 try: 0473 del _strptime._regex_cache['%d'] 0474 except KeyError: 0475 pass 0476 bogus_key = 0 0477 while len(_strptime._regex_cache) <= _strptime._CACHE_MAX_SIZE: 0478 _strptime._regex_cache[bogus_key] = None 0479 bogus_key += 1 0480 _strptime.strptime("10", "%d") 0481 self.failUnlessEqual(len(_strptime._regex_cache), 1) 0482 0483 def test_new_localetime(self): 0484 # A new LocaleTime instance should be created when a new TimeRE object 0485 # is created. 0486 locale_time_id = id(_strptime._TimeRE_cache.locale_time) 0487 _strptime._TimeRE_cache.locale_time.lang = "Ni" 0488 _strptime.strptime("10", "%d") 0489 self.failIfEqual(locale_time_id, 0490 id(_strptime._TimeRE_cache.locale_time)) 0491 0492 0493 def test_main(): 0494 test_support.run_unittest( 0495 getlang_Tests, 0496 LocaleTime_Tests, 0497 TimeRETests, 0498 StrptimeTests, 0499 Strptime12AMPMTests, 0500 JulianTests, 0501 CalculationTests, 0502 CacheTests 0503 ) 0504 0505 0506 if __name__ == '__main__': 0507 test_main() 0508
Generated by PyXR 0.9.4