blob: 6ced0470d0756156993917ec18e8daf5c9b9f18a [file] [log] [blame]
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001from test import support
Hai Shi3ddc6342020-06-30 21:46:06 +08002from test.support import warnings_helper
Victor Stinner3e2c8d82015-09-09 22:32:48 +02003import decimal
Victor Stinner992c43f2015-03-27 17:12:45 +01004import enum
5import locale
Victor Stinner3e2c8d82015-09-09 22:32:48 +02006import math
Victor Stinner992c43f2015-03-27 17:12:45 +01007import platform
8import sys
9import sysconfig
Barry Warsawb0c22321996-12-06 23:30:07 +000010import time
pdoxe14679c2017-10-05 00:01:56 -070011import threading
Fred Drakebc561982001-05-22 17:02:02 +000012import unittest
Victor Stinnerec895392012-04-29 02:41:27 +020013try:
Victor Stinner34dc0f42015-03-27 18:19:03 +010014 import _testcapi
15except ImportError:
16 _testcapi = None
17
Paul Monson9cd39b12019-07-18 06:56:59 -070018from test.support import skip_if_buggy_ucrt_strfptime
Barry Warsawb0c22321996-12-06 23:30:07 +000019
Florent Xiclunabceb5282011-11-01 14:11:34 +010020# Max year is only limited by the size of C int.
21SIZEOF_INT = sysconfig.get_config_var('SIZEOF_INT') or 4
22TIME_MAXYEAR = (1 << 8 * SIZEOF_INT - 1) - 1
Gregory P. Smith76be0ff2018-08-24 18:08:50 -070023TIME_MINYEAR = -TIME_MAXYEAR - 1 + 1900
Victor Stinner992c43f2015-03-27 17:12:45 +010024
Victor Stinner3e2c8d82015-09-09 22:32:48 +020025SEC_TO_US = 10 ** 6
Victor Stinner62d1c702015-04-01 17:47:07 +020026US_TO_NS = 10 ** 3
27MS_TO_NS = 10 ** 6
Victor Stinner4bfb4602015-03-27 22:27:24 +010028SEC_TO_NS = 10 ** 9
Victor Stinner3e2c8d82015-09-09 22:32:48 +020029NS_TO_SEC = 10 ** 9
Victor Stinner992c43f2015-03-27 17:12:45 +010030
31class _PyTime(enum.IntEnum):
Victor Stinnerbcdd7772015-03-30 03:52:49 +020032 # Round towards minus infinity (-inf)
Victor Stinnera695f832015-03-30 03:57:14 +020033 ROUND_FLOOR = 0
Victor Stinnerbcdd7772015-03-30 03:52:49 +020034 # Round towards infinity (+inf)
Victor Stinnera695f832015-03-30 03:57:14 +020035 ROUND_CEILING = 1
Victor Stinner7667f582015-09-09 01:02:23 +020036 # Round to nearest with ties going to nearest even integer
37 ROUND_HALF_EVEN = 2
Pablo Galindo2c15b292017-10-17 15:14:41 +010038 # Round away from zero
39 ROUND_UP = 3
Victor Stinner992c43f2015-03-27 17:12:45 +010040
Victor Stinner3e2c8d82015-09-09 22:32:48 +020041# Rounding modes supported by PyTime
42ROUNDING_MODES = (
43 # (PyTime rounding method, decimal rounding method)
44 (_PyTime.ROUND_FLOOR, decimal.ROUND_FLOOR),
45 (_PyTime.ROUND_CEILING, decimal.ROUND_CEILING),
46 (_PyTime.ROUND_HALF_EVEN, decimal.ROUND_HALF_EVEN),
Pablo Galindo2c15b292017-10-17 15:14:41 +010047 (_PyTime.ROUND_UP, decimal.ROUND_UP),
Victor Stinner3e2c8d82015-09-09 22:32:48 +020048)
Florent Xiclunabceb5282011-11-01 14:11:34 +010049
50
Fred Drakebc561982001-05-22 17:02:02 +000051class TimeTestCase(unittest.TestCase):
Barry Warsawb0c22321996-12-06 23:30:07 +000052
Fred Drakebc561982001-05-22 17:02:02 +000053 def setUp(self):
54 self.t = time.time()
Barry Warsawb0c22321996-12-06 23:30:07 +000055
Fred Drakebc561982001-05-22 17:02:02 +000056 def test_data_attributes(self):
57 time.altzone
58 time.daylight
59 time.timezone
60 time.tzname
Barry Warsawb0c22321996-12-06 23:30:07 +000061
Victor Stinnerec895392012-04-29 02:41:27 +020062 def test_time(self):
63 time.time()
64 info = time.get_clock_info('time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040065 self.assertFalse(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +020066 self.assertTrue(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020067
Victor Stinnerc29b5852017-11-02 07:28:27 -070068 def test_time_ns_type(self):
69 def check_ns(sec, ns):
70 self.assertIsInstance(ns, int)
71
72 sec_ns = int(sec * 1e9)
73 # tolerate a difference of 50 ms
74 self.assertLess((sec_ns - ns), 50 ** 6, (sec, ns))
75
76 check_ns(time.time(),
77 time.time_ns())
78 check_ns(time.monotonic(),
79 time.monotonic_ns())
80 check_ns(time.perf_counter(),
81 time.perf_counter_ns())
82 check_ns(time.process_time(),
83 time.process_time_ns())
84
Antoine Pitrou4bd41c92017-11-15 22:52:21 +010085 if hasattr(time, 'thread_time'):
86 check_ns(time.thread_time(),
87 time.thread_time_ns())
88
Victor Stinnerc29b5852017-11-02 07:28:27 -070089 if hasattr(time, 'clock_gettime'):
90 check_ns(time.clock_gettime(time.CLOCK_REALTIME),
91 time.clock_gettime_ns(time.CLOCK_REALTIME))
92
Victor Stinnere0be4232011-10-25 13:06:09 +020093 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
94 'need time.clock_gettime()')
95 def test_clock_realtime(self):
Victor Stinnerc29b5852017-11-02 07:28:27 -070096 t = time.clock_gettime(time.CLOCK_REALTIME)
97 self.assertIsInstance(t, float)
Victor Stinnere0be4232011-10-25 13:06:09 +020098
99 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
100 'need time.clock_gettime()')
101 @unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'),
102 'need time.CLOCK_MONOTONIC')
103 def test_clock_monotonic(self):
104 a = time.clock_gettime(time.CLOCK_MONOTONIC)
105 b = time.clock_gettime(time.CLOCK_MONOTONIC)
106 self.assertLessEqual(a, b)
107
pdoxe14679c2017-10-05 00:01:56 -0700108 @unittest.skipUnless(hasattr(time, 'pthread_getcpuclockid'),
109 'need time.pthread_getcpuclockid()')
110 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
111 'need time.clock_gettime()')
pdoxe14679c2017-10-05 00:01:56 -0700112 def test_pthread_getcpuclockid(self):
113 clk_id = time.pthread_getcpuclockid(threading.get_ident())
114 self.assertTrue(type(clk_id) is int)
Michael Felte2926b72018-12-28 14:57:37 +0100115 # when in 32-bit mode AIX only returns the predefined constant
116 if not platform.system() == "AIX":
117 self.assertNotEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
118 elif (sys.maxsize.bit_length() > 32):
119 self.assertNotEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
120 else:
121 self.assertEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
pdoxe14679c2017-10-05 00:01:56 -0700122 t1 = time.clock_gettime(clk_id)
Benjamin Peterson86566702017-10-05 22:50:42 -0700123 t2 = time.clock_gettime(clk_id)
pdoxe14679c2017-10-05 00:01:56 -0700124 self.assertLessEqual(t1, t2)
pdoxe14679c2017-10-05 00:01:56 -0700125
Victor Stinnere0be4232011-10-25 13:06:09 +0200126 @unittest.skipUnless(hasattr(time, 'clock_getres'),
127 'need time.clock_getres()')
128 def test_clock_getres(self):
129 res = time.clock_getres(time.CLOCK_REALTIME)
130 self.assertGreater(res, 0.0)
131 self.assertLessEqual(res, 1.0)
132
Victor Stinner30d79472012-04-03 00:45:07 +0200133 @unittest.skipUnless(hasattr(time, 'clock_settime'),
134 'need time.clock_settime()')
135 def test_clock_settime(self):
136 t = time.clock_gettime(time.CLOCK_REALTIME)
137 try:
138 time.clock_settime(time.CLOCK_REALTIME, t)
139 except PermissionError:
140 pass
141
Victor Stinnerec895392012-04-29 02:41:27 +0200142 if hasattr(time, 'CLOCK_MONOTONIC'):
143 self.assertRaises(OSError,
144 time.clock_settime, time.CLOCK_MONOTONIC, 0)
Victor Stinner30d79472012-04-03 00:45:07 +0200145
Fred Drakebc561982001-05-22 17:02:02 +0000146 def test_conversions(self):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000147 self.assertEqual(time.ctime(self.t),
148 time.asctime(time.localtime(self.t)))
149 self.assertEqual(int(time.mktime(time.localtime(self.t))),
150 int(self.t))
Fred Drakebc561982001-05-22 17:02:02 +0000151
152 def test_sleep(self):
Victor Stinner7f53a502011-07-05 22:00:25 +0200153 self.assertRaises(ValueError, time.sleep, -2)
154 self.assertRaises(ValueError, time.sleep, -1)
Fred Drakebc561982001-05-22 17:02:02 +0000155 time.sleep(1.2)
156
157 def test_strftime(self):
158 tt = time.gmtime(self.t)
159 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
160 'j', 'm', 'M', 'p', 'S',
161 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
162 format = ' %' + directive
163 try:
164 time.strftime(format, tt)
165 except ValueError:
166 self.fail('conversion specifier: %r failed.' % format)
167
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300168 self.assertRaises(TypeError, time.strftime, b'%S', tt)
169 # embedded null character
170 self.assertRaises(ValueError, time.strftime, '%S\0', tt)
171
Florent Xicluna49ce0682011-11-01 12:56:14 +0100172 def _bounds_checking(self, func):
Brett Cannond1080a32004-03-02 04:38:10 +0000173 # Make sure that strftime() checks the bounds of the various parts
Florent Xicluna49ce0682011-11-01 12:56:14 +0100174 # of the time tuple (0 is valid for *all* values).
Brett Cannond1080a32004-03-02 04:38:10 +0000175
Victor Stinner73ea29c2011-01-08 01:56:31 +0000176 # The year field is tested by other test cases above
177
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000178 # Check month [1, 12] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100179 func((1900, 0, 1, 0, 0, 0, 0, 1, -1))
180 func((1900, 12, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000181 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000182 (1900, -1, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000183 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000184 (1900, 13, 1, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000185 # Check day of month [1, 31] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100186 func((1900, 1, 0, 0, 0, 0, 0, 1, -1))
187 func((1900, 1, 31, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000188 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000189 (1900, 1, -1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000190 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000191 (1900, 1, 32, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000192 # Check hour [0, 23]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100193 func((1900, 1, 1, 23, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000194 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000195 (1900, 1, 1, -1, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000196 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000197 (1900, 1, 1, 24, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000198 # Check minute [0, 59]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100199 func((1900, 1, 1, 0, 59, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000200 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000201 (1900, 1, 1, 0, -1, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000202 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000203 (1900, 1, 1, 0, 60, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000204 # Check second [0, 61]
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000205 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000206 (1900, 1, 1, 0, 0, -1, 0, 1, -1))
207 # C99 only requires allowing for one leap second, but Python's docs say
208 # allow two leap seconds (0..61)
Florent Xicluna49ce0682011-11-01 12:56:14 +0100209 func((1900, 1, 1, 0, 0, 60, 0, 1, -1))
210 func((1900, 1, 1, 0, 0, 61, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000211 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000212 (1900, 1, 1, 0, 0, 62, 0, 1, -1))
213 # No check for upper-bound day of week;
214 # value forced into range by a ``% 7`` calculation.
215 # Start check at -2 since gettmarg() increments value before taking
216 # modulo.
Florent Xicluna49ce0682011-11-01 12:56:14 +0100217 self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)),
218 func((1900, 1, 1, 0, 0, 0, +6, 1, -1)))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000219 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000220 (1900, 1, 1, 0, 0, 0, -2, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000221 # Check day of the year [1, 366] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100222 func((1900, 1, 1, 0, 0, 0, 0, 0, -1))
223 func((1900, 1, 1, 0, 0, 0, 0, 366, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000224 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000225 (1900, 1, 1, 0, 0, 0, 0, -1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000226 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000227 (1900, 1, 1, 0, 0, 0, 0, 367, -1))
Brett Cannond1080a32004-03-02 04:38:10 +0000228
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000229 def test_strftime_bounding_check(self):
230 self._bounds_checking(lambda tup: time.strftime('', tup))
231
Steve Dowere5b58952015-09-06 19:20:51 -0700232 def test_strftime_format_check(self):
233 # Test that strftime does not crash on invalid format strings
234 # that may trigger a buffer overread. When not triggered,
235 # strftime may succeed or raise ValueError depending on
236 # the platform.
237 for x in [ '', 'A', '%A', '%AA' ]:
238 for y in range(0x0, 0x10):
239 for z in [ '%', 'A%', 'AA%', '%A%', 'A%A%', '%#' ]:
240 try:
241 time.strftime(x * y + z)
242 except ValueError:
243 pass
244
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000245 def test_default_values_for_zero(self):
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400246 # Make sure that using all zeros uses the proper default
247 # values. No test for daylight savings since strftime() does
248 # not change output based on its value and no test for year
249 # because systems vary in their support for year 0.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000250 expected = "2000 01 01 00 00 00 1 001"
Hai Shi3ddc6342020-06-30 21:46:06 +0800251 with warnings_helper.check_warnings():
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400252 result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000253 self.assertEqual(expected, result)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000254
Paul Monson9cd39b12019-07-18 06:56:59 -0700255 @skip_if_buggy_ucrt_strfptime
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000256 def test_strptime(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000257 # Should be able to go round-trip from strftime to strptime without
Andrew Svetlov737fb892012-12-18 21:14:22 +0200258 # raising an exception.
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000259 tt = time.gmtime(self.t)
260 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
261 'j', 'm', 'M', 'p', 'S',
262 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000263 format = '%' + directive
264 strf_output = time.strftime(format, tt)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000265 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000266 time.strptime(strf_output, format)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000267 except ValueError:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000268 self.fail("conversion specifier %r failed with '%s' input." %
269 (format, strf_output))
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000270
Brett Cannon7f6b4f82009-03-30 21:30:26 +0000271 def test_strptime_bytes(self):
272 # Make sure only strings are accepted as arguments to strptime.
273 self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
274 self.assertRaises(TypeError, time.strptime, '2009', b'%Y')
275
Ezio Melotti0f389082013-04-04 02:09:20 +0300276 def test_strptime_exception_context(self):
277 # check that this doesn't chain exceptions needlessly (see #17572)
278 with self.assertRaises(ValueError) as e:
279 time.strptime('', '%D')
280 self.assertIs(e.exception.__suppress_context__, True)
Serhiy Storchakacdac3022013-11-24 18:15:37 +0200281 # additional check for IndexError branch (issue #19545)
282 with self.assertRaises(ValueError) as e:
283 time.strptime('19', '%Y %')
284 self.assertIs(e.exception.__suppress_context__, True)
Ezio Melotti0f389082013-04-04 02:09:20 +0300285
Fred Drakebc561982001-05-22 17:02:02 +0000286 def test_asctime(self):
287 time.asctime(time.gmtime(self.t))
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000288
289 # Max year is only limited by the size of C int.
Florent Xiclunabceb5282011-11-01 14:11:34 +0100290 for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
291 asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
292 self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
293 self.assertRaises(OverflowError, time.asctime,
294 (TIME_MAXYEAR + 1,) + (0,) * 8)
295 self.assertRaises(OverflowError, time.asctime,
296 (TIME_MINYEAR - 1,) + (0,) * 8)
Fred Drakebc561982001-05-22 17:02:02 +0000297 self.assertRaises(TypeError, time.asctime, 0)
Alexander Belopolskye2dc0822011-01-02 20:48:22 +0000298 self.assertRaises(TypeError, time.asctime, ())
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000299 self.assertRaises(TypeError, time.asctime, (0,) * 10)
Fred Drakebc561982001-05-22 17:02:02 +0000300
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000301 def test_asctime_bounding_check(self):
302 self._bounds_checking(time.asctime)
303
Georg Brandle10608c2011-01-02 22:33:43 +0000304 def test_ctime(self):
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000305 t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
306 self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
307 t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
308 self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000')
Victor Stinner1ac42612014-02-21 09:27:17 +0100309 for year in [-100, 100, 1000, 2000, 2050, 10000]:
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000310 try:
311 testval = time.mktime((year, 1, 10) + (0,)*6)
312 except (ValueError, OverflowError):
313 # If mktime fails, ctime will fail too. This may happen
314 # on some platforms.
315 pass
316 else:
317 self.assertEqual(time.ctime(testval)[20:], str(year))
Georg Brandle10608c2011-01-02 22:33:43 +0000318
Florent Xiclunae54371e2011-11-11 18:59:30 +0100319 @unittest.skipUnless(hasattr(time, "tzset"),
320 "time module has no attribute tzset")
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000321 def test_tzset(self):
Guido van Rossumd2b738e2003-03-15 12:01:52 +0000322
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000323 from os import environ
324
Tim Peters0eadaac2003-04-24 16:02:54 +0000325 # Epoch time of midnight Dec 25th 2002. Never DST in northern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000326 # hemisphere.
Tim Peters0eadaac2003-04-24 16:02:54 +0000327 xmas2002 = 1040774400.0
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000328
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000329 # These formats are correct for 2002, and possibly future years
330 # This format is the 'standard' as documented at:
331 # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
332 # They are also documented in the tzset(3) man page on most Unix
333 # systems.
Tim Peters0eadaac2003-04-24 16:02:54 +0000334 eastern = 'EST+05EDT,M4.1.0,M10.5.0'
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000335 victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
336 utc='UTC+0'
337
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000338 org_TZ = environ.get('TZ',None)
339 try:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000340 # Make sure we can switch to UTC time and results are correct
341 # Note that unknown timezones default to UTC.
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000342 # Note that altzone is undefined in UTC, as there is no DST
343 environ['TZ'] = eastern
344 time.tzset()
345 environ['TZ'] = utc
346 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000347 self.assertEqual(
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000348 time.gmtime(xmas2002), time.localtime(xmas2002)
349 )
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000350 self.assertEqual(time.daylight, 0)
351 self.assertEqual(time.timezone, 0)
352 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000353
354 # Make sure we can switch to US/Eastern
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000355 environ['TZ'] = eastern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000356 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000357 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
358 self.assertEqual(time.tzname, ('EST', 'EDT'))
359 self.assertEqual(len(time.tzname), 2)
360 self.assertEqual(time.daylight, 1)
361 self.assertEqual(time.timezone, 18000)
362 self.assertEqual(time.altzone, 14400)
363 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
364 self.assertEqual(len(time.tzname), 2)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000365
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000366 # Now go to the southern hemisphere.
367 environ['TZ'] = victoria
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000368 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000369 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
Victor Stinner0cd47902011-12-08 00:32:51 +0100370
371 # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100372 # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
373 # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
374 # on some operating systems (e.g. FreeBSD), which is wrong. See for
375 # example this bug:
376 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
Victor Stinner0cd47902011-12-08 00:32:51 +0100377 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100378 self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000379 self.assertEqual(len(time.tzname), 2)
380 self.assertEqual(time.daylight, 1)
381 self.assertEqual(time.timezone, -36000)
382 self.assertEqual(time.altzone, -39600)
383 self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000384
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000385 finally:
386 # Repair TZ environment variable in case any other tests
387 # rely on it.
388 if org_TZ is not None:
389 environ['TZ'] = org_TZ
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000390 elif 'TZ' in environ:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000391 del environ['TZ']
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000392 time.tzset()
Tim Peters0eadaac2003-04-24 16:02:54 +0000393
Tim Peters1b6f7a92004-06-20 02:50:16 +0000394 def test_insane_timestamps(self):
395 # It's possible that some platform maps time_t to double,
396 # and that this test will fail there. This test should
397 # exempt such platforms (provided they return reasonable
398 # results!).
399 for func in time.ctime, time.gmtime, time.localtime:
400 for unreasonable in -1e200, 1e200:
Victor Stinner5d272cc2012-03-13 13:35:55 +0100401 self.assertRaises(OverflowError, func, unreasonable)
Fred Drakebc561982001-05-22 17:02:02 +0000402
Fred Drakef901abd2004-08-03 17:58:55 +0000403 def test_ctime_without_arg(self):
404 # Not sure how to check the values, since the clock could tick
405 # at any time. Make sure these are at least accepted and
406 # don't raise errors.
407 time.ctime()
408 time.ctime(None)
409
410 def test_gmtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000411 gt0 = time.gmtime()
412 gt1 = time.gmtime(None)
413 t0 = time.mktime(gt0)
414 t1 = time.mktime(gt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000415 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000416
417 def test_localtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000418 lt0 = time.localtime()
419 lt1 = time.localtime(None)
420 t0 = time.mktime(lt0)
421 t1 = time.mktime(lt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000422 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000423
Florent Xiclunae54371e2011-11-11 18:59:30 +0100424 def test_mktime(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100425 # Issue #1726687
426 for t in (-2, -1, 0, 1):
427 try:
428 tt = time.localtime(t)
Victor Stinner2cbae982012-01-27 00:50:33 +0100429 except (OverflowError, OSError):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100430 pass
431 else:
432 self.assertEqual(time.mktime(tt), t)
Florent Xiclunae54371e2011-11-11 18:59:30 +0100433
434 # Issue #13309: passing extreme values to mktime() or localtime()
435 # borks the glibc's internal timezone data.
436 @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
437 "disabled because of a bug in glibc. Issue #13309")
438 def test_mktime_error(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100439 # It may not be possible to reliably make mktime return error
440 # on all platfom. This will make sure that no other exception
441 # than OverflowError is raised for an extreme value.
Florent Xiclunae54371e2011-11-11 18:59:30 +0100442 tt = time.gmtime(self.t)
443 tzname = time.strftime('%Z', tt)
444 self.assertNotEqual(tzname, 'LMT')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100445 try:
446 time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
447 except OverflowError:
448 pass
Florent Xiclunae54371e2011-11-11 18:59:30 +0100449 self.assertEqual(time.strftime('%Z', tt), tzname)
Florent Xiclunabceb5282011-11-01 14:11:34 +0100450
Victor Stinnerec895392012-04-29 02:41:27 +0200451 def test_monotonic(self):
Victor Stinner6c861812013-11-23 00:15:27 +0100452 # monotonic() should not go backward
453 times = [time.monotonic() for n in range(100)]
454 t1 = times[0]
455 for t2 in times[1:]:
456 self.assertGreaterEqual(t2, t1, "times=%s" % times)
457 t1 = t2
458
459 # monotonic() includes time elapsed during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200460 t1 = time.monotonic()
Victor Stinnera9c99a62013-07-03 23:07:37 +0200461 time.sleep(0.5)
Victor Stinnerec895392012-04-29 02:41:27 +0200462 t2 = time.monotonic()
Victor Stinner2dd254d2012-01-20 02:24:18 +0100463 dt = t2 - t1
Victor Stinner8b302012012-02-07 23:29:46 +0100464 self.assertGreater(t2, t1)
Victor Stinnerd246a672019-04-24 00:15:12 +0200465 # bpo-20101: tolerate a difference of 50 ms because of bad timer
466 # resolution on Windows
467 self.assertTrue(0.450 <= dt)
Antoine Pitrou391166f2012-01-18 22:35:21 +0100468
Victor Stinner6c861812013-11-23 00:15:27 +0100469 # monotonic() is a monotonic but non adjustable clock
Victor Stinnerec895392012-04-29 02:41:27 +0200470 info = time.get_clock_info('monotonic')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400471 self.assertTrue(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +0200472 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200473
474 def test_perf_counter(self):
475 time.perf_counter()
476
477 def test_process_time(self):
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200478 # process_time() should not include time spend during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200479 start = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200480 time.sleep(0.100)
Victor Stinnerec895392012-04-29 02:41:27 +0200481 stop = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200482 # use 20 ms because process_time() has usually a resolution of 15 ms
483 # on Windows
484 self.assertLess(stop - start, 0.020)
Victor Stinnerec895392012-04-29 02:41:27 +0200485
486 info = time.get_clock_info('process_time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400487 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200488 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200489
Antoine Pitrou4bd41c92017-11-15 22:52:21 +0100490 def test_thread_time(self):
491 if not hasattr(time, 'thread_time'):
492 if sys.platform.startswith(('linux', 'win')):
493 self.fail("time.thread_time() should be available on %r"
494 % (sys.platform,))
495 else:
496 self.skipTest("need time.thread_time")
497
498 # thread_time() should not include time spend during a sleep
499 start = time.thread_time()
500 time.sleep(0.100)
501 stop = time.thread_time()
502 # use 20 ms because thread_time() has usually a resolution of 15 ms
503 # on Windows
504 self.assertLess(stop - start, 0.020)
505
Antoine Pitrou4bd41c92017-11-15 22:52:21 +0100506 info = time.get_clock_info('thread_time')
507 self.assertTrue(info.monotonic)
508 self.assertFalse(info.adjustable)
509
Victor Stinnerec895392012-04-29 02:41:27 +0200510 @unittest.skipUnless(hasattr(time, 'clock_settime'),
511 'need time.clock_settime')
512 def test_monotonic_settime(self):
513 t1 = time.monotonic()
514 realtime = time.clock_gettime(time.CLOCK_REALTIME)
515 # jump backward with an offset of 1 hour
Victor Stinner071eca32012-03-15 01:17:09 +0100516 try:
Victor Stinnerec895392012-04-29 02:41:27 +0200517 time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
518 except PermissionError as err:
519 self.skipTest(err)
520 t2 = time.monotonic()
521 time.clock_settime(time.CLOCK_REALTIME, realtime)
522 # monotonic must not be affected by system clock updates
Victor Stinner071eca32012-03-15 01:17:09 +0100523 self.assertGreaterEqual(t2, t1)
524
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100525 def test_localtime_failure(self):
526 # Issue #13847: check for localtime() failure
Victor Stinner53d36452012-01-27 01:03:25 +0100527 invalid_time_t = None
528 for time_t in (-1, 2**30, 2**33, 2**60):
529 try:
530 time.localtime(time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100531 except OverflowError:
532 self.skipTest("need 64-bit time_t")
Victor Stinner53d36452012-01-27 01:03:25 +0100533 except OSError:
534 invalid_time_t = time_t
535 break
536 if invalid_time_t is None:
537 self.skipTest("unable to find an invalid time_t value")
538
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100539 self.assertRaises(OSError, time.localtime, invalid_time_t)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100540 self.assertRaises(OSError, time.ctime, invalid_time_t)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100541
Han Lee829dacc2017-09-09 08:05:05 +0900542 # Issue #26669: check for localtime() failure
543 self.assertRaises(ValueError, time.localtime, float("nan"))
544 self.assertRaises(ValueError, time.ctime, float("nan"))
545
Victor Stinnerec895392012-04-29 02:41:27 +0200546 def test_get_clock_info(self):
pxinwrf1464f42019-04-15 17:06:21 +0800547 clocks = ['monotonic', 'perf_counter', 'process_time', 'time']
Victor Stinnerec895392012-04-29 02:41:27 +0200548
549 for name in clocks:
Matthias Bussonniere2500612019-05-12 18:34:44 -0700550 info = time.get_clock_info(name)
Victor Stinner884d13a2017-10-17 14:46:45 -0700551
Victor Stinnerec895392012-04-29 02:41:27 +0200552 #self.assertIsInstance(info, dict)
553 self.assertIsInstance(info.implementation, str)
554 self.assertNotEqual(info.implementation, '')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400555 self.assertIsInstance(info.monotonic, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200556 self.assertIsInstance(info.resolution, float)
557 # 0.0 < resolution <= 1.0
558 self.assertGreater(info.resolution, 0.0)
559 self.assertLessEqual(info.resolution, 1.0)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200560 self.assertIsInstance(info.adjustable, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200561
562 self.assertRaises(ValueError, time.get_clock_info, 'xxx')
563
564
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000565class TestLocale(unittest.TestCase):
566 def setUp(self):
567 self.oldloc = locale.setlocale(locale.LC_ALL)
Fred Drake2e2be372001-09-20 21:33:42 +0000568
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000569 def tearDown(self):
570 locale.setlocale(locale.LC_ALL, self.oldloc)
571
Martin v. Löwisa6a9c4d2009-05-30 06:15:30 +0000572 def test_bug_3061(self):
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000573 try:
574 tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
575 except locale.Error:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600576 self.skipTest('could not set locale.LC_ALL to fr_FR')
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000577 # This should not cause an exception
578 time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
579
Victor Stinner73ea29c2011-01-08 01:56:31 +0000580
Victor Stinner73ea29c2011-01-08 01:56:31 +0000581class _TestAsctimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100582 _format = '%d'
583
Victor Stinner73ea29c2011-01-08 01:56:31 +0000584 def yearstr(self, y):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000585 return time.asctime((y,) + (0,) * 8).split()[-1]
Alexander Belopolskya6867252011-01-05 23:00:47 +0000586
Victor Stinner73ea29c2011-01-08 01:56:31 +0000587 def test_large_year(self):
Victor Stinner73691322011-01-08 02:00:24 +0000588 # Check that it doesn't crash for year > 9999
Victor Stinner73ea29c2011-01-08 01:56:31 +0000589 self.assertEqual(self.yearstr(12345), '12345')
590 self.assertEqual(self.yearstr(123456789), '123456789')
591
592class _TestStrftimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100593
594 # Issue 13305: For years < 1000, the value is not always
595 # padded to 4 digits across platforms. The C standard
596 # assumes year >= 1900, so it does not specify the number
597 # of digits.
598
599 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
600 _format = '%04d'
601 else:
602 _format = '%d'
603
Victor Stinner73ea29c2011-01-08 01:56:31 +0000604 def yearstr(self, y):
Florent Xicluna49ce0682011-11-01 12:56:14 +0100605 return time.strftime('%Y', (y,) + (0,) * 8)
606
607 def test_4dyear(self):
608 # Check that we can return the zero padded value.
609 if self._format == '%04d':
610 self.test_year('%04d')
611 else:
612 def year4d(y):
613 return time.strftime('%4Y', (y,) + (0,) * 8)
614 self.test_year('%04d', func=year4d)
615
Florent Xiclunabceb5282011-11-01 14:11:34 +0100616 def skip_if_not_supported(y):
617 msg = "strftime() is limited to [1; 9999] with Visual Studio"
618 # Check that it doesn't crash for year > 9999
619 try:
620 time.strftime('%Y', (y,) + (0,) * 8)
621 except ValueError:
622 cond = False
623 else:
624 cond = True
625 return unittest.skipUnless(cond, msg)
626
627 @skip_if_not_supported(10000)
628 def test_large_year(self):
629 return super().test_large_year()
630
631 @skip_if_not_supported(0)
632 def test_negative(self):
633 return super().test_negative()
634
635 del skip_if_not_supported
636
637
Ezio Melotti3836d702013-04-11 20:29:42 +0300638class _Test4dYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100639 _format = '%d'
640
641 def test_year(self, fmt=None, func=None):
642 fmt = fmt or self._format
643 func = func or self.yearstr
644 self.assertEqual(func(1), fmt % 1)
645 self.assertEqual(func(68), fmt % 68)
646 self.assertEqual(func(69), fmt % 69)
647 self.assertEqual(func(99), fmt % 99)
648 self.assertEqual(func(999), fmt % 999)
649 self.assertEqual(func(9999), fmt % 9999)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000650
651 def test_large_year(self):
Benjamin Petersone1a34ce2018-09-12 16:21:36 -0700652 self.assertEqual(self.yearstr(12345).lstrip('+'), '12345')
653 self.assertEqual(self.yearstr(123456789).lstrip('+'), '123456789')
654 self.assertEqual(self.yearstr(TIME_MAXYEAR).lstrip('+'), str(TIME_MAXYEAR))
Florent Xiclunabceb5282011-11-01 14:11:34 +0100655 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000656
Victor Stinner301f1212011-01-08 03:06:52 +0000657 def test_negative(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100658 self.assertEqual(self.yearstr(-1), self._format % -1)
Victor Stinner301f1212011-01-08 03:06:52 +0000659 self.assertEqual(self.yearstr(-1234), '-1234')
660 self.assertEqual(self.yearstr(-123456), '-123456')
Florent Xiclunad1bd7f72011-11-01 23:42:05 +0100661 self.assertEqual(self.yearstr(-123456789), str(-123456789))
662 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
Gregory P. Smith76be0ff2018-08-24 18:08:50 -0700663 self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
664 # Modules/timemodule.c checks for underflow
Florent Xiclunabceb5282011-11-01 14:11:34 +0100665 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
Gregory P. Smith76be0ff2018-08-24 18:08:50 -0700666 with self.assertRaises(OverflowError):
667 self.yearstr(-TIME_MAXYEAR - 1)
Victor Stinner301f1212011-01-08 03:06:52 +0000668
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000669
Ezio Melotti3836d702013-04-11 20:29:42 +0300670class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner73ea29c2011-01-08 01:56:31 +0000671 pass
672
Ezio Melotti3836d702013-04-11 20:29:42 +0300673class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner301f1212011-01-08 03:06:52 +0000674 pass
Victor Stinner73ea29c2011-01-08 01:56:31 +0000675
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000676
Victor Stinner643cd682012-03-02 22:54:03 +0100677class TestPytime(unittest.TestCase):
Paul Monson9cd39b12019-07-18 06:56:59 -0700678 @skip_if_buggy_ucrt_strfptime
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400679 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
680 def test_localtime_timezone(self):
Victor Stinner643cd682012-03-02 22:54:03 +0100681
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400682 # Get the localtime and examine it for the offset and zone.
683 lt = time.localtime()
684 self.assertTrue(hasattr(lt, "tm_gmtoff"))
685 self.assertTrue(hasattr(lt, "tm_zone"))
686
687 # See if the offset and zone are similar to the module
688 # attributes.
689 if lt.tm_gmtoff is None:
690 self.assertTrue(not hasattr(time, "timezone"))
691 else:
692 self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
693 if lt.tm_zone is None:
694 self.assertTrue(not hasattr(time, "tzname"))
695 else:
696 self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
697
698 # Try and make UNIX times from the localtime and a 9-tuple
699 # created from the localtime. Test to see that the times are
700 # the same.
701 t = time.mktime(lt); t9 = time.mktime(lt[:9])
702 self.assertEqual(t, t9)
703
704 # Make localtimes from the UNIX times and compare them to
705 # the original localtime, thus making a round trip.
706 new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
707 self.assertEqual(new_lt, lt)
708 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
709 self.assertEqual(new_lt.tm_zone, lt.tm_zone)
710 self.assertEqual(new_lt9, lt)
711 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
712 self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
713
714 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
715 def test_strptime_timezone(self):
716 t = time.strptime("UTC", "%Z")
717 self.assertEqual(t.tm_zone, 'UTC')
718 t = time.strptime("+0500", "%z")
719 self.assertEqual(t.tm_gmtoff, 5 * 3600)
720
721 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
722 def test_short_times(self):
723
724 import pickle
725
726 # Load a short time structure using pickle.
727 st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
728 lt = pickle.loads(st)
729 self.assertIs(lt.tm_gmtoff, None)
730 self.assertIs(lt.tm_zone, None)
Victor Stinner643cd682012-03-02 22:54:03 +0100731
Fred Drake2e2be372001-09-20 21:33:42 +0000732
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200733@unittest.skipIf(_testcapi is None, 'need the _testcapi module')
734class CPyTimeTestCase:
Victor Stinneracea9f62015-09-02 10:39:40 +0200735 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200736 Base class to test the C _PyTime_t API.
Victor Stinneracea9f62015-09-02 10:39:40 +0200737 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200738 OVERFLOW_SECONDS = None
739
Victor Stinner4237d342015-09-10 10:10:39 +0200740 def setUp(self):
741 from _testcapi import SIZEOF_TIME_T
742 bits = SIZEOF_TIME_T * 8 - 1
743 self.time_t_min = -2 ** bits
744 self.time_t_max = 2 ** bits - 1
745
746 def time_t_filter(self, seconds):
747 return (self.time_t_min <= seconds <= self.time_t_max)
748
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200749 def _rounding_values(self, use_float):
750 "Build timestamps used to test rounding."
751
752 units = [1, US_TO_NS, MS_TO_NS, SEC_TO_NS]
753 if use_float:
754 # picoseconds are only tested to pytime_converter accepting floats
755 units.append(1e-3)
756
757 values = (
758 # small values
759 1, 2, 5, 7, 123, 456, 1234,
760 # 10^k - 1
761 9,
762 99,
763 999,
764 9999,
765 99999,
766 999999,
767 # test half even rounding near 0.5, 1.5, 2.5, 3.5, 4.5
768 499, 500, 501,
769 1499, 1500, 1501,
770 2500,
771 3500,
772 4500,
773 )
774
775 ns_timestamps = [0]
776 for unit in units:
777 for value in values:
778 ns = value * unit
779 ns_timestamps.extend((-ns, ns))
780 for pow2 in (0, 5, 10, 15, 22, 23, 24, 30, 33):
781 ns = (2 ** pow2) * SEC_TO_NS
782 ns_timestamps.extend((
783 -ns-1, -ns, -ns+1,
784 ns-1, ns, ns+1
785 ))
786 for seconds in (_testcapi.INT_MIN, _testcapi.INT_MAX):
787 ns_timestamps.append(seconds * SEC_TO_NS)
788 if use_float:
Victor Stinner717a32b2016-08-17 11:07:21 +0200789 # numbers with an exact representation in IEEE 754 (base 2)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200790 for pow2 in (3, 7, 10, 15):
791 ns = 2.0 ** (-pow2)
792 ns_timestamps.extend((-ns, ns))
793
794 # seconds close to _PyTime_t type limit
795 ns = (2 ** 63 // SEC_TO_NS) * SEC_TO_NS
796 ns_timestamps.extend((-ns, ns))
797
798 return ns_timestamps
799
800 def _check_rounding(self, pytime_converter, expected_func,
801 use_float, unit_to_sec, value_filter=None):
802
803 def convert_values(ns_timestamps):
804 if use_float:
805 unit_to_ns = SEC_TO_NS / float(unit_to_sec)
806 values = [ns / unit_to_ns for ns in ns_timestamps]
807 else:
808 unit_to_ns = SEC_TO_NS // unit_to_sec
809 values = [ns // unit_to_ns for ns in ns_timestamps]
810
811 if value_filter:
812 values = filter(value_filter, values)
813
814 # remove duplicates and sort
815 return sorted(set(values))
816
817 # test rounding
818 ns_timestamps = self._rounding_values(use_float)
819 valid_values = convert_values(ns_timestamps)
820 for time_rnd, decimal_rnd in ROUNDING_MODES :
Bo Bayles938045f2018-07-21 12:54:14 -0500821 with decimal.localcontext() as context:
822 context.rounding = decimal_rnd
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200823
Bo Bayles938045f2018-07-21 12:54:14 -0500824 for value in valid_values:
825 debug_info = {'value': value, 'rounding': decimal_rnd}
826 try:
827 result = pytime_converter(value, time_rnd)
828 expected = expected_func(value)
Pablo Galindo293dd232019-11-19 21:34:03 +0000829 except Exception:
Bo Bayles938045f2018-07-21 12:54:14 -0500830 self.fail("Error on timestamp conversion: %s" % debug_info)
831 self.assertEqual(result,
832 expected,
833 debug_info)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200834
835 # test overflow
836 ns = self.OVERFLOW_SECONDS * SEC_TO_NS
837 ns_timestamps = (-ns, ns)
838 overflow_values = convert_values(ns_timestamps)
839 for time_rnd, _ in ROUNDING_MODES :
840 for value in overflow_values:
Victor Stinnerc60542b2015-09-10 15:55:07 +0200841 debug_info = {'value': value, 'rounding': time_rnd}
842 with self.assertRaises(OverflowError, msg=debug_info):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200843 pytime_converter(value, time_rnd)
844
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200845 def check_int_rounding(self, pytime_converter, expected_func,
846 unit_to_sec=1, value_filter=None):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200847 self._check_rounding(pytime_converter, expected_func,
848 False, unit_to_sec, value_filter)
849
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200850 def check_float_rounding(self, pytime_converter, expected_func,
851 unit_to_sec=1, value_filter=None):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200852 self._check_rounding(pytime_converter, expected_func,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200853 True, unit_to_sec, value_filter)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200854
855 def decimal_round(self, x):
856 d = decimal.Decimal(x)
857 d = d.quantize(1)
858 return int(d)
859
860
861class TestCPyTime(CPyTimeTestCase, unittest.TestCase):
862 """
863 Test the C _PyTime_t API.
864 """
865 # _PyTime_t is a 64-bit signed integer
866 OVERFLOW_SECONDS = math.ceil((2**63 + 1) / SEC_TO_NS)
867
Victor Stinner13019fd2015-04-03 13:10:54 +0200868 def test_FromSeconds(self):
869 from _testcapi import PyTime_FromSeconds
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200870
871 # PyTime_FromSeconds() expects a C int, reject values out of range
872 def c_int_filter(secs):
873 return (_testcapi.INT_MIN <= secs <= _testcapi.INT_MAX)
874
875 self.check_int_rounding(lambda secs, rnd: PyTime_FromSeconds(secs),
876 lambda secs: secs * SEC_TO_NS,
877 value_filter=c_int_filter)
Victor Stinner13019fd2015-04-03 13:10:54 +0200878
Han Lee829dacc2017-09-09 08:05:05 +0900879 # test nan
880 for time_rnd, _ in ROUNDING_MODES:
881 with self.assertRaises(TypeError):
882 PyTime_FromSeconds(float('nan'))
883
Victor Stinner992c43f2015-03-27 17:12:45 +0100884 def test_FromSecondsObject(self):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100885 from _testcapi import PyTime_FromSecondsObject
Victor Stinner992c43f2015-03-27 17:12:45 +0100886
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200887 self.check_int_rounding(
888 PyTime_FromSecondsObject,
889 lambda secs: secs * SEC_TO_NS)
Victor Stinner992c43f2015-03-27 17:12:45 +0100890
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200891 self.check_float_rounding(
892 PyTime_FromSecondsObject,
893 lambda ns: self.decimal_round(ns * SEC_TO_NS))
Victor Stinner4bfb4602015-03-27 22:27:24 +0100894
Han Lee829dacc2017-09-09 08:05:05 +0900895 # test nan
896 for time_rnd, _ in ROUNDING_MODES:
897 with self.assertRaises(ValueError):
898 PyTime_FromSecondsObject(float('nan'), time_rnd)
899
Victor Stinner4bfb4602015-03-27 22:27:24 +0100900 def test_AsSecondsDouble(self):
901 from _testcapi import PyTime_AsSecondsDouble
902
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200903 def float_converter(ns):
904 if abs(ns) % SEC_TO_NS == 0:
905 return float(ns // SEC_TO_NS)
906 else:
907 return float(ns) / SEC_TO_NS
Victor Stinner4bfb4602015-03-27 22:27:24 +0100908
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200909 self.check_int_rounding(lambda ns, rnd: PyTime_AsSecondsDouble(ns),
910 float_converter,
911 NS_TO_SEC)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100912
Han Lee829dacc2017-09-09 08:05:05 +0900913 # test nan
914 for time_rnd, _ in ROUNDING_MODES:
915 with self.assertRaises(TypeError):
916 PyTime_AsSecondsDouble(float('nan'))
917
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200918 def create_decimal_converter(self, denominator):
919 denom = decimal.Decimal(denominator)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100920
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200921 def converter(value):
922 d = decimal.Decimal(value) / denom
923 return self.decimal_round(d)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100924
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200925 return converter
Victor Stinner4bfb4602015-03-27 22:27:24 +0100926
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200927 def test_AsTimeval(self):
Victor Stinner95e9cef2015-03-28 01:26:47 +0100928 from _testcapi import PyTime_AsTimeval
Victor Stinner95e9cef2015-03-28 01:26:47 +0100929
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200930 us_converter = self.create_decimal_converter(US_TO_NS)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100931
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200932 def timeval_converter(ns):
933 us = us_converter(ns)
934 return divmod(us, SEC_TO_US)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100935
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200936 if sys.platform == 'win32':
937 from _testcapi import LONG_MIN, LONG_MAX
938
939 # On Windows, timeval.tv_sec type is a C long
940 def seconds_filter(secs):
941 return LONG_MIN <= secs <= LONG_MAX
942 else:
Victor Stinner4237d342015-09-10 10:10:39 +0200943 seconds_filter = self.time_t_filter
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200944
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200945 self.check_int_rounding(PyTime_AsTimeval,
946 timeval_converter,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200947 NS_TO_SEC,
948 value_filter=seconds_filter)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100949
Victor Stinner34dc0f42015-03-27 18:19:03 +0100950 @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec'),
951 'need _testcapi.PyTime_AsTimespec')
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200952 def test_AsTimespec(self):
Victor Stinner34dc0f42015-03-27 18:19:03 +0100953 from _testcapi import PyTime_AsTimespec
Victor Stinner34dc0f42015-03-27 18:19:03 +0100954
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200955 def timespec_converter(ns):
956 return divmod(ns, SEC_TO_NS)
Victor Stinner34dc0f42015-03-27 18:19:03 +0100957
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200958 self.check_int_rounding(lambda ns, rnd: PyTime_AsTimespec(ns),
959 timespec_converter,
Victor Stinner4237d342015-09-10 10:10:39 +0200960 NS_TO_SEC,
961 value_filter=self.time_t_filter)
Victor Stinner34dc0f42015-03-27 18:19:03 +0100962
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200963 def test_AsMilliseconds(self):
Victor Stinner62d1c702015-04-01 17:47:07 +0200964 from _testcapi import PyTime_AsMilliseconds
Victor Stinner62d1c702015-04-01 17:47:07 +0200965
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200966 self.check_int_rounding(PyTime_AsMilliseconds,
967 self.create_decimal_converter(MS_TO_NS),
968 NS_TO_SEC)
Victor Stinner62d1c702015-04-01 17:47:07 +0200969
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200970 def test_AsMicroseconds(self):
Victor Stinner62d1c702015-04-01 17:47:07 +0200971 from _testcapi import PyTime_AsMicroseconds
Victor Stinner62d1c702015-04-01 17:47:07 +0200972
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200973 self.check_int_rounding(PyTime_AsMicroseconds,
974 self.create_decimal_converter(US_TO_NS),
975 NS_TO_SEC)
Victor Stinner62d1c702015-04-01 17:47:07 +0200976
Victor Stinner992c43f2015-03-27 17:12:45 +0100977
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200978class TestOldPyTime(CPyTimeTestCase, unittest.TestCase):
Victor Stinneracea9f62015-09-02 10:39:40 +0200979 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200980 Test the old C _PyTime_t API: _PyTime_ObjectToXXX() functions.
Victor Stinneracea9f62015-09-02 10:39:40 +0200981 """
Victor Stinneracea9f62015-09-02 10:39:40 +0200982
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200983 # time_t is a 32-bit or 64-bit signed integer
984 OVERFLOW_SECONDS = 2 ** 64
985
986 def test_object_to_time_t(self):
Victor Stinneracea9f62015-09-02 10:39:40 +0200987 from _testcapi import pytime_object_to_time_t
988
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200989 self.check_int_rounding(pytime_object_to_time_t,
Victor Stinner4237d342015-09-10 10:10:39 +0200990 lambda secs: secs,
991 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200992
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200993 self.check_float_rounding(pytime_object_to_time_t,
Victor Stinner350b5182015-09-10 11:45:06 +0200994 self.decimal_round,
995 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200996
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200997 def create_converter(self, sec_to_unit):
998 def converter(secs):
999 floatpart, intpart = math.modf(secs)
1000 intpart = int(intpart)
1001 floatpart *= sec_to_unit
1002 floatpart = self.decimal_round(floatpart)
1003 if floatpart < 0:
1004 floatpart += sec_to_unit
1005 intpart -= 1
1006 elif floatpart >= sec_to_unit:
1007 floatpart -= sec_to_unit
1008 intpart += 1
1009 return (intpart, floatpart)
1010 return converter
Victor Stinneracea9f62015-09-02 10:39:40 +02001011
Victor Stinneradfefa52015-09-04 23:57:25 +02001012 def test_object_to_timeval(self):
Victor Stinneracea9f62015-09-02 10:39:40 +02001013 from _testcapi import pytime_object_to_timeval
1014
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001015 self.check_int_rounding(pytime_object_to_timeval,
Victor Stinner4237d342015-09-10 10:10:39 +02001016 lambda secs: (secs, 0),
1017 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001018
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001019 self.check_float_rounding(pytime_object_to_timeval,
Victor Stinner350b5182015-09-10 11:45:06 +02001020 self.create_converter(SEC_TO_US),
1021 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001022
Han Lee829dacc2017-09-09 08:05:05 +09001023 # test nan
1024 for time_rnd, _ in ROUNDING_MODES:
1025 with self.assertRaises(ValueError):
1026 pytime_object_to_timeval(float('nan'), time_rnd)
1027
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001028 def test_object_to_timespec(self):
Victor Stinneracea9f62015-09-02 10:39:40 +02001029 from _testcapi import pytime_object_to_timespec
1030
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001031 self.check_int_rounding(pytime_object_to_timespec,
Victor Stinner4237d342015-09-10 10:10:39 +02001032 lambda secs: (secs, 0),
1033 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001034
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001035 self.check_float_rounding(pytime_object_to_timespec,
Victor Stinner350b5182015-09-10 11:45:06 +02001036 self.create_converter(SEC_TO_NS),
1037 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001038
Han Lee829dacc2017-09-09 08:05:05 +09001039 # test nan
1040 for time_rnd, _ in ROUNDING_MODES:
1041 with self.assertRaises(ValueError):
1042 pytime_object_to_timespec(float('nan'), time_rnd)
1043
Victor Stinneracea9f62015-09-02 10:39:40 +02001044
Fred Drake2e2be372001-09-20 21:33:42 +00001045if __name__ == "__main__":
Ezio Melotti3836d702013-04-11 20:29:42 +03001046 unittest.main()