1 """PyUnit testing against strptime"""
7 from test
import test_support
11 class LocaleTime_Tests(unittest
.TestCase
):
12 """Tests for _strptime.LocaleTime."""
15 """Create time tuple based on current time."""
16 self
.time_tuple
= time
.localtime()
17 self
.LT_ins
= _strptime
.LocaleTime()
19 def compare_against_time(self
, testing
, directive
, tuple_position
,
21 """Helper method that tests testing against directive based on the
22 tuple_position of time_tuple. Uses error_msg as error message.
25 strftime_output
= time
.strftime(directive
, self
.time_tuple
)
26 comparison
= testing
[self
.time_tuple
[tuple_position
]]
27 self
.failUnless(strftime_output
in testing
, "%s: not found in tuple" %
29 self
.failUnless(comparison
== strftime_output
,
30 "%s: position within tuple incorrect; %s != %s" %
31 (error_msg
, comparison
, strftime_output
))
33 def test_weekday(self
):
34 # Make sure that full and abbreviated weekday names are correct in
35 # both string and position with tuple
36 self
.compare_against_time(self
.LT_ins
.f_weekday
, '%A', 6,
37 "Testing of full weekday name failed")
38 self
.compare_against_time(self
.LT_ins
.a_weekday
, '%a', 6,
39 "Testing of abbreviated weekday name failed")
42 # Test full and abbreviated month names; both string and position
44 self
.compare_against_time(self
.LT_ins
.f_month
, '%B', 1,
45 "Testing against full month name failed")
46 self
.compare_against_time(self
.LT_ins
.a_month
, '%b', 1,
47 "Testing against abbreviated month name failed")
50 # Make sure AM/PM representation done properly
51 strftime_output
= time
.strftime("%p", self
.time_tuple
)
52 self
.failUnless(strftime_output
in self
.LT_ins
.am_pm
,
53 "AM/PM representation not in tuple")
54 if self
.time_tuple
[3] < 12: position
= 0
56 self
.failUnless(strftime_output
== self
.LT_ins
.am_pm
[position
],
57 "AM/PM representation in the wrong position within the tuple")
59 def test_timezone(self
):
60 # Make sure timezone is correct
61 if time
.strftime("%Z", self
.time_tuple
):
62 self
.compare_against_time(self
.LT_ins
.timezone
, '%Z', 8,
63 "Testing against timezone failed")
65 def test_date_time(self
):
66 # Check that LC_date_time, LC_date, and LC_time are correct
67 # the magic date is used so as to not have issues with %c when day of
68 # the month is a single digit and has a leading space. This is not an
69 # issue since strptime still parses it correctly. The problem is
70 # testing these directives for correctness by comparing strftime
72 magic_date
= (1999, 3, 17, 22, 44, 55, 2, 76, 0)
73 strftime_output
= time
.strftime("%c", magic_date
)
74 self
.failUnless(strftime_output
== time
.strftime(self
.LT_ins
.LC_date_time
,
76 "LC_date_time incorrect")
77 strftime_output
= time
.strftime("%x", magic_date
)
78 self
.failUnless(strftime_output
== time
.strftime(self
.LT_ins
.LC_date
,
81 strftime_output
= time
.strftime("%X", magic_date
)
82 self
.failUnless(strftime_output
== time
.strftime(self
.LT_ins
.LC_time
,
85 LT
= _strptime
.LocaleTime(am_pm
=('',''))
86 self
.failUnless(LT
.LC_time
, "LocaleTime's LC directives cannot handle "
90 # Make sure lang is set
91 self
.failUnless(self
.LT_ins
.lang
in (locale
.getdefaultlocale()[0],
92 locale
.getlocale(locale
.LC_TIME
),
94 "Setting of lang failed")
96 def test_by_hand_input(self
):
97 # Test passed-in initialization value checks
98 self
.failUnless(_strptime
.LocaleTime(f_weekday
=range(7)),
99 "Argument size check for f_weekday failed")
100 self
.assertRaises(TypeError, _strptime
.LocaleTime
, f_weekday
=range(8))
101 self
.assertRaises(TypeError, _strptime
.LocaleTime
, f_weekday
=range(6))
102 self
.failUnless(_strptime
.LocaleTime(a_weekday
=range(7)),
103 "Argument size check for a_weekday failed")
104 self
.assertRaises(TypeError, _strptime
.LocaleTime
, a_weekday
=range(8))
105 self
.assertRaises(TypeError, _strptime
.LocaleTime
, a_weekday
=range(6))
106 self
.failUnless(_strptime
.LocaleTime(f_month
=range(12)),
107 "Argument size check for f_month failed")
108 self
.assertRaises(TypeError, _strptime
.LocaleTime
, f_month
=range(11))
109 self
.assertRaises(TypeError, _strptime
.LocaleTime
, f_month
=range(13))
110 self
.failUnless(len(_strptime
.LocaleTime(f_month
=range(12)).f_month
) == 13,
111 "dummy value for f_month not added")
112 self
.failUnless(_strptime
.LocaleTime(a_month
=range(12)),
113 "Argument size check for a_month failed")
114 self
.assertRaises(TypeError, _strptime
.LocaleTime
, a_month
=range(11))
115 self
.assertRaises(TypeError, _strptime
.LocaleTime
, a_month
=range(13))
116 self
.failUnless(len(_strptime
.LocaleTime(a_month
=range(12)).a_month
) == 13,
117 "dummy value for a_month not added")
118 self
.failUnless(_strptime
.LocaleTime(am_pm
=range(2)),
119 "Argument size check for am_pm failed")
120 self
.assertRaises(TypeError, _strptime
.LocaleTime
, am_pm
=range(1))
121 self
.assertRaises(TypeError, _strptime
.LocaleTime
, am_pm
=range(3))
122 self
.failUnless(_strptime
.LocaleTime(timezone
=range(2)),
123 "Argument size check for timezone failed")
124 self
.assertRaises(TypeError, _strptime
.LocaleTime
, timezone
=range(1))
125 self
.assertRaises(TypeError, _strptime
.LocaleTime
, timezone
=range(3))
127 def test_unknowntimezone(self
):
128 # Handle timezone set to ('','') properly.
130 locale_time
= _strptime
.LocaleTime(timezone
=('',''))
131 self
.failUnless("%Z" not in locale_time
.LC_date
,
132 "when timezone == ('',''), string.replace('','%Z') is "
135 class TimeRETests(unittest
.TestCase
):
136 """Tests for TimeRE."""
139 """Construct generic TimeRE object."""
140 self
.time_re
= _strptime
.TimeRE()
141 self
.locale_time
= _strptime
.LocaleTime()
143 def test_getitem(self
):
144 # Make sure that __getitem__ works properly
145 self
.failUnless(self
.time_re
['m'],
146 "Fetching 'm' directive (built-in) failed")
147 self
.failUnless(self
.time_re
['b'],
148 "Fetching 'b' directive (built w/ __tupleToRE) failed")
149 for name
in self
.locale_time
.a_month
:
150 self
.failUnless(self
.time_re
['b'].find(name
) != -1,
151 "Not all abbreviated month names in regex")
152 self
.failUnless(self
.time_re
['c'],
153 "Fetching 'c' directive (built w/ format) failed")
154 self
.failUnless(self
.time_re
['c'].find('%') == -1,
155 "Conversion of 'c' directive failed; '%' found")
156 self
.assertRaises(KeyError, self
.time_re
.__getitem
__, '1')
158 def test_pattern(self
):
159 # Test TimeRE.pattern
160 pattern_string
= self
.time_re
.pattern(r
"%a %A %d")
161 self
.failUnless(pattern_string
.find(self
.locale_time
.a_weekday
[2]) != -1,
162 "did not find abbreviated weekday in pattern string '%s'" %
164 self
.failUnless(pattern_string
.find(self
.locale_time
.f_weekday
[4]) != -1,
165 "did not find full weekday in pattern string '%s'" %
167 self
.failUnless(pattern_string
.find(self
.time_re
['d']) != -1,
168 "did not find 'd' directive pattern string '%s'" %
171 def test_pattern_escaping(self
):
172 # Make sure any characters in the format string that might be taken as
173 # regex syntax is escaped.
174 pattern_string
= self
.time_re
.pattern("\d+")
175 self
.failUnless(r
"\\d\+" in pattern_string
,
176 "%s does not have re characters escaped properly" %
179 def test_compile(self
):
180 # Check that compiled regex is correct
181 found
= self
.time_re
.compile(r
"%A").match(self
.locale_time
.f_weekday
[6])
182 self
.failUnless(found
and found
.group('A') == self
.locale_time
.f_weekday
[6],
183 "re object for '%A' failed")
184 compiled
= self
.time_re
.compile(r
"%a %b")
185 found
= compiled
.match("%s %s" % (self
.locale_time
.a_weekday
[4],
186 self
.locale_time
.a_month
[4]))
187 self
.failUnless(found
,
188 "Match failed with '%s' regex and '%s' string" %
189 (compiled
.pattern
, "%s %s" % (self
.locale_time
.a_weekday
[4],
190 self
.locale_time
.a_month
[4])))
191 self
.failUnless(found
.group('a') == self
.locale_time
.a_weekday
[4] and
192 found
.group('b') == self
.locale_time
.a_month
[4],
193 "re object couldn't find the abbreviated weekday month in "
194 "'%s' using '%s'; group 'a' = '%s', group 'b' = %s'" %
195 (found
.string
, found
.re
.pattern
, found
.group('a'),
197 for directive
in ('a','A','b','B','c','d','H','I','j','m','M','p','S',
198 'U','w','W','x','X','y','Y','Z','%'):
199 compiled
= self
.time_re
.compile("%" + directive
)
200 found
= compiled
.match(time
.strftime("%" + directive
))
201 self
.failUnless(found
, "Matching failed on '%s' using '%s' regex" %
202 (time
.strftime("%" + directive
),
205 def test_blankpattern(self
):
206 # Make sure when tuple or something has no values no regex is generated.
208 test_locale
= _strptime
.LocaleTime(timezone
=('',''))
209 self
.failUnless(_strptime
.TimeRE(test_locale
).pattern("%Z") == '',
210 "with timezone == ('',''), TimeRE().pattern('%Z') != ''")
212 def test_matching_with_escapes(self
):
213 # Make sure a format that requires escaping of characters works
214 compiled_re
= self
.time_re
.compile("\w+ %m")
215 found
= compiled_re
.match("\w+ 10")
216 self
.failUnless(found
, "Escaping failed of format '\w+ 10'")
218 class StrptimeTests(unittest
.TestCase
):
219 """Tests for _strptime.strptime."""
222 """Create testing time tuple."""
223 self
.time_tuple
= time
.gmtime()
225 def test_TypeError(self
):
226 # Make sure ValueError is raised when match fails
227 self
.assertRaises(ValueError, _strptime
.strptime
, data_string
="%d",
230 def helper(self
, directive
, position
):
231 """Helper fxn in testing."""
232 strf_output
= time
.strftime("%" + directive
, self
.time_tuple
)
233 strp_output
= _strptime
.strptime(strf_output
, "%" + directive
)
234 self
.failUnless(strp_output
[position
] == self
.time_tuple
[position
],
235 "testing of '%s' directive failed; '%s' -> %s != %s" %
236 (directive
, strf_output
, strp_output
[position
],
237 self
.time_tuple
[position
]))
240 # Test that the year is handled properly
241 for directive
in ('y', 'Y'):
242 self
.helper(directive
, 0)
243 # Must also make sure %y values are correct for bounds set by Open Group
244 for century
, bounds
in ((1900, ('69', '99')), (2000, ('00', '68'))):
246 strp_output
= _strptime
.strptime(bound
, '%y')
247 expected_result
= century
+ int(bound
)
248 self
.failUnless(strp_output
[0] == expected_result
,
249 "'y' test failed; passed in '%s' "
250 "and returned '%s'" % (bound
, strp_output
[0]))
252 def test_month(self
):
253 # Test for month directives
254 for directive
in ('B', 'b', 'm'):
255 self
.helper(directive
, 1)
258 # Test for day directives
262 # Test hour directives
264 strf_output
= time
.strftime("%I %p", self
.time_tuple
)
265 strp_output
= _strptime
.strptime(strf_output
, "%I %p")
266 self
.failUnless(strp_output
[3] == self
.time_tuple
[3],
267 "testing of '%%I %%p' directive failed; '%s' -> %s != %s" %
268 (strf_output
, strp_output
[3], self
.time_tuple
[3]))
270 def test_minute(self
):
271 # Test minute directives
274 def test_second(self
):
275 # Test second directives
278 def test_weekday(self
):
279 # Test weekday directives
280 for directive
in ('A', 'a', 'w'):
281 self
.helper(directive
,6)
283 def test_julian(self
):
284 # Test julian directives
287 def test_timezone(self
):
288 # Test timezone directives.
289 # When gmtime() is used with %Z, entire result of strftime() is empty.
290 # Check for equal timezone names deals with bad locale info when this
291 # occurs; first found in FreeBSD 4.4.
292 time_tuple
= time
.localtime()
293 strf_output
= time
.strftime("%Z") #UTC does not have a timezone
294 strp_output
= _strptime
.strptime(strf_output
, "%Z")
295 locale_time
= _strptime
.LocaleTime()
296 if locale_time
.timezone
[0] != locale_time
.timezone
[1]:
297 self
.failUnless(strp_output
[8] == time_tuple
[8],
298 "timezone check failed; '%s' -> %s != %s" %
299 (strf_output
, strp_output
[8], time_tuple
[8]))
301 self
.failUnless(strp_output
[8] == -1,
302 "LocaleTime().timezone has duplicate values but "
303 "timzone value not set to 0")
305 def test_date_time(self
):
307 for position
in range(6):
308 self
.helper('c', position
)
312 for position
in range(0,3):
313 self
.helper('x', position
)
317 for position
in range(3,6):
318 self
.helper('X', position
)
320 def test_percent(self
):
321 # Make sure % signs are handled properly
322 strf_output
= time
.strftime("%m %% %Y", self
.time_tuple
)
323 strp_output
= _strptime
.strptime(strf_output
, "%m %% %Y")
324 self
.failUnless(strp_output
[0] == self
.time_tuple
[0] and
325 strp_output
[1] == self
.time_tuple
[1],
326 "handling of percent sign failed")
328 def test_caseinsensitive(self
):
329 # Should handle names case-insensitively.
330 strf_output
= time
.strftime("%B", self
.time_tuple
)
331 self
.failUnless(_strptime
.strptime(strf_output
.upper(), "%B"),
332 "strptime does not handle ALL-CAPS names properly")
333 self
.failUnless(_strptime
.strptime(strf_output
.lower(), "%B"),
334 "strptime does not handle lowercase names properly")
335 self
.failUnless(_strptime
.strptime(strf_output
.capitalize(), "%B"),
336 "strptime does not handle capword names properly")
338 def test_defaults(self
):
339 # Default return value should be (1900, 1, 1, 0, 0, 0, 0, 1, 0)
340 defaults
= (1900, 1, 1, 0, 0, 0, 0, 1, -1)
341 strp_output
= _strptime
.strptime('1', '%m')
342 self
.failUnless(strp_output
== defaults
,
343 "Default values for strptime() are incorrect;"
344 " %s != %s" % (strp_output
, defaults
))
346 class Strptime12AMPMTests(unittest
.TestCase
):
347 """Test a _strptime regression in '%I %p' at 12 noon (12 PM)"""
349 def test_twelve_noon_midnight(self
):
350 eq
= self
.assertEqual
351 eq(time
.strptime('12 PM', '%I %p')[3], 12)
352 eq(time
.strptime('12 AM', '%I %p')[3], 0)
353 eq(_strptime
.strptime('12 PM', '%I %p')[3], 12)
354 eq(_strptime
.strptime('12 AM', '%I %p')[3], 0)
357 class JulianTests(unittest
.TestCase
):
358 """Test a _strptime regression that all julian (1-366) are accepted"""
360 def test_all_julian_days(self
):
361 eq
= self
.assertEqual
362 for i
in range(1, 367):
363 # use 2004, since it is a leap year, we have 366 days
364 eq(_strptime
.strptime('%d 2004' % i
, '%j %Y')[7], i
)
366 class CalculationTests(unittest
.TestCase
):
367 """Test that strptime() fills in missing info correctly"""
370 self
.time_tuple
= time
.gmtime()
372 def test_julian_calculation(self
):
373 # Make sure that when Julian is missing that it is calculated
374 format_string
= "%Y %m %d %H %M %S %w %Z"
375 result
= _strptime
.strptime(time
.strftime(format_string
, self
.time_tuple
),
377 self
.failUnless(result
.tm_yday
== self
.time_tuple
.tm_yday
,
378 "Calculation of tm_yday failed; %s != %s" %
379 (result
.tm_yday
, self
.time_tuple
.tm_yday
))
381 def test_gregorian_calculation(self
):
382 # Test that Gregorian date can be calculated from Julian day
383 format_string
= "%Y %H %M %S %w %j %Z"
384 result
= _strptime
.strptime(time
.strftime(format_string
, self
.time_tuple
),
386 self
.failUnless(result
.tm_year
== self
.time_tuple
.tm_year
and
387 result
.tm_mon
== self
.time_tuple
.tm_mon
and
388 result
.tm_mday
== self
.time_tuple
.tm_mday
,
389 "Calculation of Gregorian date failed;"
390 "%s-%s-%s != %s-%s-%s" %
391 (result
.tm_year
, result
.tm_mon
, result
.tm_mday
,
392 self
.time_tuple
.tm_year
, self
.time_tuple
.tm_mon
,
393 self
.time_tuple
.tm_mday
))
395 def test_day_of_week_calculation(self
):
396 # Test that the day of the week is calculated as needed
397 format_string
= "%Y %m %d %H %S %j %Z"
398 result
= _strptime
.strptime(time
.strftime(format_string
, self
.time_tuple
),
400 self
.failUnless(result
.tm_wday
== self
.time_tuple
.tm_wday
,
401 "Calculation of day of the week failed;"
402 "%s != %s" % (result
.tm_wday
, self
.time_tuple
.tm_wday
))
405 suite
= unittest
.TestSuite()
406 suite
.addTest(unittest
.makeSuite(LocaleTime_Tests
))
407 suite
.addTest(unittest
.makeSuite(TimeRETests
))
408 suite
.addTest(unittest
.makeSuite(StrptimeTests
))
409 suite
.addTest(unittest
.makeSuite(Strptime12AMPMTests
))
410 suite
.addTest(unittest
.makeSuite(JulianTests
))
411 suite
.addTest(unittest
.makeSuite(CalculationTests
))
412 test_support
.run_suite(suite
)
415 if __name__
== '__main__':