Debian Codegraph @

Lib/test/test_strptime.py

raw
1 """PyUnit testing against strptime"""
2
3 import unittest
4 import time
5 import locale
6 import re
7 import os
8 import platform
9 import sys
10 from test import support
11 from test.support import warnings_helper
12 from test.support import skip_if_buggy_ucrt_strfptime, run_with_locales
13 from datetime import date as datetime_date
14
15 import _strptime
16
17 libc_ver = platform.libc_ver()
18 if libc_ver[0] == 'glibc':
19 glibc_ver = tuple(map(int, libc_ver[1].split('.')))
20 else:
21 glibc_ver = None
22
23
24 class getlang_Tests(unittest.TestCase):
25 """Test _getlang"""
26 def test_basic(self):
27 self.assertEqual(_strptime._getlang(), locale.getlocale(locale.LC_TIME))
28
29 class LocaleTime_Tests(unittest.TestCase):
30 """Tests for _strptime.LocaleTime.
31
32 All values are lower-cased when stored in LocaleTime, so make sure to
33 compare values after running ``lower`` on them.
34
35 """
36
37 def setUp(self):
38 """Create time tuple based on current time."""
39 self.time_tuple = time.localtime()
40 self.LT_ins = _strptime.LocaleTime()
41
42 def compare_against_time(self, testing, directive, tuple_position,
43 error_msg):
44 """Helper method that tests testing against directive based on the
45 tuple_position of time_tuple. Uses error_msg as error message.
46
47 """
48 strftime_output = time.strftime(directive, self.time_tuple).lower()
49 comparison = testing[self.time_tuple[tuple_position]]
50 self.assertIn(strftime_output, testing,
51 "%s: not found in tuple" % error_msg)
52 self.assertEqual(comparison, strftime_output,
53 "%s: position within tuple incorrect; %s != %s" %
54 (error_msg, comparison, strftime_output))
55
56 def test_weekday(self):
57 # Make sure that full and abbreviated weekday names are correct in
58 # both string and position with tuple
59 self.compare_against_time(self.LT_ins.f_weekday, '%A', 6,
60 "Testing of full weekday name failed")
61 self.compare_against_time(self.LT_ins.a_weekday, '%a', 6,
62 "Testing of abbreviated weekday name failed")
63
64 def test_month(self):
65 # Test full and abbreviated month names; both string and position
66 # within the tuple
67 self.compare_against_time(self.LT_ins.f_month, '%B', 1,
68 "Testing against full month name failed")
69 self.compare_against_time(self.LT_ins.a_month, '%b', 1,
70 "Testing against abbreviated month name failed")
71
72 def test_am_pm(self):
73 # Make sure AM/PM representation done properly
74 strftime_output = time.strftime("%p", self.time_tuple).lower()
75 self.assertIn(strftime_output, self.LT_ins.am_pm,
76 "AM/PM representation not in tuple")
77 if self.time_tuple[3] < 12: position = 0
78 else: position = 1
79 self.assertEqual(self.LT_ins.am_pm[position], strftime_output,
80 "AM/PM representation in the wrong position within the tuple")
81
82 @unittest.skipIf(
83 support.is_emscripten, "musl libc issue on Emscripten, bpo-46390"
84 )
85 def test_timezone(self):
86 # Make sure timezone is correct
87 timezone = time.strftime("%Z", self.time_tuple).lower()
88 if timezone:
89 self.assertTrue(timezone in self.LT_ins.timezone[0] or
90 timezone in self.LT_ins.timezone[1],
91 "timezone %s not found in %s" %
92 (timezone, self.LT_ins.timezone))
93
94 def test_date_time(self):
95 # Check that LC_date_time, LC_date, and LC_time are correct
96 # the magic date is used so as to not have issues with %c when day of
97 # the month is a single digit and has a leading space. This is not an
98 # issue since strptime still parses it correctly. The problem is
99 # testing these directives for correctness by comparing strftime
100 # output.
101 magic_date = (1999, 3, 17, 22, 44, 55, 2, 76, 0)
102 strftime_output = time.strftime("%c", magic_date)
103 self.assertEqual(time.strftime(self.LT_ins.LC_date_time, magic_date),
104 strftime_output, "LC_date_time incorrect")
105 strftime_output = time.strftime("%x", magic_date)
106 self.assertEqual(time.strftime(self.LT_ins.LC_date, magic_date),
107 strftime_output, "LC_date incorrect")
108 strftime_output = time.strftime("%X", magic_date)
109 self.assertEqual(time.strftime(self.LT_ins.LC_time, magic_date),
110 strftime_output, "LC_time incorrect")
111 LT = _strptime.LocaleTime()
112 LT.am_pm = ('', '')
113 self.assertTrue(LT.LC_time, "LocaleTime's LC directives cannot handle "
114 "empty strings")
115
116 def test_lang(self):
117 # Make sure lang is set to what _getlang() returns
118 # Assuming locale has not changed between now and when self.LT_ins was created
119 self.assertEqual(self.LT_ins.lang, _strptime._getlang())
120
121
122 class TimeRETests(unittest.TestCase):
123 """Tests for TimeRE."""
124
125 def setUp(self):
126 """Construct generic TimeRE object."""
127 self.time_re = _strptime.TimeRE()
128 self.locale_time = _strptime.LocaleTime()
129
130 def test_pattern(self):
131 # Test TimeRE.pattern
132 pattern_string = self.time_re.pattern(r"%a %A %d %Y")
133 self.assertTrue(pattern_string.find(self.locale_time.a_weekday[2]) != -1,
134 "did not find abbreviated weekday in pattern string '%s'" %
135 pattern_string)
136 self.assertTrue(pattern_string.find(self.locale_time.f_weekday[4]) != -1,
137 "did not find full weekday in pattern string '%s'" %
138 pattern_string)
139 self.assertTrue(pattern_string.find(self.time_re['d']) != -1,
140 "did not find 'd' directive pattern string '%s'" %
141 pattern_string)
142
143 def test_pattern_escaping(self):
144 # Make sure any characters in the format string that might be taken as
145 # regex syntax is escaped.
146 pattern_string = self.time_re.pattern(r"\d+")
147 self.assertIn(r"\\d\+", pattern_string,
148 "%s does not have re characters escaped properly" %
149 pattern_string)
150
151 @skip_if_buggy_ucrt_strfptime
152 def test_compile(self):
153 # Check that compiled regex is correct
154 found = self.time_re.compile(r"%A").match(self.locale_time.f_weekday[6])
155 self.assertTrue(found and found.group('A') == self.locale_time.f_weekday[6],
156 "re object for '%A' failed")
157 compiled = self.time_re.compile(r"%a %b")
158 found = compiled.match("%s %s" % (self.locale_time.a_weekday[4],
159 self.locale_time.a_month[4]))
160 self.assertTrue(found,
161 "Match failed with '%s' regex and '%s' string" %
162 (compiled.pattern, "%s %s" % (self.locale_time.a_weekday[4],
163 self.locale_time.a_month[4])))
164 self.assertTrue(found.group('a') == self.locale_time.a_weekday[4] and
165 found.group('b') == self.locale_time.a_month[4],
166 "re object couldn't find the abbreviated weekday month in "
167 "'%s' using '%s'; group 'a' = '%s', group 'b' = %s'" %
168 (found.string, found.re.pattern, found.group('a'),
169 found.group('b')))
170 for directive in ('a','A','b','B','c','d','G','H','I','j','m','M','p',
171 'S','u','U','V','w','W','x','X','y','Y','Z','%'):
172 fmt = "%d %Y" if directive == 'd' else "%" + directive
173 compiled = self.time_re.compile(fmt)
174 found = compiled.match(time.strftime(fmt))
175 self.assertTrue(found, "Matching failed on '%s' using '%s' regex" %
176 (time.strftime(fmt),
177 compiled.pattern))
178
179 def test_blankpattern(self):
180 # Make sure when tuple or something has no values no regex is generated.
181 # Fixes bug #661354
182 test_locale = _strptime.LocaleTime()
183 test_locale.timezone = (frozenset(), frozenset())
184 self.assertEqual(_strptime.TimeRE(test_locale).pattern("%Z"), '',
185 "with timezone == ('',''), TimeRE().pattern('%Z') != ''")
186
187 def test_matching_with_escapes(self):
188 # Make sure a format that requires escaping of characters works
189 compiled_re = self.time_re.compile(r"\w+ %m")
190 found = compiled_re.match(r"\w+ 10")
191 self.assertTrue(found, r"Escaping failed of format '\w+ 10'")
192
193 def test_locale_data_w_regex_metacharacters(self):
194 # Check that if locale data contains regex metacharacters they are
195 # escaped properly.
196 # Discovered by bug #1039270 .
197 locale_time = _strptime.LocaleTime()
198 locale_time.timezone = (frozenset(("utc", "gmt",
199 "Tokyo (standard time)")),
200 frozenset("Tokyo (daylight time)"))
201 time_re = _strptime.TimeRE(locale_time)
202 self.assertTrue(time_re.compile("%Z").match("Tokyo (standard time)"),
203 "locale data that contains regex metacharacters is not"
204 " properly escaped")
205
206 def test_whitespace_substitution(self):
207 # When pattern contains whitespace, make sure it is taken into account
208 # so as to not allow subpatterns to end up next to each other and
209 # "steal" characters from each other.
210 pattern = self.time_re.pattern('%j %H')
211 self.assertFalse(re.match(pattern, "180"))
212 self.assertTrue(re.match(pattern, "18 0"))
213
214
215 class StrptimeTests(unittest.TestCase):
216 """Tests for _strptime.strptime."""
217
218 def setUp(self):
219 """Create testing time tuples."""
220 self.time_tuple = time.localtime()
221
222 def test_ValueError(self):
223 # Make sure ValueError is raised when match fails or format is bad
224 self.assertRaises(ValueError, _strptime._strptime_time, data_string="%d",
225 format="%A")
226 for bad_format in ("%", "% ", "%\n"):
227 with (self.subTest(format=bad_format),
228 self.assertRaisesRegex(ValueError, "stray % in format ")):
229 _strptime._strptime_time("2005", bad_format)
230 for bad_format in ("%i", "%Oi", "%O", "%O ", "%Ee", "%E", "%E ",
231 "%.", "%+", "%~", "%\\",
232 "%O.", "%O+", "%O_", "%O~", "%O\\"):
233 directive = bad_format[1:].rstrip()
234 with (self.subTest(format=bad_format),
235 self.assertRaisesRegex(ValueError,
236 f"'{re.escape(directive)}' is a bad directive in format ")):
237 _strptime._strptime_time("2005", bad_format)
238
239 msg_week_no_year_or_weekday = r"ISO week directive '%V' must be used with " \
240 r"the ISO year directive '%G' and a weekday directive " \
241 r"\('%A', '%a', '%w', or '%u'\)."
242 msg_week_not_compatible = r"ISO week directive '%V' is incompatible with " \
243 r"the year directive '%Y'. Use the ISO year '%G' instead."
244 msg_julian_not_compatible = r"Day of the year directive '%j' is not " \
245 r"compatible with ISO year directive '%G'. Use '%Y' instead."
246 msg_year_no_week_or_weekday = r"ISO year directive '%G' must be used with " \
247 r"the ISO week directive '%V' and a weekday directive " \
248 r"\('%A', '%a', '%w', or '%u'\)."
249
250 locale_time = _strptime.LocaleTime()
251
252 # Ambiguous or incomplete cases using ISO year/week/weekday directives
253 subtests = [
254 # 1. ISO week (%V) is specified, but the year is specified with %Y
255 # instead of %G
256 ("1999 50", "%Y %V", msg_week_no_year_or_weekday),
257 ("1999 50 5", "%Y %V %u", msg_week_not_compatible),
258 # 2. ISO year (%G) and ISO week (%V) are specified, but weekday is not
259 ("1999 51", "%G %V", msg_year_no_week_or_weekday),
260 # 3. ISO year (%G) and weekday are specified, but ISO week (%V) is not
261 ("1999 {}".format(locale_time.f_weekday[5]), "%G %A",
262 msg_year_no_week_or_weekday),
263 ("1999 {}".format(locale_time.a_weekday[5]), "%G %a",
264 msg_year_no_week_or_weekday),
265 ("1999 5", "%G %w", msg_year_no_week_or_weekday),
266 ("1999 5", "%G %u", msg_year_no_week_or_weekday),
267 # 4. ISO year is specified alone (e.g. time.strptime('2015', '%G'))
268 ("2015", "%G", msg_year_no_week_or_weekday),
269 # 5. Julian/ordinal day (%j) is specified with %G, but not %Y
270 ("1999 256", "%G %j", msg_julian_not_compatible),
271 ("1999 50 5 256", "%G %V %u %j", msg_julian_not_compatible),
272 # ISO week specified alone
273 ("50", "%V", msg_week_no_year_or_weekday),
274 # ISO year is unspecified, falling back to year
275 ("50 5", "%V %u", msg_week_no_year_or_weekday),
276 # 6. Invalid ISO weeks
277 ("2019-00-1", "%G-%V-%u",
278 "time data '2019-00-1' does not match format '%G-%V-%u'"),
279 ("2019-54-1", "%G-%V-%u",
280 "time data '2019-54-1' does not match format '%G-%V-%u'"),
281 ("2021-53-1", "%G-%V-%u", "Invalid week: 53"),
282 ]
283
284 for (data_string, format, message) in subtests:
285 with self.subTest(data_string=data_string, format=format):
286 with self.assertRaisesRegex(ValueError, message):
287 _strptime._strptime(data_string, format)
288
289 def test_strptime_exception_context(self):
290 # check that this doesn't chain exceptions needlessly (see #17572)
291 with self.assertRaises(ValueError) as e:
292 _strptime._strptime_time('', '%D')
293 self.assertTrue(e.exception.__suppress_context__)
294 # additional check for stray % branch
295 with self.assertRaises(ValueError) as e:
296 _strptime._strptime_time('%', '%')
297 self.assertTrue(e.exception.__suppress_context__)
298
299 def test_unconverteddata(self):
300 # Check ValueError is raised when there is unconverted data
301 self.assertRaises(ValueError, _strptime._strptime_time, "10 12", "%m")
302
303 def roundtrip(self, fmt, position, time_tuple=None):
304 """Helper fxn in testing."""
305 if time_tuple is None:
306 time_tuple = self.time_tuple
307 strf_output = time.strftime(fmt, time_tuple)
308 strp_output = _strptime._strptime_time(strf_output, fmt)
309 self.assertEqual(strp_output[position], time_tuple[position],
310 "testing of %r format failed; %r -> %r != %r" %
311 (fmt, strf_output, strp_output[position],
312 time_tuple[position]))
313 if support.verbose >= 3:
314 print("testing of %r format: %r -> %r" %
315 (fmt, strf_output, strp_output[position]))
316
317 def test_year(self):
318 # Test that the year is handled properly
319 self.roundtrip('%Y', 0)
320 self.roundtrip('%y', 0)
321 self.roundtrip('%Y', 0, (1900, 1, 1, 0, 0, 0, 0, 1, 0))
322
323 # Must also make sure %y values are correct for bounds set by Open Group
324 strptime = _strptime._strptime_time
325 self.assertEqual(strptime('00', '%y')[0], 2000)
326 self.assertEqual(strptime('68', '%y')[0], 2068)
327 self.assertEqual(strptime('69', '%y')[0], 1969)
328 self.assertEqual(strptime('99', '%y')[0], 1999)
329
330 def test_month(self):
331 # Test for month directives
332 self.roundtrip('%m', 1)
333
334 @run_with_locales('LC_TIME', 'C', 'en_US', 'fr_FR', 'de_DE', 'ja_JP', 'he_IL', '')
335 def test_month_locale(self):
336 # Test for month directives
337 self.roundtrip('%B', 1)
338 self.roundtrip('%b', 1)
339 for m in range(1, 13):
340 self.roundtrip('%B', 1, (1900, m, 1, 0, 0, 0, 0, 1, 0))
341 self.roundtrip('%b', 1, (1900, m, 1, 0, 0, 0, 0, 1, 0))
342
343 @run_with_locales('LC_TIME', 'az_AZ', 'ber_DZ', 'ber_MA', 'crh_UA')
344 def test_month_locale2(self):
345 # Test for month directives
346 # Month name contains 'İ' ('\u0130')
347 self.roundtrip('%B', 1, (2025, 6, 1, 0, 0, 0, 6, 152, 0))
348 self.roundtrip('%b', 1, (2025, 6, 1, 0, 0, 0, 6, 152, 0))
349 self.roundtrip('%B', 1, (2025, 7, 1, 0, 0, 0, 1, 182, 0))
350 self.roundtrip('%b', 1, (2025, 7, 1, 0, 0, 0, 1, 182, 0))
351
352 def test_day(self):
353 # Test for day directives
354 self.roundtrip('%d %Y', 2)
355
356 def test_hour(self):
357 # Test hour directives
358 self.roundtrip('%H', 3)
359
360 # NB: Only works on locales with AM/PM
361 @run_with_locales('LC_TIME', 'C', 'en_US', 'ja_JP')
362 def test_hour_locale(self):
363 # Test hour directives
364 self.roundtrip('%I %p', 3)
365
366 def test_minute(self):
367 # Test minute directives
368 self.roundtrip('%M', 4)
369
370 def test_second(self):
371 # Test second directives
372 self.roundtrip('%S', 5)
373
374 def test_fraction(self):
375 # Test microseconds
376 import datetime
377 d = datetime.datetime(2012, 12, 20, 12, 34, 56, 78987)
378 tup, frac, _ = _strptime._strptime(str(d), format="%Y-%m-%d %H:%M:%S.%f")
379 self.assertEqual(frac, d.microsecond)
380
381 def test_weekday(self):
382 # Test weekday directives
383 self.roundtrip('%w', 6)
384 self.roundtrip('%u', 6)
385
386 @run_with_locales('LC_TIME', 'C', 'en_US', 'fr_FR', 'de_DE', 'ja_JP', '')
387 def test_weekday_locale(self):
388 # Test weekday directives
389 self.roundtrip('%A', 6)
390 self.roundtrip('%a', 6)
391
392 def test_julian(self):
393 # Test julian directives
394 self.roundtrip('%j', 7)
395
396 def test_offset(self):
397 one_hour = 60 * 60
398 half_hour = 30 * 60
399 half_minute = 30
400 (*_, offset), _, offset_fraction = _strptime._strptime("+0130", "%z")
401 self.assertEqual(offset, one_hour + half_hour)
402 self.assertEqual(offset_fraction, 0)
403 (*_, offset), _, offset_fraction = _strptime._strptime("-0100", "%z")
404 self.assertEqual(offset, -one_hour)
405 self.assertEqual(offset_fraction, 0)
406 (*_, offset), _, offset_fraction = _strptime._strptime("-013030", "%z")
407 self.assertEqual(offset, -(one_hour + half_hour + half_minute))
408 self.assertEqual(offset_fraction, 0)
409 (*_, offset), _, offset_fraction = _strptime._strptime("-013030.000001", "%z")
410 self.assertEqual(offset, -(one_hour + half_hour + half_minute))
411 self.assertEqual(offset_fraction, -1)
412 (*_, offset), _, offset_fraction = _strptime._strptime("+01:00", "%z")
413 self.assertEqual(offset, one_hour)
414 self.assertEqual(offset_fraction, 0)
415 (*_, offset), _, offset_fraction = _strptime._strptime("-01:30", "%z")
416 self.assertEqual(offset, -(one_hour + half_hour))
417 self.assertEqual(offset_fraction, 0)
418 (*_, offset), _, offset_fraction = _strptime._strptime("-01:30:30", "%z")
419 self.assertEqual(offset, -(one_hour + half_hour + half_minute))
420 self.assertEqual(offset_fraction, 0)
421 (*_, offset), _, offset_fraction = _strptime._strptime("-01:30:30.000001", "%z")
422 self.assertEqual(offset, -(one_hour + half_hour + half_minute))
423 self.assertEqual(offset_fraction, -1)
424 (*_, offset), _, offset_fraction = _strptime._strptime("+01:30:30.001", "%z")
425 self.assertEqual(offset, one_hour + half_hour + half_minute)
426 self.assertEqual(offset_fraction, 1000)
427 (*_, offset), _, offset_fraction = _strptime._strptime("Z", "%z")
428 self.assertEqual(offset, 0)
429 self.assertEqual(offset_fraction, 0)
430
431 def test_bad_offset(self):
432 with self.assertRaises(ValueError):
433 _strptime._strptime("-01:30:30.", "%z")
434 with self.assertRaises(ValueError):
435 _strptime._strptime("-0130:30", "%z")
436 with self.assertRaises(ValueError):
437 _strptime._strptime("-01:30:30.1234567", "%z")
438 with self.assertRaises(ValueError):
439 _strptime._strptime("-01:30:30:123456", "%z")
440 with self.assertRaises(ValueError) as err:
441 _strptime._strptime("-01:3030", "%z")
442 self.assertEqual("Inconsistent use of : in -01:3030", str(err.exception))
443
444 @skip_if_buggy_ucrt_strfptime
445 @unittest.skipIf(
446 support.is_emscripten, "musl libc issue on Emscripten, bpo-46390"
447 )
448 def test_timezone(self):
449 # Test timezone directives.
450 # When gmtime() is used with %Z, entire result of strftime() is empty.
451 # Check for equal timezone names deals with bad locale info when this
452 # occurs; first found in FreeBSD 4.4.
453 strp_output = _strptime._strptime_time("UTC", "%Z")
454 self.assertEqual(strp_output.tm_isdst, 0)
455 strp_output = _strptime._strptime_time("GMT", "%Z")
456 self.assertEqual(strp_output.tm_isdst, 0)
457 time_tuple = time.localtime()
458 strf_output = time.strftime("%Z") #UTC does not have a timezone
459 strp_output = _strptime._strptime_time(strf_output, "%Z")
460 locale_time = _strptime.LocaleTime()
461 if time.tzname[0] != time.tzname[1] or not time.daylight:
462 self.assertTrue(strp_output[8] == time_tuple[8],
463 "timezone check failed; '%s' -> %s != %s" %
464 (strf_output, strp_output[8], time_tuple[8]))
465 else:
466 self.assertTrue(strp_output[8] == -1,
467 "LocaleTime().timezone has duplicate values and "
468 "time.daylight but timezone value not set to -1")
469
470 @unittest.skipUnless(
471 hasattr(time, "tzset"), "time module has no attribute tzset"
472 )
473 def test_bad_timezone(self):
474 # Explicitly test possibility of bad timezone;
475 # when time.tzname[0] == time.tzname[1] and time.daylight
476 tz_name = time.tzname[0]
477 if tz_name.upper() in ("UTC", "GMT"):
478 self.skipTest('need non-UTC/GMT timezone')
479
480 with support.swap_attr(time, 'tzname', (tz_name, tz_name)), \
481 support.swap_attr(time, 'daylight', 1), \
482 support.swap_attr(time, 'tzset', lambda: None):
483 time.tzname = (tz_name, tz_name)
484 time.daylight = 1
485 tz_value = _strptime._strptime_time(tz_name, "%Z")[8]
486 self.assertEqual(tz_value, -1,
487 "%s lead to a timezone value of %s instead of -1 when "
488 "time.daylight set to %s and passing in %s" %
489 (time.tzname, tz_value, time.daylight, tz_name))
490
491 # NB: Does not roundtrip in some locales due to the ambiguity of
492 # the date and time representation (bugs in locales?):
493 # * Seconds are not included: bem_ZM, bokmal, ff_SN, nb_NO, nn_NO,
494 # no_NO, norwegian, nynorsk.
495 # * Hours are in 12-hour notation without AM/PM indication: hy_AM,
496 # id_ID, ms_MY.
497 # * Year is not included: ha_NG.
498 # * Use non-Gregorian calendar: lo_LA, thai, th_TH.
499 # On Windows: ar_IN, ar_SA, fa_IR, ps_AF.
500 @run_with_locales('LC_TIME', 'C', 'en_US', 'fr_FR', 'de_DE', 'ja_JP',
501 'he_IL', 'eu_ES', 'ar_AE', 'mfe_MU', 'yo_NG',
502 'csb_PL', 'br_FR', 'gez_ET', 'brx_IN',
503 'my_MM', 'or_IN', 'shn_MM', 'az_IR',
504 'byn_ER', 'wal_ET', 'lzh_TW')
505 def test_date_time_locale(self):
506 # Test %c directive
507 loc = locale.getlocale(locale.LC_TIME)[0]
508 if glibc_ver and glibc_ver < (2, 31) and loc == 'br_FR':
509 self.skipTest('%c in locale br_FR does not include time')
510 now = time.time()
511 self.roundtrip('%c', slice(0, 6), time.localtime(now))
512 # 1 hour 20 minutes 30 seconds ago
513 self.roundtrip('%c', slice(0, 6), time.localtime(now - 4830))
514 # 12 hours ago
515 self.roundtrip('%c', slice(0, 6), time.localtime(now - 12*3600))
516 # different days of the week
517 for i in range(1, 7):
518 self.roundtrip('%c', slice(0, 6), time.localtime(now - i*24*3600))
519 # different months
520 for i in range(1, 12):
521 self.roundtrip('%c', slice(0, 6), time.localtime(now - i*30*24*3600))
522 # different year
523 self.roundtrip('%c', slice(0, 6), time.localtime(now - 366*24*3600))
524
525 # NB: Dates before 1969 do not roundtrip on some locales:
526 # az_IR, bo_CN, bo_IN, dz_BT, eu_ES, eu_FR, fa_IR, or_IN.
527 @support.run_with_tz('STD-1DST,M4.1.0,M10.1.0')
528 @run_with_locales('LC_TIME', 'C', 'en_US', 'fr_FR', 'de_DE', 'ja_JP',
529 'he_IL', 'ar_AE', 'mfe_MU', 'yo_NG',
530 'csb_PL', 'br_FR', 'gez_ET', 'brx_IN',
531 'my_MM', 'shn_MM')
532 def test_date_time_locale2(self):
533 # Test %c directive
534 loc = locale.getlocale(locale.LC_TIME)[0]
535 if sys.platform.startswith('sunos'):
536 if loc in ('ar_AE',):
537 self.skipTest(f'locale {loc!r} may not work on this platform')
538 self.roundtrip('%c', slice(0, 6), (1900, 1, 1, 0, 0, 0, 0, 1, 0))
539 self.roundtrip('%c', slice(0, 6), (1800, 1, 1, 0, 0, 0, 0, 1, 0))
540
541 # NB: Does not roundtrip because use non-Gregorian calendar:
542 # lo_LA, thai, th_TH. On Windows: ar_IN, ar_SA, fa_IR, ps_AF.
543 @run_with_locales('LC_TIME', 'C', 'en_US', 'fr_FR', 'de_DE', 'ja_JP',
544 'he_IL', 'eu_ES', 'ar_AE',
545 'az_IR', 'my_MM', 'or_IN', 'shn_MM', 'lzh_TW')
546 def test_date_locale(self):
547 # Test %x directive
548 now = time.time()
549 self.roundtrip('%x', slice(0, 3), time.localtime(now))
550 # different days of the week
551 for i in range(1, 7):
552 self.roundtrip('%x', slice(0, 3), time.localtime(now - i*24*3600))
553 # different months
554 for i in range(1, 12):
555 self.roundtrip('%x', slice(0, 3), time.localtime(now - i*30*24*3600))
556 # different year
557 self.roundtrip('%x', slice(0, 3), time.localtime(now - 366*24*3600))
558
559 # NB: Dates before 1969 do not roundtrip on many locales, including C.
560 @unittest.skipIf(
561 support.is_emscripten or support.is_wasi,
562 "musl libc issue on Emscripten, bpo-46390"
563 )
564 @run_with_locales('LC_TIME', 'en_US', 'fr_FR', 'de_DE', 'ja_JP',
565 'eu_ES', 'ar_AE', 'my_MM', 'shn_MM', 'lzh_TW')
566 def test_date_locale2(self):
567 # Test %x directive
568 loc = locale.getlocale(locale.LC_TIME)[0]
569 if sys.platform.startswith(('sunos', 'aix')):
570 if loc in ('en_US', 'de_DE', 'ar_AE'):
571 self.skipTest(f'locale {loc!r} may not work on this platform')
572 self.roundtrip('%x', slice(0, 3), (1900, 1, 1, 0, 0, 0, 0, 1, 0))
573 self.roundtrip('%x', slice(0, 3), (1800, 1, 1, 0, 0, 0, 0, 1, 0))
574
575 # NB: Does not roundtrip in some locales due to the ambiguity of
576 # the time representation (bugs in locales?):
577 # * Seconds are not included: bokmal, ff_SN, nb_NO, nn_NO, no_NO,
578 # norwegian, nynorsk.
579 # * Hours are in 12-hour notation without AM/PM indication: hy_AM,
580 # ms_MY, sm_WS.
581 @run_with_locales('LC_TIME', 'C', 'en_US', 'fr_FR', 'de_DE', 'ja_JP',
582 'aa_ET', 'am_ET', 'az_IR', 'byn_ER', 'fa_IR', 'gez_ET',
583 'my_MM', 'om_ET', 'or_IN', 'shn_MM', 'sid_ET', 'so_SO',
584 'ti_ET', 'tig_ER', 'wal_ET', 'lzh_TW',
585 'ar_SA', 'bg_BG')
586 def test_time_locale(self):
587 # Test %X directive
588 loc = locale.getlocale(locale.LC_TIME)[0]
589 pos = slice(3, 6)
590 if glibc_ver and glibc_ver < (2, 29) and loc in {
591 'aa_ET', 'am_ET', 'byn_ER', 'gez_ET', 'om_ET',
592 'sid_ET', 'so_SO', 'ti_ET', 'tig_ER', 'wal_ET'}:
593 # Hours are in 12-hour notation without AM/PM indication.
594 # Ignore hours.
595 pos = slice(4, 6)
596 now = time.time()
597 self.roundtrip('%X', pos, time.localtime(now))
598 # 1 hour 20 minutes 30 seconds ago
599 self.roundtrip('%X', pos, time.localtime(now - 4830))
600 # 12 hours ago
601 self.roundtrip('%X', pos, time.localtime(now - 12*3600))
602
603 def test_percent(self):
604 # Make sure % signs are handled properly
605 strf_output = time.strftime("%m %% %Y", self.time_tuple)
606 strp_output = _strptime._strptime_time(strf_output, "%m %% %Y")
607 self.assertTrue(strp_output[0] == self.time_tuple[0] and
608 strp_output[1] == self.time_tuple[1],
609 "handling of percent sign failed")
610
611 def test_caseinsensitive(self):
612 # Should handle names case-insensitively.
613 strf_output = time.strftime("%B", self.time_tuple)
614 self.assertTrue(_strptime._strptime_time(strf_output.upper(), "%B"),
615 "strptime does not handle ALL-CAPS names properly")
616 self.assertTrue(_strptime._strptime_time(strf_output.lower(), "%B"),
617 "strptime does not handle lowercase names properly")
618 self.assertTrue(_strptime._strptime_time(strf_output.capitalize(), "%B"),
619 "strptime does not handle capword names properly")
620
621 def test_defaults(self):
622 # Default return value should be (1900, 1, 1, 0, 0, 0, 0, 1, 0)
623 defaults = (1900, 1, 1, 0, 0, 0, 0, 1, -1)
624 strp_output = _strptime._strptime_time('1', '%m')
625 self.assertTrue(strp_output == defaults,
626 "Default values for strptime() are incorrect;"
627 " %s != %s" % (strp_output, defaults))
628
629 def test_escaping(self):
630 # Make sure all characters that have regex significance are escaped.
631 # Parentheses are in a purposeful order; will cause an error of
632 # unbalanced parentheses when the regex is compiled if they are not
633 # escaped.
634 # Test instigated by bug #796149 .
635 need_escaping = r".^$*+?{}\[]|)("
636 self.assertTrue(_strptime._strptime_time(need_escaping, need_escaping))
637
638 @warnings_helper.ignore_warnings(category=DeprecationWarning) # gh-70647
639 def test_feb29_on_leap_year_without_year(self):
640 time.strptime("Feb 29", "%b %d")
641
642 @warnings_helper.ignore_warnings(category=DeprecationWarning) # gh-70647
643 def test_mar1_comes_after_feb29_even_when_omitting_the_year(self):
644 self.assertLess(
645 time.strptime("Feb 29", "%b %d"),
646 time.strptime("Mar 1", "%b %d"))
647
648 class Strptime12AMPMTests(unittest.TestCase):
649 """Test a _strptime regression in '%I %p' at 12 noon (12 PM)"""
650
651 def test_twelve_noon_midnight(self):
652 eq = self.assertEqual
653 eq(time.strptime('12 PM', '%I %p')[3], 12)
654 eq(time.strptime('12 AM', '%I %p')[3], 0)
655 eq(_strptime._strptime_time('12 PM', '%I %p')[3], 12)
656 eq(_strptime._strptime_time('12 AM', '%I %p')[3], 0)
657
658
659 class JulianTests(unittest.TestCase):
660 """Test a _strptime regression that all julian (1-366) are accepted"""
661
662 def test_all_julian_days(self):
663 eq = self.assertEqual
664 for i in range(1, 367):
665 # use 2004, since it is a leap year, we have 366 days
666 eq(_strptime._strptime_time('%d 2004' % i, '%j %Y')[7], i)
667
668 class CalculationTests(unittest.TestCase):
669 """Test that strptime() fills in missing info correctly"""
670
671 def setUp(self):
672 self.time_tuple = time.gmtime()
673
674 @skip_if_buggy_ucrt_strfptime
675 def test_julian_calculation(self):
676 # Make sure that when Julian is missing that it is calculated
677 format_string = "%Y %m %d %H %M %S %w %Z"
678 result = _strptime._strptime_time(time.strftime(format_string, self.time_tuple),
679 format_string)
680 self.assertTrue(result.tm_yday == self.time_tuple.tm_yday,
681 "Calculation of tm_yday failed; %s != %s" %
682 (result.tm_yday, self.time_tuple.tm_yday))
683
684 @skip_if_buggy_ucrt_strfptime
685 def test_gregorian_calculation(self):
686 # Test that Gregorian date can be calculated from Julian day
687 format_string = "%Y %H %M %S %w %j %Z"
688 result = _strptime._strptime_time(time.strftime(format_string, self.time_tuple),
689 format_string)
690 self.assertTrue(result.tm_year == self.time_tuple.tm_year and
691 result.tm_mon == self.time_tuple.tm_mon and
692 result.tm_mday == self.time_tuple.tm_mday,
693 "Calculation of Gregorian date failed; "
694 "%s-%s-%s != %s-%s-%s" %
695 (result.tm_year, result.tm_mon, result.tm_mday,
696 self.time_tuple.tm_year, self.time_tuple.tm_mon,
697 self.time_tuple.tm_mday))
698
699 @skip_if_buggy_ucrt_strfptime
700 def test_day_of_week_calculation(self):
701 # Test that the day of the week is calculated as needed
702 format_string = "%Y %m %d %H %S %j %Z"
703 result = _strptime._strptime_time(time.strftime(format_string, self.time_tuple),
704 format_string)
705 self.assertTrue(result.tm_wday == self.time_tuple.tm_wday,
706 "Calculation of day of the week failed; "
707 "%s != %s" % (result.tm_wday, self.time_tuple.tm_wday))
708
709 if support.is_android:
710 # Issue #26929: strftime() on Android incorrectly formats %V or %G for
711 # the last or the first incomplete week in a year.
712 _ymd_excluded = ((1905, 1, 1), (1906, 12, 31), (2008, 12, 29),
713 (1917, 12, 31))
714 _formats_excluded = ('%G %V',)
715 else:
716 _ymd_excluded = ()
717 _formats_excluded = ()
718
719 @unittest.skipIf(sys.platform.startswith('aix'),
720 'bpo-29972: broken test on AIX')
721 def test_week_of_year_and_day_of_week_calculation(self):
722 # Should be able to infer date if given year, week of year (%U or %W)
723 # and day of the week
724 def test_helper(ymd_tuple, test_reason):
725 for year_week_format in ('%Y %W', '%Y %U', '%G %V'):
726 if (year_week_format in self._formats_excluded and
727 ymd_tuple in self._ymd_excluded):
728 return
729 for weekday_format in ('%w', '%u', '%a', '%A'):
730 format_string = year_week_format + ' ' + weekday_format
731 with self.subTest(test_reason,
732 date=ymd_tuple,
733 format=format_string):
734 dt_date = datetime_date(*ymd_tuple)
735 strp_input = dt_date.strftime(format_string)
736 strp_output = _strptime._strptime_time(strp_input,
737 format_string)
738 msg = "%r: %s != %s" % (strp_input,
739 strp_output[7],
740 dt_date.timetuple()[7])
741 self.assertEqual(strp_output[:3], ymd_tuple, msg)
742 test_helper((1901, 1, 3), "week 0")
743 test_helper((1901, 1, 8), "common case")
744 test_helper((1901, 1, 13), "day on Sunday")
745 test_helper((1901, 1, 14), "day on Monday")
746 test_helper((1905, 1, 1), "Jan 1 on Sunday")
747 test_helper((1906, 1, 1), "Jan 1 on Monday")
748 test_helper((1906, 1, 7), "first Sunday in a year starting on Monday")
749 test_helper((1905, 12, 31), "Dec 31 on Sunday")
750 test_helper((1906, 12, 31), "Dec 31 on Monday")
751 test_helper((2008, 12, 29), "Monday in the last week of the year")
752 test_helper((2008, 12, 22), "Monday in the second-to-last week of the "
753 "year")
754 test_helper((1978, 10, 23), "randomly chosen date")
755 test_helper((2004, 12, 18), "randomly chosen date")
756 test_helper((1978, 10, 23), "year starting and ending on Monday while "
757 "date not on Sunday or Monday")
758 test_helper((1917, 12, 17), "year starting and ending on Monday with "
759 "a Monday not at the beginning or end "
760 "of the year")
761 test_helper((1917, 12, 31), "Dec 31 on Monday with year starting and "
762 "ending on Monday")
763 test_helper((2007, 1, 7), "First Sunday of 2007")
764 test_helper((2007, 1, 14), "Second Sunday of 2007")
765 test_helper((2006, 12, 31), "Last Sunday of 2006")
766 test_helper((2006, 12, 24), "Second to last Sunday of 2006")
767
768 def test_week_0(self):
769 def check(value, format, *expected):
770 self.assertEqual(_strptime._strptime_time(value, format)[:-1], expected)
771 check('2015 0 0', '%Y %U %w', 2014, 12, 28, 0, 0, 0, 6, 362)
772 check('2015 0 0', '%Y %W %w', 2015, 1, 4, 0, 0, 0, 6, 4)
773 check('2015 1 1', '%G %V %u', 2014, 12, 29, 0, 0, 0, 0, 363)
774 check('2015 0 1', '%Y %U %w', 2014, 12, 29, 0, 0, 0, 0, 363)
775 check('2015 0 1', '%Y %W %w', 2014, 12, 29, 0, 0, 0, 0, 363)
776 check('2015 1 2', '%G %V %u', 2014, 12, 30, 0, 0, 0, 1, 364)
777 check('2015 0 2', '%Y %U %w', 2014, 12, 30, 0, 0, 0, 1, 364)
778 check('2015 0 2', '%Y %W %w', 2014, 12, 30, 0, 0, 0, 1, 364)
779 check('2015 1 3', '%G %V %u', 2014, 12, 31, 0, 0, 0, 2, 365)
780 check('2015 0 3', '%Y %U %w', 2014, 12, 31, 0, 0, 0, 2, 365)
781 check('2015 0 3', '%Y %W %w', 2014, 12, 31, 0, 0, 0, 2, 365)
782 check('2015 1 4', '%G %V %u', 2015, 1, 1, 0, 0, 0, 3, 1)
783 check('2015 0 4', '%Y %U %w', 2015, 1, 1, 0, 0, 0, 3, 1)
784 check('2015 0 4', '%Y %W %w', 2015, 1, 1, 0, 0, 0, 3, 1)
785 check('2015 1 5', '%G %V %u', 2015, 1, 2, 0, 0, 0, 4, 2)
786 check('2015 0 5', '%Y %U %w', 2015, 1, 2, 0, 0, 0, 4, 2)
787 check('2015 0 5', '%Y %W %w', 2015, 1, 2, 0, 0, 0, 4, 2)
788 check('2015 1 6', '%G %V %u', 2015, 1, 3, 0, 0, 0, 5, 3)
789 check('2015 0 6', '%Y %U %w', 2015, 1, 3, 0, 0, 0, 5, 3)
790 check('2015 0 6', '%Y %W %w', 2015, 1, 3, 0, 0, 0, 5, 3)
791 check('2015 1 7', '%G %V %u', 2015, 1, 4, 0, 0, 0, 6, 4)
792
793 check('2009 0 0', '%Y %U %w', 2008, 12, 28, 0, 0, 0, 6, 363)
794 check('2009 0 0', '%Y %W %w', 2009, 1, 4, 0, 0, 0, 6, 4)
795 check('2009 1 1', '%G %V %u', 2008, 12, 29, 0, 0, 0, 0, 364)
796 check('2009 0 1', '%Y %U %w', 2008, 12, 29, 0, 0, 0, 0, 364)
797 check('2009 0 1', '%Y %W %w', 2008, 12, 29, 0, 0, 0, 0, 364)
798 check('2009 1 2', '%G %V %u', 2008, 12, 30, 0, 0, 0, 1, 365)
799 check('2009 0 2', '%Y %U %w', 2008, 12, 30, 0, 0, 0, 1, 365)
800 check('2009 0 2', '%Y %W %w', 2008, 12, 30, 0, 0, 0, 1, 365)
801 check('2009 1 3', '%G %V %u', 2008, 12, 31, 0, 0, 0, 2, 366)
802 check('2009 0 3', '%Y %U %w', 2008, 12, 31, 0, 0, 0, 2, 366)
803 check('2009 0 3', '%Y %W %w', 2008, 12, 31, 0, 0, 0, 2, 366)
804 check('2009 1 4', '%G %V %u', 2009, 1, 1, 0, 0, 0, 3, 1)
805 check('2009 0 4', '%Y %U %w', 2009, 1, 1, 0, 0, 0, 3, 1)
806 check('2009 0 4', '%Y %W %w', 2009, 1, 1, 0, 0, 0, 3, 1)
807 check('2009 1 5', '%G %V %u', 2009, 1, 2, 0, 0, 0, 4, 2)
808 check('2009 0 5', '%Y %U %w', 2009, 1, 2, 0, 0, 0, 4, 2)
809 check('2009 0 5', '%Y %W %w', 2009, 1, 2, 0, 0, 0, 4, 2)
810 check('2009 1 6', '%G %V %u', 2009, 1, 3, 0, 0, 0, 5, 3)
811 check('2009 0 6', '%Y %U %w', 2009, 1, 3, 0, 0, 0, 5, 3)
812 check('2009 0 6', '%Y %W %w', 2009, 1, 3, 0, 0, 0, 5, 3)
813 check('2009 1 7', '%G %V %u', 2009, 1, 4, 0, 0, 0, 6, 4)
814
815
816 class CacheTests(unittest.TestCase):
817 """Test that caching works properly."""
818
819 def test_time_re_recreation(self):
820 # Make sure cache is recreated when current locale does not match what
821 # cached object was created with.
822 _strptime._strptime_time("10 2004", "%d %Y")
823 _strptime._strptime_time("2005", "%Y")
824 _strptime._TimeRE_cache.locale_time.lang = "Ni"
825 original_time_re = _strptime._TimeRE_cache
826 _strptime._strptime_time("10 2004", "%d %Y")
827 self.assertIsNot(original_time_re, _strptime._TimeRE_cache)
828 self.assertEqual(len(_strptime._regex_cache), 1)
829
830 def test_regex_cleanup(self):
831 # Make sure cached regexes are discarded when cache becomes "full".
832 try:
833 del _strptime._regex_cache['%d %Y']
834 except KeyError:
835 pass
836 bogus_key = 0
837 while len(_strptime._regex_cache) <= _strptime._CACHE_MAX_SIZE:
838 _strptime._regex_cache[bogus_key] = None
839 bogus_key += 1
840 _strptime._strptime_time("10 2004", "%d %Y")
841 self.assertEqual(len(_strptime._regex_cache), 1)
842
843 def test_new_localetime(self):
844 # A new LocaleTime instance should be created when a new TimeRE object
845 # is created.
846 locale_time_id = _strptime._TimeRE_cache.locale_time
847 _strptime._TimeRE_cache.locale_time.lang = "Ni"
848 _strptime._strptime_time("10 2004", "%d %Y")
849 self.assertIsNot(locale_time_id, _strptime._TimeRE_cache.locale_time)
850
851 def test_TimeRE_recreation_locale(self):
852 # The TimeRE instance should be recreated upon changing the locale.
853 with support.run_with_locale('LC_TIME', 'en_US.UTF8'):
854 _strptime._strptime_time('10 2004', '%d %Y')
855 # Get id of current cache object.
856 first_time_re = _strptime._TimeRE_cache
857 try:
858 # Change the locale and force a recreation of the cache.
859 locale.setlocale(locale.LC_TIME, ('de_DE', 'UTF8'))
860 _strptime._strptime_time('10 2004', '%d %Y')
861 # Get the new cache object's id.
862 second_time_re = _strptime._TimeRE_cache
863 # They should not be equal.
864 self.assertIsNot(first_time_re, second_time_re)
865 # Possible test locale is not supported while initial locale is.
866 # If this is the case just suppress the exception and fall-through
867 # to the resetting to the original locale.
868 except locale.Error:
869 self.skipTest('test needs de_DE.UTF8 locale')
870
871 @support.run_with_tz('STD-1DST,M4.1.0,M10.1.0')
872 def test_TimeRE_recreation_timezone(self):
873 # The TimeRE instance should be recreated upon changing the timezone.
874 oldtzname = time.tzname
875 tm = _strptime._strptime_time(time.tzname[0], '%Z')
876 self.assertEqual(tm.tm_isdst, 0)
877 tm = _strptime._strptime_time(time.tzname[1], '%Z')
878 self.assertEqual(tm.tm_isdst, 1)
879 # Get id of current cache object.
880 first_time_re = _strptime._TimeRE_cache
881 # Change the timezone and force a recreation of the cache.
882 os.environ['TZ'] = 'EST+05EDT,M3.2.0,M11.1.0'
883 time.tzset()
884 tm = _strptime._strptime_time(time.tzname[0], '%Z')
885 self.assertEqual(tm.tm_isdst, 0)
886 tm = _strptime._strptime_time(time.tzname[1], '%Z')
887 self.assertEqual(tm.tm_isdst, 1)
888 # Get the new cache object's id.
889 second_time_re = _strptime._TimeRE_cache
890 # They should not be equal.
891 self.assertIsNot(first_time_re, second_time_re)
892 # Make sure old names no longer accepted.
893 with self.assertRaises(ValueError):
894 _strptime._strptime_time(oldtzname[0], '%Z')
895 with self.assertRaises(ValueError):
896 _strptime._strptime_time(oldtzname[1], '%Z')
897
898
899 if __name__ == '__main__':
900 unittest.main()