blob: 80e43fafad81307646e0161775b082611dc0da18 [file] [log] [blame]
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001from test import support
Victor Stinner3e2c8d82015-09-09 22:32:48 +02002import decimal
Victor Stinner992c43f2015-03-27 17:12:45 +01003import enum
4import locale
Victor Stinner3e2c8d82015-09-09 22:32:48 +02005import math
Victor Stinner992c43f2015-03-27 17:12:45 +01006import platform
7import sys
8import sysconfig
Barry Warsawb0c22321996-12-06 23:30:07 +00009import time
pdoxe14679c2017-10-05 00:01:56 -070010import threading
Fred Drakebc561982001-05-22 17:02:02 +000011import unittest
Victor Stinnerec895392012-04-29 02:41:27 +020012try:
Victor Stinner34dc0f42015-03-27 18:19:03 +010013 import _testcapi
14except ImportError:
15 _testcapi = None
16
Paul Monson9cd39b12019-07-18 06:56:59 -070017from test.support import skip_if_buggy_ucrt_strfptime
Barry Warsawb0c22321996-12-06 23:30:07 +000018
Florent Xiclunabceb5282011-11-01 14:11:34 +010019# Max year is only limited by the size of C int.
20SIZEOF_INT = sysconfig.get_config_var('SIZEOF_INT') or 4
21TIME_MAXYEAR = (1 << 8 * SIZEOF_INT - 1) - 1
Gregory P. Smith76be0ff2018-08-24 18:08:50 -070022TIME_MINYEAR = -TIME_MAXYEAR - 1 + 1900
Victor Stinner992c43f2015-03-27 17:12:45 +010023
Victor Stinner3e2c8d82015-09-09 22:32:48 +020024SEC_TO_US = 10 ** 6
Victor Stinner62d1c702015-04-01 17:47:07 +020025US_TO_NS = 10 ** 3
26MS_TO_NS = 10 ** 6
Victor Stinner4bfb4602015-03-27 22:27:24 +010027SEC_TO_NS = 10 ** 9
Victor Stinner3e2c8d82015-09-09 22:32:48 +020028NS_TO_SEC = 10 ** 9
Victor Stinner992c43f2015-03-27 17:12:45 +010029
30class _PyTime(enum.IntEnum):
Victor Stinnerbcdd7772015-03-30 03:52:49 +020031 # Round towards minus infinity (-inf)
Victor Stinnera695f832015-03-30 03:57:14 +020032 ROUND_FLOOR = 0
Victor Stinnerbcdd7772015-03-30 03:52:49 +020033 # Round towards infinity (+inf)
Victor Stinnera695f832015-03-30 03:57:14 +020034 ROUND_CEILING = 1
Victor Stinner7667f582015-09-09 01:02:23 +020035 # Round to nearest with ties going to nearest even integer
36 ROUND_HALF_EVEN = 2
Pablo Galindo2c15b292017-10-17 15:14:41 +010037 # Round away from zero
38 ROUND_UP = 3
Victor Stinner992c43f2015-03-27 17:12:45 +010039
Victor Stinner3e2c8d82015-09-09 22:32:48 +020040# Rounding modes supported by PyTime
41ROUNDING_MODES = (
42 # (PyTime rounding method, decimal rounding method)
43 (_PyTime.ROUND_FLOOR, decimal.ROUND_FLOOR),
44 (_PyTime.ROUND_CEILING, decimal.ROUND_CEILING),
45 (_PyTime.ROUND_HALF_EVEN, decimal.ROUND_HALF_EVEN),
Pablo Galindo2c15b292017-10-17 15:14:41 +010046 (_PyTime.ROUND_UP, decimal.ROUND_UP),
Victor Stinner3e2c8d82015-09-09 22:32:48 +020047)
Florent Xiclunabceb5282011-11-01 14:11:34 +010048
49
Fred Drakebc561982001-05-22 17:02:02 +000050class TimeTestCase(unittest.TestCase):
Barry Warsawb0c22321996-12-06 23:30:07 +000051
Fred Drakebc561982001-05-22 17:02:02 +000052 def setUp(self):
53 self.t = time.time()
Barry Warsawb0c22321996-12-06 23:30:07 +000054
Fred Drakebc561982001-05-22 17:02:02 +000055 def test_data_attributes(self):
56 time.altzone
57 time.daylight
58 time.timezone
59 time.tzname
Barry Warsawb0c22321996-12-06 23:30:07 +000060
Victor Stinnerec895392012-04-29 02:41:27 +020061 def test_time(self):
62 time.time()
63 info = time.get_clock_info('time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040064 self.assertFalse(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +020065 self.assertTrue(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020066
Victor Stinnerc29b5852017-11-02 07:28:27 -070067 def test_time_ns_type(self):
68 def check_ns(sec, ns):
69 self.assertIsInstance(ns, int)
70
71 sec_ns = int(sec * 1e9)
72 # tolerate a difference of 50 ms
73 self.assertLess((sec_ns - ns), 50 ** 6, (sec, ns))
74
75 check_ns(time.time(),
76 time.time_ns())
77 check_ns(time.monotonic(),
78 time.monotonic_ns())
79 check_ns(time.perf_counter(),
80 time.perf_counter_ns())
81 check_ns(time.process_time(),
82 time.process_time_ns())
83
Antoine Pitrou4bd41c92017-11-15 22:52:21 +010084 if hasattr(time, 'thread_time'):
85 check_ns(time.thread_time(),
86 time.thread_time_ns())
87
Victor Stinnerc29b5852017-11-02 07:28:27 -070088 if hasattr(time, 'clock_gettime'):
89 check_ns(time.clock_gettime(time.CLOCK_REALTIME),
90 time.clock_gettime_ns(time.CLOCK_REALTIME))
91
Victor Stinnere0be4232011-10-25 13:06:09 +020092 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
93 'need time.clock_gettime()')
94 def test_clock_realtime(self):
Victor Stinnerc29b5852017-11-02 07:28:27 -070095 t = time.clock_gettime(time.CLOCK_REALTIME)
96 self.assertIsInstance(t, float)
Victor Stinnere0be4232011-10-25 13:06:09 +020097
98 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
99 'need time.clock_gettime()')
100 @unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'),
101 'need time.CLOCK_MONOTONIC')
102 def test_clock_monotonic(self):
103 a = time.clock_gettime(time.CLOCK_MONOTONIC)
104 b = time.clock_gettime(time.CLOCK_MONOTONIC)
105 self.assertLessEqual(a, b)
106
pdoxe14679c2017-10-05 00:01:56 -0700107 @unittest.skipUnless(hasattr(time, 'pthread_getcpuclockid'),
108 'need time.pthread_getcpuclockid()')
109 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
110 'need time.clock_gettime()')
pdoxe14679c2017-10-05 00:01:56 -0700111 def test_pthread_getcpuclockid(self):
112 clk_id = time.pthread_getcpuclockid(threading.get_ident())
113 self.assertTrue(type(clk_id) is int)
Michael Felte2926b72018-12-28 14:57:37 +0100114 # when in 32-bit mode AIX only returns the predefined constant
115 if not platform.system() == "AIX":
116 self.assertNotEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
117 elif (sys.maxsize.bit_length() > 32):
118 self.assertNotEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
119 else:
120 self.assertEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
pdoxe14679c2017-10-05 00:01:56 -0700121 t1 = time.clock_gettime(clk_id)
Benjamin Peterson86566702017-10-05 22:50:42 -0700122 t2 = time.clock_gettime(clk_id)
pdoxe14679c2017-10-05 00:01:56 -0700123 self.assertLessEqual(t1, t2)
pdoxe14679c2017-10-05 00:01:56 -0700124
Victor Stinnere0be4232011-10-25 13:06:09 +0200125 @unittest.skipUnless(hasattr(time, 'clock_getres'),
126 'need time.clock_getres()')
127 def test_clock_getres(self):
128 res = time.clock_getres(time.CLOCK_REALTIME)
129 self.assertGreater(res, 0.0)
130 self.assertLessEqual(res, 1.0)
131
Victor Stinner30d79472012-04-03 00:45:07 +0200132 @unittest.skipUnless(hasattr(time, 'clock_settime'),
133 'need time.clock_settime()')
134 def test_clock_settime(self):
135 t = time.clock_gettime(time.CLOCK_REALTIME)
136 try:
137 time.clock_settime(time.CLOCK_REALTIME, t)
138 except PermissionError:
139 pass
140
Victor Stinnerec895392012-04-29 02:41:27 +0200141 if hasattr(time, 'CLOCK_MONOTONIC'):
142 self.assertRaises(OSError,
143 time.clock_settime, time.CLOCK_MONOTONIC, 0)
Victor Stinner30d79472012-04-03 00:45:07 +0200144
Fred Drakebc561982001-05-22 17:02:02 +0000145 def test_conversions(self):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000146 self.assertEqual(time.ctime(self.t),
147 time.asctime(time.localtime(self.t)))
148 self.assertEqual(int(time.mktime(time.localtime(self.t))),
149 int(self.t))
Fred Drakebc561982001-05-22 17:02:02 +0000150
151 def test_sleep(self):
Victor Stinner7f53a502011-07-05 22:00:25 +0200152 self.assertRaises(ValueError, time.sleep, -2)
153 self.assertRaises(ValueError, time.sleep, -1)
Fred Drakebc561982001-05-22 17:02:02 +0000154 time.sleep(1.2)
155
156 def test_strftime(self):
157 tt = time.gmtime(self.t)
158 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
159 'j', 'm', 'M', 'p', 'S',
160 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
161 format = ' %' + directive
162 try:
163 time.strftime(format, tt)
164 except ValueError:
165 self.fail('conversion specifier: %r failed.' % format)
166
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300167 self.assertRaises(TypeError, time.strftime, b'%S', tt)
168 # embedded null character
169 self.assertRaises(ValueError, time.strftime, '%S\0', tt)
170
Florent Xicluna49ce0682011-11-01 12:56:14 +0100171 def _bounds_checking(self, func):
Brett Cannond1080a32004-03-02 04:38:10 +0000172 # Make sure that strftime() checks the bounds of the various parts
Florent Xicluna49ce0682011-11-01 12:56:14 +0100173 # of the time tuple (0 is valid for *all* values).
Brett Cannond1080a32004-03-02 04:38:10 +0000174
Victor Stinner73ea29c2011-01-08 01:56:31 +0000175 # The year field is tested by other test cases above
176
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000177 # Check month [1, 12] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100178 func((1900, 0, 1, 0, 0, 0, 0, 1, -1))
179 func((1900, 12, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000180 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000181 (1900, -1, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000182 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000183 (1900, 13, 1, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000184 # Check day of month [1, 31] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100185 func((1900, 1, 0, 0, 0, 0, 0, 1, -1))
186 func((1900, 1, 31, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000187 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000188 (1900, 1, -1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000189 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000190 (1900, 1, 32, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000191 # Check hour [0, 23]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100192 func((1900, 1, 1, 23, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000193 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000194 (1900, 1, 1, -1, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000195 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000196 (1900, 1, 1, 24, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000197 # Check minute [0, 59]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100198 func((1900, 1, 1, 0, 59, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000199 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000200 (1900, 1, 1, 0, -1, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000201 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000202 (1900, 1, 1, 0, 60, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000203 # Check second [0, 61]
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000204 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000205 (1900, 1, 1, 0, 0, -1, 0, 1, -1))
206 # C99 only requires allowing for one leap second, but Python's docs say
207 # allow two leap seconds (0..61)
Florent Xicluna49ce0682011-11-01 12:56:14 +0100208 func((1900, 1, 1, 0, 0, 60, 0, 1, -1))
209 func((1900, 1, 1, 0, 0, 61, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000210 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000211 (1900, 1, 1, 0, 0, 62, 0, 1, -1))
212 # No check for upper-bound day of week;
213 # value forced into range by a ``% 7`` calculation.
214 # Start check at -2 since gettmarg() increments value before taking
215 # modulo.
Florent Xicluna49ce0682011-11-01 12:56:14 +0100216 self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)),
217 func((1900, 1, 1, 0, 0, 0, +6, 1, -1)))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000218 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000219 (1900, 1, 1, 0, 0, 0, -2, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000220 # Check day of the year [1, 366] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100221 func((1900, 1, 1, 0, 0, 0, 0, 0, -1))
222 func((1900, 1, 1, 0, 0, 0, 0, 366, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000223 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000224 (1900, 1, 1, 0, 0, 0, 0, -1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000225 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000226 (1900, 1, 1, 0, 0, 0, 0, 367, -1))
Brett Cannond1080a32004-03-02 04:38:10 +0000227
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000228 def test_strftime_bounding_check(self):
229 self._bounds_checking(lambda tup: time.strftime('', tup))
230
Steve Dowere5b58952015-09-06 19:20:51 -0700231 def test_strftime_format_check(self):
232 # Test that strftime does not crash on invalid format strings
233 # that may trigger a buffer overread. When not triggered,
234 # strftime may succeed or raise ValueError depending on
235 # the platform.
236 for x in [ '', 'A', '%A', '%AA' ]:
237 for y in range(0x0, 0x10):
238 for z in [ '%', 'A%', 'AA%', '%A%', 'A%A%', '%#' ]:
239 try:
240 time.strftime(x * y + z)
241 except ValueError:
242 pass
243
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000244 def test_default_values_for_zero(self):
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400245 # Make sure that using all zeros uses the proper default
246 # values. No test for daylight savings since strftime() does
247 # not change output based on its value and no test for year
248 # because systems vary in their support for year 0.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000249 expected = "2000 01 01 00 00 00 1 001"
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000250 with support.check_warnings():
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400251 result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000252 self.assertEqual(expected, result)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000253
Paul Monson9cd39b12019-07-18 06:56:59 -0700254 @skip_if_buggy_ucrt_strfptime
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000255 def test_strptime(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000256 # Should be able to go round-trip from strftime to strptime without
Andrew Svetlov737fb892012-12-18 21:14:22 +0200257 # raising an exception.
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000258 tt = time.gmtime(self.t)
259 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
260 'j', 'm', 'M', 'p', 'S',
261 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000262 format = '%' + directive
263 strf_output = time.strftime(format, tt)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000264 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000265 time.strptime(strf_output, format)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000266 except ValueError:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000267 self.fail("conversion specifier %r failed with '%s' input." %
268 (format, strf_output))
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000269
Brett Cannon7f6b4f82009-03-30 21:30:26 +0000270 def test_strptime_bytes(self):
271 # Make sure only strings are accepted as arguments to strptime.
272 self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
273 self.assertRaises(TypeError, time.strptime, '2009', b'%Y')
274
Ezio Melotti0f389082013-04-04 02:09:20 +0300275 def test_strptime_exception_context(self):
276 # check that this doesn't chain exceptions needlessly (see #17572)
277 with self.assertRaises(ValueError) as e:
278 time.strptime('', '%D')
279 self.assertIs(e.exception.__suppress_context__, True)
Serhiy Storchakacdac3022013-11-24 18:15:37 +0200280 # additional check for IndexError branch (issue #19545)
281 with self.assertRaises(ValueError) as e:
282 time.strptime('19', '%Y %')
283 self.assertIs(e.exception.__suppress_context__, True)
Ezio Melotti0f389082013-04-04 02:09:20 +0300284
Fred Drakebc561982001-05-22 17:02:02 +0000285 def test_asctime(self):
286 time.asctime(time.gmtime(self.t))
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000287
288 # Max year is only limited by the size of C int.
Florent Xiclunabceb5282011-11-01 14:11:34 +0100289 for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
290 asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
291 self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
292 self.assertRaises(OverflowError, time.asctime,
293 (TIME_MAXYEAR + 1,) + (0,) * 8)
294 self.assertRaises(OverflowError, time.asctime,
295 (TIME_MINYEAR - 1,) + (0,) * 8)
Fred Drakebc561982001-05-22 17:02:02 +0000296 self.assertRaises(TypeError, time.asctime, 0)
Alexander Belopolskye2dc0822011-01-02 20:48:22 +0000297 self.assertRaises(TypeError, time.asctime, ())
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000298 self.assertRaises(TypeError, time.asctime, (0,) * 10)
Fred Drakebc561982001-05-22 17:02:02 +0000299
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000300 def test_asctime_bounding_check(self):
301 self._bounds_checking(time.asctime)
302
Georg Brandle10608c2011-01-02 22:33:43 +0000303 def test_ctime(self):
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000304 t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
305 self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
306 t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
307 self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000')
Victor Stinner1ac42612014-02-21 09:27:17 +0100308 for year in [-100, 100, 1000, 2000, 2050, 10000]:
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000309 try:
310 testval = time.mktime((year, 1, 10) + (0,)*6)
311 except (ValueError, OverflowError):
312 # If mktime fails, ctime will fail too. This may happen
313 # on some platforms.
314 pass
315 else:
316 self.assertEqual(time.ctime(testval)[20:], str(year))
Georg Brandle10608c2011-01-02 22:33:43 +0000317
Florent Xiclunae54371e2011-11-11 18:59:30 +0100318 @unittest.skipUnless(hasattr(time, "tzset"),
319 "time module has no attribute tzset")
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000320 def test_tzset(self):
Guido van Rossumd2b738e2003-03-15 12:01:52 +0000321
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000322 from os import environ
323
Tim Peters0eadaac2003-04-24 16:02:54 +0000324 # Epoch time of midnight Dec 25th 2002. Never DST in northern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000325 # hemisphere.
Tim Peters0eadaac2003-04-24 16:02:54 +0000326 xmas2002 = 1040774400.0
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000327
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000328 # These formats are correct for 2002, and possibly future years
329 # This format is the 'standard' as documented at:
330 # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
331 # They are also documented in the tzset(3) man page on most Unix
332 # systems.
Tim Peters0eadaac2003-04-24 16:02:54 +0000333 eastern = 'EST+05EDT,M4.1.0,M10.5.0'
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000334 victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
335 utc='UTC+0'
336
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000337 org_TZ = environ.get('TZ',None)
338 try:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000339 # Make sure we can switch to UTC time and results are correct
340 # Note that unknown timezones default to UTC.
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000341 # Note that altzone is undefined in UTC, as there is no DST
342 environ['TZ'] = eastern
343 time.tzset()
344 environ['TZ'] = utc
345 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000346 self.assertEqual(
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000347 time.gmtime(xmas2002), time.localtime(xmas2002)
348 )
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000349 self.assertEqual(time.daylight, 0)
350 self.assertEqual(time.timezone, 0)
351 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000352
353 # Make sure we can switch to US/Eastern
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000354 environ['TZ'] = eastern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000355 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000356 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
357 self.assertEqual(time.tzname, ('EST', 'EDT'))
358 self.assertEqual(len(time.tzname), 2)
359 self.assertEqual(time.daylight, 1)
360 self.assertEqual(time.timezone, 18000)
361 self.assertEqual(time.altzone, 14400)
362 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
363 self.assertEqual(len(time.tzname), 2)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000364
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000365 # Now go to the southern hemisphere.
366 environ['TZ'] = victoria
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000367 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000368 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
Victor Stinner0cd47902011-12-08 00:32:51 +0100369
370 # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100371 # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
372 # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
373 # on some operating systems (e.g. FreeBSD), which is wrong. See for
374 # example this bug:
375 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
Victor Stinner0cd47902011-12-08 00:32:51 +0100376 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100377 self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000378 self.assertEqual(len(time.tzname), 2)
379 self.assertEqual(time.daylight, 1)
380 self.assertEqual(time.timezone, -36000)
381 self.assertEqual(time.altzone, -39600)
382 self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000383
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000384 finally:
385 # Repair TZ environment variable in case any other tests
386 # rely on it.
387 if org_TZ is not None:
388 environ['TZ'] = org_TZ
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000389 elif 'TZ' in environ:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000390 del environ['TZ']
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000391 time.tzset()
Tim Peters0eadaac2003-04-24 16:02:54 +0000392
Tim Peters1b6f7a92004-06-20 02:50:16 +0000393 def test_insane_timestamps(self):
394 # It's possible that some platform maps time_t to double,
395 # and that this test will fail there. This test should
396 # exempt such platforms (provided they return reasonable
397 # results!).
398 for func in time.ctime, time.gmtime, time.localtime:
399 for unreasonable in -1e200, 1e200:
Victor Stinner5d272cc2012-03-13 13:35:55 +0100400 self.assertRaises(OverflowError, func, unreasonable)
Fred Drakebc561982001-05-22 17:02:02 +0000401
Fred Drakef901abd2004-08-03 17:58:55 +0000402 def test_ctime_without_arg(self):
403 # Not sure how to check the values, since the clock could tick
404 # at any time. Make sure these are at least accepted and
405 # don't raise errors.
406 time.ctime()
407 time.ctime(None)
408
409 def test_gmtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000410 gt0 = time.gmtime()
411 gt1 = time.gmtime(None)
412 t0 = time.mktime(gt0)
413 t1 = time.mktime(gt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000414 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000415
416 def test_localtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000417 lt0 = time.localtime()
418 lt1 = time.localtime(None)
419 t0 = time.mktime(lt0)
420 t1 = time.mktime(lt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000421 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000422
Florent Xiclunae54371e2011-11-11 18:59:30 +0100423 def test_mktime(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100424 # Issue #1726687
425 for t in (-2, -1, 0, 1):
426 try:
427 tt = time.localtime(t)
Victor Stinner2cbae982012-01-27 00:50:33 +0100428 except (OverflowError, OSError):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100429 pass
430 else:
431 self.assertEqual(time.mktime(tt), t)
Florent Xiclunae54371e2011-11-11 18:59:30 +0100432
433 # Issue #13309: passing extreme values to mktime() or localtime()
434 # borks the glibc's internal timezone data.
435 @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
436 "disabled because of a bug in glibc. Issue #13309")
437 def test_mktime_error(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100438 # It may not be possible to reliably make mktime return error
439 # on all platfom. This will make sure that no other exception
440 # than OverflowError is raised for an extreme value.
Florent Xiclunae54371e2011-11-11 18:59:30 +0100441 tt = time.gmtime(self.t)
442 tzname = time.strftime('%Z', tt)
443 self.assertNotEqual(tzname, 'LMT')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100444 try:
445 time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
446 except OverflowError:
447 pass
Florent Xiclunae54371e2011-11-11 18:59:30 +0100448 self.assertEqual(time.strftime('%Z', tt), tzname)
Florent Xiclunabceb5282011-11-01 14:11:34 +0100449
Victor Stinnerec895392012-04-29 02:41:27 +0200450 def test_monotonic(self):
Victor Stinner6c861812013-11-23 00:15:27 +0100451 # monotonic() should not go backward
452 times = [time.monotonic() for n in range(100)]
453 t1 = times[0]
454 for t2 in times[1:]:
455 self.assertGreaterEqual(t2, t1, "times=%s" % times)
456 t1 = t2
457
458 # monotonic() includes time elapsed during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200459 t1 = time.monotonic()
Victor Stinnera9c99a62013-07-03 23:07:37 +0200460 time.sleep(0.5)
Victor Stinnerec895392012-04-29 02:41:27 +0200461 t2 = time.monotonic()
Victor Stinner2dd254d2012-01-20 02:24:18 +0100462 dt = t2 - t1
Victor Stinner8b302012012-02-07 23:29:46 +0100463 self.assertGreater(t2, t1)
Victor Stinnerd246a672019-04-24 00:15:12 +0200464 # bpo-20101: tolerate a difference of 50 ms because of bad timer
465 # resolution on Windows
466 self.assertTrue(0.450 <= dt)
Antoine Pitrou391166f2012-01-18 22:35:21 +0100467
Victor Stinner6c861812013-11-23 00:15:27 +0100468 # monotonic() is a monotonic but non adjustable clock
Victor Stinnerec895392012-04-29 02:41:27 +0200469 info = time.get_clock_info('monotonic')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400470 self.assertTrue(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +0200471 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200472
473 def test_perf_counter(self):
474 time.perf_counter()
475
476 def test_process_time(self):
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200477 # process_time() should not include time spend during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200478 start = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200479 time.sleep(0.100)
Victor Stinnerec895392012-04-29 02:41:27 +0200480 stop = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200481 # use 20 ms because process_time() has usually a resolution of 15 ms
482 # on Windows
483 self.assertLess(stop - start, 0.020)
Victor Stinnerec895392012-04-29 02:41:27 +0200484
485 info = time.get_clock_info('process_time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400486 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200487 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200488
Antoine Pitrou4bd41c92017-11-15 22:52:21 +0100489 def test_thread_time(self):
490 if not hasattr(time, 'thread_time'):
491 if sys.platform.startswith(('linux', 'win')):
492 self.fail("time.thread_time() should be available on %r"
493 % (sys.platform,))
494 else:
495 self.skipTest("need time.thread_time")
496
497 # thread_time() should not include time spend during a sleep
498 start = time.thread_time()
499 time.sleep(0.100)
500 stop = time.thread_time()
501 # use 20 ms because thread_time() has usually a resolution of 15 ms
502 # on Windows
503 self.assertLess(stop - start, 0.020)
504
Antoine Pitrou4bd41c92017-11-15 22:52:21 +0100505 info = time.get_clock_info('thread_time')
506 self.assertTrue(info.monotonic)
507 self.assertFalse(info.adjustable)
508
Victor Stinnerec895392012-04-29 02:41:27 +0200509 @unittest.skipUnless(hasattr(time, 'clock_settime'),
510 'need time.clock_settime')
511 def test_monotonic_settime(self):
512 t1 = time.monotonic()
513 realtime = time.clock_gettime(time.CLOCK_REALTIME)
514 # jump backward with an offset of 1 hour
Victor Stinner071eca32012-03-15 01:17:09 +0100515 try:
Victor Stinnerec895392012-04-29 02:41:27 +0200516 time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
517 except PermissionError as err:
518 self.skipTest(err)
519 t2 = time.monotonic()
520 time.clock_settime(time.CLOCK_REALTIME, realtime)
521 # monotonic must not be affected by system clock updates
Victor Stinner071eca32012-03-15 01:17:09 +0100522 self.assertGreaterEqual(t2, t1)
523
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100524 def test_localtime_failure(self):
525 # Issue #13847: check for localtime() failure
Victor Stinner53d36452012-01-27 01:03:25 +0100526 invalid_time_t = None
527 for time_t in (-1, 2**30, 2**33, 2**60):
528 try:
529 time.localtime(time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100530 except OverflowError:
531 self.skipTest("need 64-bit time_t")
Victor Stinner53d36452012-01-27 01:03:25 +0100532 except OSError:
533 invalid_time_t = time_t
534 break
535 if invalid_time_t is None:
536 self.skipTest("unable to find an invalid time_t value")
537
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100538 self.assertRaises(OSError, time.localtime, invalid_time_t)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100539 self.assertRaises(OSError, time.ctime, invalid_time_t)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100540
Han Lee829dacc2017-09-09 08:05:05 +0900541 # Issue #26669: check for localtime() failure
542 self.assertRaises(ValueError, time.localtime, float("nan"))
543 self.assertRaises(ValueError, time.ctime, float("nan"))
544
Victor Stinnerec895392012-04-29 02:41:27 +0200545 def test_get_clock_info(self):
pxinwrf1464f42019-04-15 17:06:21 +0800546 clocks = ['monotonic', 'perf_counter', 'process_time', 'time']
Victor Stinnerec895392012-04-29 02:41:27 +0200547
548 for name in clocks:
Matthias Bussonniere2500612019-05-12 18:34:44 -0700549 info = time.get_clock_info(name)
Victor Stinner884d13a2017-10-17 14:46:45 -0700550
Victor Stinnerec895392012-04-29 02:41:27 +0200551 #self.assertIsInstance(info, dict)
552 self.assertIsInstance(info.implementation, str)
553 self.assertNotEqual(info.implementation, '')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400554 self.assertIsInstance(info.monotonic, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200555 self.assertIsInstance(info.resolution, float)
556 # 0.0 < resolution <= 1.0
557 self.assertGreater(info.resolution, 0.0)
558 self.assertLessEqual(info.resolution, 1.0)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200559 self.assertIsInstance(info.adjustable, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200560
561 self.assertRaises(ValueError, time.get_clock_info, 'xxx')
562
563
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000564class TestLocale(unittest.TestCase):
565 def setUp(self):
566 self.oldloc = locale.setlocale(locale.LC_ALL)
Fred Drake2e2be372001-09-20 21:33:42 +0000567
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000568 def tearDown(self):
569 locale.setlocale(locale.LC_ALL, self.oldloc)
570
Martin v. Löwisa6a9c4d2009-05-30 06:15:30 +0000571 def test_bug_3061(self):
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000572 try:
573 tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
574 except locale.Error:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600575 self.skipTest('could not set locale.LC_ALL to fr_FR')
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000576 # This should not cause an exception
577 time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
578
Victor Stinner73ea29c2011-01-08 01:56:31 +0000579
Victor Stinner73ea29c2011-01-08 01:56:31 +0000580class _TestAsctimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100581 _format = '%d'
582
Victor Stinner73ea29c2011-01-08 01:56:31 +0000583 def yearstr(self, y):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000584 return time.asctime((y,) + (0,) * 8).split()[-1]
Alexander Belopolskya6867252011-01-05 23:00:47 +0000585
Victor Stinner73ea29c2011-01-08 01:56:31 +0000586 def test_large_year(self):
Victor Stinner73691322011-01-08 02:00:24 +0000587 # Check that it doesn't crash for year > 9999
Victor Stinner73ea29c2011-01-08 01:56:31 +0000588 self.assertEqual(self.yearstr(12345), '12345')
589 self.assertEqual(self.yearstr(123456789), '123456789')
590
591class _TestStrftimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100592
593 # Issue 13305: For years < 1000, the value is not always
594 # padded to 4 digits across platforms. The C standard
595 # assumes year >= 1900, so it does not specify the number
596 # of digits.
597
598 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
599 _format = '%04d'
600 else:
601 _format = '%d'
602
Victor Stinner73ea29c2011-01-08 01:56:31 +0000603 def yearstr(self, y):
Florent Xicluna49ce0682011-11-01 12:56:14 +0100604 return time.strftime('%Y', (y,) + (0,) * 8)
605
606 def test_4dyear(self):
607 # Check that we can return the zero padded value.
608 if self._format == '%04d':
609 self.test_year('%04d')
610 else:
611 def year4d(y):
612 return time.strftime('%4Y', (y,) + (0,) * 8)
613 self.test_year('%04d', func=year4d)
614
Florent Xiclunabceb5282011-11-01 14:11:34 +0100615 def skip_if_not_supported(y):
616 msg = "strftime() is limited to [1; 9999] with Visual Studio"
617 # Check that it doesn't crash for year > 9999
618 try:
619 time.strftime('%Y', (y,) + (0,) * 8)
620 except ValueError:
621 cond = False
622 else:
623 cond = True
624 return unittest.skipUnless(cond, msg)
625
626 @skip_if_not_supported(10000)
627 def test_large_year(self):
628 return super().test_large_year()
629
630 @skip_if_not_supported(0)
631 def test_negative(self):
632 return super().test_negative()
633
634 del skip_if_not_supported
635
636
Ezio Melotti3836d702013-04-11 20:29:42 +0300637class _Test4dYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100638 _format = '%d'
639
640 def test_year(self, fmt=None, func=None):
641 fmt = fmt or self._format
642 func = func or self.yearstr
643 self.assertEqual(func(1), fmt % 1)
644 self.assertEqual(func(68), fmt % 68)
645 self.assertEqual(func(69), fmt % 69)
646 self.assertEqual(func(99), fmt % 99)
647 self.assertEqual(func(999), fmt % 999)
648 self.assertEqual(func(9999), fmt % 9999)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000649
650 def test_large_year(self):
Benjamin Petersone1a34ce2018-09-12 16:21:36 -0700651 self.assertEqual(self.yearstr(12345).lstrip('+'), '12345')
652 self.assertEqual(self.yearstr(123456789).lstrip('+'), '123456789')
653 self.assertEqual(self.yearstr(TIME_MAXYEAR).lstrip('+'), str(TIME_MAXYEAR))
Florent Xiclunabceb5282011-11-01 14:11:34 +0100654 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000655
Victor Stinner301f1212011-01-08 03:06:52 +0000656 def test_negative(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100657 self.assertEqual(self.yearstr(-1), self._format % -1)
Victor Stinner301f1212011-01-08 03:06:52 +0000658 self.assertEqual(self.yearstr(-1234), '-1234')
659 self.assertEqual(self.yearstr(-123456), '-123456')
Florent Xiclunad1bd7f72011-11-01 23:42:05 +0100660 self.assertEqual(self.yearstr(-123456789), str(-123456789))
661 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
Gregory P. Smith76be0ff2018-08-24 18:08:50 -0700662 self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
663 # Modules/timemodule.c checks for underflow
Florent Xiclunabceb5282011-11-01 14:11:34 +0100664 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
Gregory P. Smith76be0ff2018-08-24 18:08:50 -0700665 with self.assertRaises(OverflowError):
666 self.yearstr(-TIME_MAXYEAR - 1)
Victor Stinner301f1212011-01-08 03:06:52 +0000667
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000668
Ezio Melotti3836d702013-04-11 20:29:42 +0300669class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner73ea29c2011-01-08 01:56:31 +0000670 pass
671
Ezio Melotti3836d702013-04-11 20:29:42 +0300672class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner301f1212011-01-08 03:06:52 +0000673 pass
Victor Stinner73ea29c2011-01-08 01:56:31 +0000674
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000675
Victor Stinner643cd682012-03-02 22:54:03 +0100676class TestPytime(unittest.TestCase):
Paul Monson9cd39b12019-07-18 06:56:59 -0700677 @skip_if_buggy_ucrt_strfptime
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400678 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
679 def test_localtime_timezone(self):
Victor Stinner643cd682012-03-02 22:54:03 +0100680
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400681 # Get the localtime and examine it for the offset and zone.
682 lt = time.localtime()
683 self.assertTrue(hasattr(lt, "tm_gmtoff"))
684 self.assertTrue(hasattr(lt, "tm_zone"))
685
686 # See if the offset and zone are similar to the module
687 # attributes.
688 if lt.tm_gmtoff is None:
689 self.assertTrue(not hasattr(time, "timezone"))
690 else:
691 self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
692 if lt.tm_zone is None:
693 self.assertTrue(not hasattr(time, "tzname"))
694 else:
695 self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
696
697 # Try and make UNIX times from the localtime and a 9-tuple
698 # created from the localtime. Test to see that the times are
699 # the same.
700 t = time.mktime(lt); t9 = time.mktime(lt[:9])
701 self.assertEqual(t, t9)
702
703 # Make localtimes from the UNIX times and compare them to
704 # the original localtime, thus making a round trip.
705 new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
706 self.assertEqual(new_lt, lt)
707 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
708 self.assertEqual(new_lt.tm_zone, lt.tm_zone)
709 self.assertEqual(new_lt9, lt)
710 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
711 self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
712
713 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
714 def test_strptime_timezone(self):
715 t = time.strptime("UTC", "%Z")
716 self.assertEqual(t.tm_zone, 'UTC')
717 t = time.strptime("+0500", "%z")
718 self.assertEqual(t.tm_gmtoff, 5 * 3600)
719
720 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
721 def test_short_times(self):
722
723 import pickle
724
725 # Load a short time structure using pickle.
726 st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
727 lt = pickle.loads(st)
728 self.assertIs(lt.tm_gmtoff, None)
729 self.assertIs(lt.tm_zone, None)
Victor Stinner643cd682012-03-02 22:54:03 +0100730
Fred Drake2e2be372001-09-20 21:33:42 +0000731
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200732@unittest.skipIf(_testcapi is None, 'need the _testcapi module')
733class CPyTimeTestCase:
Victor Stinneracea9f62015-09-02 10:39:40 +0200734 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200735 Base class to test the C _PyTime_t API.
Victor Stinneracea9f62015-09-02 10:39:40 +0200736 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200737 OVERFLOW_SECONDS = None
738
Victor Stinner4237d342015-09-10 10:10:39 +0200739 def setUp(self):
740 from _testcapi import SIZEOF_TIME_T
741 bits = SIZEOF_TIME_T * 8 - 1
742 self.time_t_min = -2 ** bits
743 self.time_t_max = 2 ** bits - 1
744
745 def time_t_filter(self, seconds):
746 return (self.time_t_min <= seconds <= self.time_t_max)
747
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200748 def _rounding_values(self, use_float):
749 "Build timestamps used to test rounding."
750
751 units = [1, US_TO_NS, MS_TO_NS, SEC_TO_NS]
752 if use_float:
753 # picoseconds are only tested to pytime_converter accepting floats
754 units.append(1e-3)
755
756 values = (
757 # small values
758 1, 2, 5, 7, 123, 456, 1234,
759 # 10^k - 1
760 9,
761 99,
762 999,
763 9999,
764 99999,
765 999999,
766 # test half even rounding near 0.5, 1.5, 2.5, 3.5, 4.5
767 499, 500, 501,
768 1499, 1500, 1501,
769 2500,
770 3500,
771 4500,
772 )
773
774 ns_timestamps = [0]
775 for unit in units:
776 for value in values:
777 ns = value * unit
778 ns_timestamps.extend((-ns, ns))
779 for pow2 in (0, 5, 10, 15, 22, 23, 24, 30, 33):
780 ns = (2 ** pow2) * SEC_TO_NS
781 ns_timestamps.extend((
782 -ns-1, -ns, -ns+1,
783 ns-1, ns, ns+1
784 ))
785 for seconds in (_testcapi.INT_MIN, _testcapi.INT_MAX):
786 ns_timestamps.append(seconds * SEC_TO_NS)
787 if use_float:
Victor Stinner717a32b2016-08-17 11:07:21 +0200788 # numbers with an exact representation in IEEE 754 (base 2)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200789 for pow2 in (3, 7, 10, 15):
790 ns = 2.0 ** (-pow2)
791 ns_timestamps.extend((-ns, ns))
792
793 # seconds close to _PyTime_t type limit
794 ns = (2 ** 63 // SEC_TO_NS) * SEC_TO_NS
795 ns_timestamps.extend((-ns, ns))
796
797 return ns_timestamps
798
799 def _check_rounding(self, pytime_converter, expected_func,
800 use_float, unit_to_sec, value_filter=None):
801
802 def convert_values(ns_timestamps):
803 if use_float:
804 unit_to_ns = SEC_TO_NS / float(unit_to_sec)
805 values = [ns / unit_to_ns for ns in ns_timestamps]
806 else:
807 unit_to_ns = SEC_TO_NS // unit_to_sec
808 values = [ns // unit_to_ns for ns in ns_timestamps]
809
810 if value_filter:
811 values = filter(value_filter, values)
812
813 # remove duplicates and sort
814 return sorted(set(values))
815
816 # test rounding
817 ns_timestamps = self._rounding_values(use_float)
818 valid_values = convert_values(ns_timestamps)
819 for time_rnd, decimal_rnd in ROUNDING_MODES :
Bo Bayles938045f2018-07-21 12:54:14 -0500820 with decimal.localcontext() as context:
821 context.rounding = decimal_rnd
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200822
Bo Bayles938045f2018-07-21 12:54:14 -0500823 for value in valid_values:
824 debug_info = {'value': value, 'rounding': decimal_rnd}
825 try:
826 result = pytime_converter(value, time_rnd)
827 expected = expected_func(value)
Pablo Galindo293dd232019-11-19 21:34:03 +0000828 except Exception:
Bo Bayles938045f2018-07-21 12:54:14 -0500829 self.fail("Error on timestamp conversion: %s" % debug_info)
830 self.assertEqual(result,
831 expected,
832 debug_info)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200833
834 # test overflow
835 ns = self.OVERFLOW_SECONDS * SEC_TO_NS
836 ns_timestamps = (-ns, ns)
837 overflow_values = convert_values(ns_timestamps)
838 for time_rnd, _ in ROUNDING_MODES :
839 for value in overflow_values:
Victor Stinnerc60542b2015-09-10 15:55:07 +0200840 debug_info = {'value': value, 'rounding': time_rnd}
841 with self.assertRaises(OverflowError, msg=debug_info):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200842 pytime_converter(value, time_rnd)
843
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200844 def check_int_rounding(self, pytime_converter, expected_func,
845 unit_to_sec=1, value_filter=None):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200846 self._check_rounding(pytime_converter, expected_func,
847 False, unit_to_sec, value_filter)
848
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200849 def check_float_rounding(self, pytime_converter, expected_func,
850 unit_to_sec=1, value_filter=None):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200851 self._check_rounding(pytime_converter, expected_func,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200852 True, unit_to_sec, value_filter)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200853
854 def decimal_round(self, x):
855 d = decimal.Decimal(x)
856 d = d.quantize(1)
857 return int(d)
858
859
860class TestCPyTime(CPyTimeTestCase, unittest.TestCase):
861 """
862 Test the C _PyTime_t API.
863 """
864 # _PyTime_t is a 64-bit signed integer
865 OVERFLOW_SECONDS = math.ceil((2**63 + 1) / SEC_TO_NS)
866
Victor Stinner13019fd2015-04-03 13:10:54 +0200867 def test_FromSeconds(self):
868 from _testcapi import PyTime_FromSeconds
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200869
870 # PyTime_FromSeconds() expects a C int, reject values out of range
871 def c_int_filter(secs):
872 return (_testcapi.INT_MIN <= secs <= _testcapi.INT_MAX)
873
874 self.check_int_rounding(lambda secs, rnd: PyTime_FromSeconds(secs),
875 lambda secs: secs * SEC_TO_NS,
876 value_filter=c_int_filter)
Victor Stinner13019fd2015-04-03 13:10:54 +0200877
Han Lee829dacc2017-09-09 08:05:05 +0900878 # test nan
879 for time_rnd, _ in ROUNDING_MODES:
880 with self.assertRaises(TypeError):
881 PyTime_FromSeconds(float('nan'))
882
Victor Stinner992c43f2015-03-27 17:12:45 +0100883 def test_FromSecondsObject(self):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100884 from _testcapi import PyTime_FromSecondsObject
Victor Stinner992c43f2015-03-27 17:12:45 +0100885
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200886 self.check_int_rounding(
887 PyTime_FromSecondsObject,
888 lambda secs: secs * SEC_TO_NS)
Victor Stinner992c43f2015-03-27 17:12:45 +0100889
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200890 self.check_float_rounding(
891 PyTime_FromSecondsObject,
892 lambda ns: self.decimal_round(ns * SEC_TO_NS))
Victor Stinner4bfb4602015-03-27 22:27:24 +0100893
Han Lee829dacc2017-09-09 08:05:05 +0900894 # test nan
895 for time_rnd, _ in ROUNDING_MODES:
896 with self.assertRaises(ValueError):
897 PyTime_FromSecondsObject(float('nan'), time_rnd)
898
Victor Stinner4bfb4602015-03-27 22:27:24 +0100899 def test_AsSecondsDouble(self):
900 from _testcapi import PyTime_AsSecondsDouble
901
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200902 def float_converter(ns):
903 if abs(ns) % SEC_TO_NS == 0:
904 return float(ns // SEC_TO_NS)
905 else:
906 return float(ns) / SEC_TO_NS
Victor Stinner4bfb4602015-03-27 22:27:24 +0100907
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200908 self.check_int_rounding(lambda ns, rnd: PyTime_AsSecondsDouble(ns),
909 float_converter,
910 NS_TO_SEC)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100911
Han Lee829dacc2017-09-09 08:05:05 +0900912 # test nan
913 for time_rnd, _ in ROUNDING_MODES:
914 with self.assertRaises(TypeError):
915 PyTime_AsSecondsDouble(float('nan'))
916
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200917 def create_decimal_converter(self, denominator):
918 denom = decimal.Decimal(denominator)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100919
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200920 def converter(value):
921 d = decimal.Decimal(value) / denom
922 return self.decimal_round(d)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100923
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200924 return converter
Victor Stinner4bfb4602015-03-27 22:27:24 +0100925
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200926 def test_AsTimeval(self):
Victor Stinner95e9cef2015-03-28 01:26:47 +0100927 from _testcapi import PyTime_AsTimeval
Victor Stinner95e9cef2015-03-28 01:26:47 +0100928
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200929 us_converter = self.create_decimal_converter(US_TO_NS)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100930
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200931 def timeval_converter(ns):
932 us = us_converter(ns)
933 return divmod(us, SEC_TO_US)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100934
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200935 if sys.platform == 'win32':
936 from _testcapi import LONG_MIN, LONG_MAX
937
938 # On Windows, timeval.tv_sec type is a C long
939 def seconds_filter(secs):
940 return LONG_MIN <= secs <= LONG_MAX
941 else:
Victor Stinner4237d342015-09-10 10:10:39 +0200942 seconds_filter = self.time_t_filter
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200943
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200944 self.check_int_rounding(PyTime_AsTimeval,
945 timeval_converter,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200946 NS_TO_SEC,
947 value_filter=seconds_filter)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100948
Victor Stinner34dc0f42015-03-27 18:19:03 +0100949 @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec'),
950 'need _testcapi.PyTime_AsTimespec')
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200951 def test_AsTimespec(self):
Victor Stinner34dc0f42015-03-27 18:19:03 +0100952 from _testcapi import PyTime_AsTimespec
Victor Stinner34dc0f42015-03-27 18:19:03 +0100953
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200954 def timespec_converter(ns):
955 return divmod(ns, SEC_TO_NS)
Victor Stinner34dc0f42015-03-27 18:19:03 +0100956
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200957 self.check_int_rounding(lambda ns, rnd: PyTime_AsTimespec(ns),
958 timespec_converter,
Victor Stinner4237d342015-09-10 10:10:39 +0200959 NS_TO_SEC,
960 value_filter=self.time_t_filter)
Victor Stinner34dc0f42015-03-27 18:19:03 +0100961
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200962 def test_AsMilliseconds(self):
Victor Stinner62d1c702015-04-01 17:47:07 +0200963 from _testcapi import PyTime_AsMilliseconds
Victor Stinner62d1c702015-04-01 17:47:07 +0200964
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200965 self.check_int_rounding(PyTime_AsMilliseconds,
966 self.create_decimal_converter(MS_TO_NS),
967 NS_TO_SEC)
Victor Stinner62d1c702015-04-01 17:47:07 +0200968
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200969 def test_AsMicroseconds(self):
Victor Stinner62d1c702015-04-01 17:47:07 +0200970 from _testcapi import PyTime_AsMicroseconds
Victor Stinner62d1c702015-04-01 17:47:07 +0200971
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200972 self.check_int_rounding(PyTime_AsMicroseconds,
973 self.create_decimal_converter(US_TO_NS),
974 NS_TO_SEC)
Victor Stinner62d1c702015-04-01 17:47:07 +0200975
Victor Stinner992c43f2015-03-27 17:12:45 +0100976
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200977class TestOldPyTime(CPyTimeTestCase, unittest.TestCase):
Victor Stinneracea9f62015-09-02 10:39:40 +0200978 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200979 Test the old C _PyTime_t API: _PyTime_ObjectToXXX() functions.
Victor Stinneracea9f62015-09-02 10:39:40 +0200980 """
Victor Stinneracea9f62015-09-02 10:39:40 +0200981
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200982 # time_t is a 32-bit or 64-bit signed integer
983 OVERFLOW_SECONDS = 2 ** 64
984
985 def test_object_to_time_t(self):
Victor Stinneracea9f62015-09-02 10:39:40 +0200986 from _testcapi import pytime_object_to_time_t
987
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200988 self.check_int_rounding(pytime_object_to_time_t,
Victor Stinner4237d342015-09-10 10:10:39 +0200989 lambda secs: secs,
990 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200991
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200992 self.check_float_rounding(pytime_object_to_time_t,
Victor Stinner350b5182015-09-10 11:45:06 +0200993 self.decimal_round,
994 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200995
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200996 def create_converter(self, sec_to_unit):
997 def converter(secs):
998 floatpart, intpart = math.modf(secs)
999 intpart = int(intpart)
1000 floatpart *= sec_to_unit
1001 floatpart = self.decimal_round(floatpart)
1002 if floatpart < 0:
1003 floatpart += sec_to_unit
1004 intpart -= 1
1005 elif floatpart >= sec_to_unit:
1006 floatpart -= sec_to_unit
1007 intpart += 1
1008 return (intpart, floatpart)
1009 return converter
Victor Stinneracea9f62015-09-02 10:39:40 +02001010
Victor Stinneradfefa52015-09-04 23:57:25 +02001011 def test_object_to_timeval(self):
Victor Stinneracea9f62015-09-02 10:39:40 +02001012 from _testcapi import pytime_object_to_timeval
1013
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001014 self.check_int_rounding(pytime_object_to_timeval,
Victor Stinner4237d342015-09-10 10:10:39 +02001015 lambda secs: (secs, 0),
1016 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001017
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001018 self.check_float_rounding(pytime_object_to_timeval,
Victor Stinner350b5182015-09-10 11:45:06 +02001019 self.create_converter(SEC_TO_US),
1020 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001021
Han Lee829dacc2017-09-09 08:05:05 +09001022 # test nan
1023 for time_rnd, _ in ROUNDING_MODES:
1024 with self.assertRaises(ValueError):
1025 pytime_object_to_timeval(float('nan'), time_rnd)
1026
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001027 def test_object_to_timespec(self):
Victor Stinneracea9f62015-09-02 10:39:40 +02001028 from _testcapi import pytime_object_to_timespec
1029
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001030 self.check_int_rounding(pytime_object_to_timespec,
Victor Stinner4237d342015-09-10 10:10:39 +02001031 lambda secs: (secs, 0),
1032 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001033
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001034 self.check_float_rounding(pytime_object_to_timespec,
Victor Stinner350b5182015-09-10 11:45:06 +02001035 self.create_converter(SEC_TO_NS),
1036 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001037
Han Lee829dacc2017-09-09 08:05:05 +09001038 # test nan
1039 for time_rnd, _ in ROUNDING_MODES:
1040 with self.assertRaises(ValueError):
1041 pytime_object_to_timespec(float('nan'), time_rnd)
1042
Victor Stinneracea9f62015-09-02 10:39:40 +02001043
Fred Drake2e2be372001-09-20 21:33:42 +00001044if __name__ == "__main__":
Ezio Melotti3836d702013-04-11 20:29:42 +03001045 unittest.main()