blob: 42799b2a21ca34dc41dd1d0e6a1bfd8d1d970577 [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
Barry Warsawb0c22321996-12-06 23:30:07 +000017
Florent Xiclunabceb5282011-11-01 14:11:34 +010018# Max year is only limited by the size of C int.
19SIZEOF_INT = sysconfig.get_config_var('SIZEOF_INT') or 4
20TIME_MAXYEAR = (1 << 8 * SIZEOF_INT - 1) - 1
Gregory P. Smith76be0ff2018-08-24 18:08:50 -070021TIME_MINYEAR = -TIME_MAXYEAR - 1 + 1900
Victor Stinner992c43f2015-03-27 17:12:45 +010022
Victor Stinner3e2c8d82015-09-09 22:32:48 +020023SEC_TO_US = 10 ** 6
Victor Stinner62d1c702015-04-01 17:47:07 +020024US_TO_NS = 10 ** 3
25MS_TO_NS = 10 ** 6
Victor Stinner4bfb4602015-03-27 22:27:24 +010026SEC_TO_NS = 10 ** 9
Victor Stinner3e2c8d82015-09-09 22:32:48 +020027NS_TO_SEC = 10 ** 9
Victor Stinner992c43f2015-03-27 17:12:45 +010028
29class _PyTime(enum.IntEnum):
Victor Stinnerbcdd7772015-03-30 03:52:49 +020030 # Round towards minus infinity (-inf)
Victor Stinnera695f832015-03-30 03:57:14 +020031 ROUND_FLOOR = 0
Victor Stinnerbcdd7772015-03-30 03:52:49 +020032 # Round towards infinity (+inf)
Victor Stinnera695f832015-03-30 03:57:14 +020033 ROUND_CEILING = 1
Victor Stinner7667f582015-09-09 01:02:23 +020034 # Round to nearest with ties going to nearest even integer
35 ROUND_HALF_EVEN = 2
Pablo Galindo2c15b292017-10-17 15:14:41 +010036 # Round away from zero
37 ROUND_UP = 3
Victor Stinner992c43f2015-03-27 17:12:45 +010038
Victor Stinner3e2c8d82015-09-09 22:32:48 +020039# Rounding modes supported by PyTime
40ROUNDING_MODES = (
41 # (PyTime rounding method, decimal rounding method)
42 (_PyTime.ROUND_FLOOR, decimal.ROUND_FLOOR),
43 (_PyTime.ROUND_CEILING, decimal.ROUND_CEILING),
44 (_PyTime.ROUND_HALF_EVEN, decimal.ROUND_HALF_EVEN),
Pablo Galindo2c15b292017-10-17 15:14:41 +010045 (_PyTime.ROUND_UP, decimal.ROUND_UP),
Victor Stinner3e2c8d82015-09-09 22:32:48 +020046)
Florent Xiclunabceb5282011-11-01 14:11:34 +010047
48
Fred Drakebc561982001-05-22 17:02:02 +000049class TimeTestCase(unittest.TestCase):
Barry Warsawb0c22321996-12-06 23:30:07 +000050
Fred Drakebc561982001-05-22 17:02:02 +000051 def setUp(self):
52 self.t = time.time()
Barry Warsawb0c22321996-12-06 23:30:07 +000053
Fred Drakebc561982001-05-22 17:02:02 +000054 def test_data_attributes(self):
55 time.altzone
56 time.daylight
57 time.timezone
58 time.tzname
Barry Warsawb0c22321996-12-06 23:30:07 +000059
Victor Stinnerec895392012-04-29 02:41:27 +020060 def test_time(self):
61 time.time()
62 info = time.get_clock_info('time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040063 self.assertFalse(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +020064 self.assertTrue(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020065
Victor Stinnerc29b5852017-11-02 07:28:27 -070066 def test_time_ns_type(self):
67 def check_ns(sec, ns):
68 self.assertIsInstance(ns, int)
69
70 sec_ns = int(sec * 1e9)
71 # tolerate a difference of 50 ms
72 self.assertLess((sec_ns - ns), 50 ** 6, (sec, ns))
73
74 check_ns(time.time(),
75 time.time_ns())
76 check_ns(time.monotonic(),
77 time.monotonic_ns())
78 check_ns(time.perf_counter(),
79 time.perf_counter_ns())
80 check_ns(time.process_time(),
81 time.process_time_ns())
82
Antoine Pitrou4bd41c92017-11-15 22:52:21 +010083 if hasattr(time, 'thread_time'):
84 check_ns(time.thread_time(),
85 time.thread_time_ns())
86
Victor Stinnerc29b5852017-11-02 07:28:27 -070087 if hasattr(time, 'clock_gettime'):
88 check_ns(time.clock_gettime(time.CLOCK_REALTIME),
89 time.clock_gettime_ns(time.CLOCK_REALTIME))
90
pxinwrf1464f42019-04-15 17:06:21 +080091 @unittest.skipUnless(hasattr(time, 'clock'),
92 'need time.clock()')
Fred Drakebc561982001-05-22 17:02:02 +000093 def test_clock(self):
Victor Stinner884d13a2017-10-17 14:46:45 -070094 with self.assertWarns(DeprecationWarning):
95 time.clock()
Barry Warsawb0c22321996-12-06 23:30:07 +000096
Victor Stinner884d13a2017-10-17 14:46:45 -070097 with self.assertWarns(DeprecationWarning):
98 info = time.get_clock_info('clock')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040099 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200100 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200101
Victor Stinnere0be4232011-10-25 13:06:09 +0200102 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
103 'need time.clock_gettime()')
104 def test_clock_realtime(self):
Victor Stinnerc29b5852017-11-02 07:28:27 -0700105 t = time.clock_gettime(time.CLOCK_REALTIME)
106 self.assertIsInstance(t, float)
Victor Stinnere0be4232011-10-25 13:06:09 +0200107
108 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
109 'need time.clock_gettime()')
110 @unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'),
111 'need time.CLOCK_MONOTONIC')
112 def test_clock_monotonic(self):
113 a = time.clock_gettime(time.CLOCK_MONOTONIC)
114 b = time.clock_gettime(time.CLOCK_MONOTONIC)
115 self.assertLessEqual(a, b)
116
pdoxe14679c2017-10-05 00:01:56 -0700117 @unittest.skipUnless(hasattr(time, 'pthread_getcpuclockid'),
118 'need time.pthread_getcpuclockid()')
119 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
120 'need time.clock_gettime()')
pdoxe14679c2017-10-05 00:01:56 -0700121 def test_pthread_getcpuclockid(self):
122 clk_id = time.pthread_getcpuclockid(threading.get_ident())
123 self.assertTrue(type(clk_id) is int)
Michael Felte2926b72018-12-28 14:57:37 +0100124 # when in 32-bit mode AIX only returns the predefined constant
125 if not platform.system() == "AIX":
126 self.assertNotEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
127 elif (sys.maxsize.bit_length() > 32):
128 self.assertNotEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
129 else:
130 self.assertEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
pdoxe14679c2017-10-05 00:01:56 -0700131 t1 = time.clock_gettime(clk_id)
Benjamin Peterson86566702017-10-05 22:50:42 -0700132 t2 = time.clock_gettime(clk_id)
pdoxe14679c2017-10-05 00:01:56 -0700133 self.assertLessEqual(t1, t2)
pdoxe14679c2017-10-05 00:01:56 -0700134
Victor Stinnere0be4232011-10-25 13:06:09 +0200135 @unittest.skipUnless(hasattr(time, 'clock_getres'),
136 'need time.clock_getres()')
137 def test_clock_getres(self):
138 res = time.clock_getres(time.CLOCK_REALTIME)
139 self.assertGreater(res, 0.0)
140 self.assertLessEqual(res, 1.0)
141
Victor Stinner30d79472012-04-03 00:45:07 +0200142 @unittest.skipUnless(hasattr(time, 'clock_settime'),
143 'need time.clock_settime()')
144 def test_clock_settime(self):
145 t = time.clock_gettime(time.CLOCK_REALTIME)
146 try:
147 time.clock_settime(time.CLOCK_REALTIME, t)
148 except PermissionError:
149 pass
150
Victor Stinnerec895392012-04-29 02:41:27 +0200151 if hasattr(time, 'CLOCK_MONOTONIC'):
152 self.assertRaises(OSError,
153 time.clock_settime, time.CLOCK_MONOTONIC, 0)
Victor Stinner30d79472012-04-03 00:45:07 +0200154
Fred Drakebc561982001-05-22 17:02:02 +0000155 def test_conversions(self):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000156 self.assertEqual(time.ctime(self.t),
157 time.asctime(time.localtime(self.t)))
158 self.assertEqual(int(time.mktime(time.localtime(self.t))),
159 int(self.t))
Fred Drakebc561982001-05-22 17:02:02 +0000160
161 def test_sleep(self):
Victor Stinner7f53a502011-07-05 22:00:25 +0200162 self.assertRaises(ValueError, time.sleep, -2)
163 self.assertRaises(ValueError, time.sleep, -1)
Fred Drakebc561982001-05-22 17:02:02 +0000164 time.sleep(1.2)
165
166 def test_strftime(self):
167 tt = time.gmtime(self.t)
168 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
169 'j', 'm', 'M', 'p', 'S',
170 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
171 format = ' %' + directive
172 try:
173 time.strftime(format, tt)
174 except ValueError:
175 self.fail('conversion specifier: %r failed.' % format)
176
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300177 self.assertRaises(TypeError, time.strftime, b'%S', tt)
178 # embedded null character
179 self.assertRaises(ValueError, time.strftime, '%S\0', tt)
180
Florent Xicluna49ce0682011-11-01 12:56:14 +0100181 def _bounds_checking(self, func):
Brett Cannond1080a32004-03-02 04:38:10 +0000182 # Make sure that strftime() checks the bounds of the various parts
Florent Xicluna49ce0682011-11-01 12:56:14 +0100183 # of the time tuple (0 is valid for *all* values).
Brett Cannond1080a32004-03-02 04:38:10 +0000184
Victor Stinner73ea29c2011-01-08 01:56:31 +0000185 # The year field is tested by other test cases above
186
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000187 # Check month [1, 12] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100188 func((1900, 0, 1, 0, 0, 0, 0, 1, -1))
189 func((1900, 12, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000190 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000191 (1900, -1, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000192 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000193 (1900, 13, 1, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000194 # Check day of month [1, 31] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100195 func((1900, 1, 0, 0, 0, 0, 0, 1, -1))
196 func((1900, 1, 31, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000197 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000198 (1900, 1, -1, 0, 0, 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, 32, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000201 # Check hour [0, 23]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100202 func((1900, 1, 1, 23, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000203 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000204 (1900, 1, 1, -1, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000205 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000206 (1900, 1, 1, 24, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000207 # Check minute [0, 59]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100208 func((1900, 1, 1, 0, 59, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000209 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000210 (1900, 1, 1, 0, -1, 0, 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, 60, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000213 # Check second [0, 61]
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000214 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000215 (1900, 1, 1, 0, 0, -1, 0, 1, -1))
216 # C99 only requires allowing for one leap second, but Python's docs say
217 # allow two leap seconds (0..61)
Florent Xicluna49ce0682011-11-01 12:56:14 +0100218 func((1900, 1, 1, 0, 0, 60, 0, 1, -1))
219 func((1900, 1, 1, 0, 0, 61, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000220 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000221 (1900, 1, 1, 0, 0, 62, 0, 1, -1))
222 # No check for upper-bound day of week;
223 # value forced into range by a ``% 7`` calculation.
224 # Start check at -2 since gettmarg() increments value before taking
225 # modulo.
Florent Xicluna49ce0682011-11-01 12:56:14 +0100226 self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)),
227 func((1900, 1, 1, 0, 0, 0, +6, 1, -1)))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000228 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000229 (1900, 1, 1, 0, 0, 0, -2, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000230 # Check day of the year [1, 366] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100231 func((1900, 1, 1, 0, 0, 0, 0, 0, -1))
232 func((1900, 1, 1, 0, 0, 0, 0, 366, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000233 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000234 (1900, 1, 1, 0, 0, 0, 0, -1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000235 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000236 (1900, 1, 1, 0, 0, 0, 0, 367, -1))
Brett Cannond1080a32004-03-02 04:38:10 +0000237
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000238 def test_strftime_bounding_check(self):
239 self._bounds_checking(lambda tup: time.strftime('', tup))
240
Steve Dowere5b58952015-09-06 19:20:51 -0700241 def test_strftime_format_check(self):
242 # Test that strftime does not crash on invalid format strings
243 # that may trigger a buffer overread. When not triggered,
244 # strftime may succeed or raise ValueError depending on
245 # the platform.
246 for x in [ '', 'A', '%A', '%AA' ]:
247 for y in range(0x0, 0x10):
248 for z in [ '%', 'A%', 'AA%', '%A%', 'A%A%', '%#' ]:
249 try:
250 time.strftime(x * y + z)
251 except ValueError:
252 pass
253
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000254 def test_default_values_for_zero(self):
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400255 # Make sure that using all zeros uses the proper default
256 # values. No test for daylight savings since strftime() does
257 # not change output based on its value and no test for year
258 # because systems vary in their support for year 0.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000259 expected = "2000 01 01 00 00 00 1 001"
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000260 with support.check_warnings():
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400261 result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000262 self.assertEqual(expected, result)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000263
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000264 def test_strptime(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000265 # Should be able to go round-trip from strftime to strptime without
Andrew Svetlov737fb892012-12-18 21:14:22 +0200266 # raising an exception.
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000267 tt = time.gmtime(self.t)
268 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
269 'j', 'm', 'M', 'p', 'S',
270 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000271 format = '%' + directive
272 strf_output = time.strftime(format, tt)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000273 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000274 time.strptime(strf_output, format)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000275 except ValueError:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000276 self.fail("conversion specifier %r failed with '%s' input." %
277 (format, strf_output))
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000278
Brett Cannon7f6b4f82009-03-30 21:30:26 +0000279 def test_strptime_bytes(self):
280 # Make sure only strings are accepted as arguments to strptime.
281 self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
282 self.assertRaises(TypeError, time.strptime, '2009', b'%Y')
283
Ezio Melotti0f389082013-04-04 02:09:20 +0300284 def test_strptime_exception_context(self):
285 # check that this doesn't chain exceptions needlessly (see #17572)
286 with self.assertRaises(ValueError) as e:
287 time.strptime('', '%D')
288 self.assertIs(e.exception.__suppress_context__, True)
Serhiy Storchakacdac3022013-11-24 18:15:37 +0200289 # additional check for IndexError branch (issue #19545)
290 with self.assertRaises(ValueError) as e:
291 time.strptime('19', '%Y %')
292 self.assertIs(e.exception.__suppress_context__, True)
Ezio Melotti0f389082013-04-04 02:09:20 +0300293
Fred Drakebc561982001-05-22 17:02:02 +0000294 def test_asctime(self):
295 time.asctime(time.gmtime(self.t))
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000296
297 # Max year is only limited by the size of C int.
Florent Xiclunabceb5282011-11-01 14:11:34 +0100298 for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
299 asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
300 self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
301 self.assertRaises(OverflowError, time.asctime,
302 (TIME_MAXYEAR + 1,) + (0,) * 8)
303 self.assertRaises(OverflowError, time.asctime,
304 (TIME_MINYEAR - 1,) + (0,) * 8)
Fred Drakebc561982001-05-22 17:02:02 +0000305 self.assertRaises(TypeError, time.asctime, 0)
Alexander Belopolskye2dc0822011-01-02 20:48:22 +0000306 self.assertRaises(TypeError, time.asctime, ())
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000307 self.assertRaises(TypeError, time.asctime, (0,) * 10)
Fred Drakebc561982001-05-22 17:02:02 +0000308
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000309 def test_asctime_bounding_check(self):
310 self._bounds_checking(time.asctime)
311
Georg Brandle10608c2011-01-02 22:33:43 +0000312 def test_ctime(self):
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000313 t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
314 self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
315 t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
316 self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000')
Victor Stinner1ac42612014-02-21 09:27:17 +0100317 for year in [-100, 100, 1000, 2000, 2050, 10000]:
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000318 try:
319 testval = time.mktime((year, 1, 10) + (0,)*6)
320 except (ValueError, OverflowError):
321 # If mktime fails, ctime will fail too. This may happen
322 # on some platforms.
323 pass
324 else:
325 self.assertEqual(time.ctime(testval)[20:], str(year))
Georg Brandle10608c2011-01-02 22:33:43 +0000326
Florent Xiclunae54371e2011-11-11 18:59:30 +0100327 @unittest.skipUnless(hasattr(time, "tzset"),
328 "time module has no attribute tzset")
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000329 def test_tzset(self):
Guido van Rossumd2b738e2003-03-15 12:01:52 +0000330
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000331 from os import environ
332
Tim Peters0eadaac2003-04-24 16:02:54 +0000333 # Epoch time of midnight Dec 25th 2002. Never DST in northern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000334 # hemisphere.
Tim Peters0eadaac2003-04-24 16:02:54 +0000335 xmas2002 = 1040774400.0
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000336
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000337 # These formats are correct for 2002, and possibly future years
338 # This format is the 'standard' as documented at:
339 # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
340 # They are also documented in the tzset(3) man page on most Unix
341 # systems.
Tim Peters0eadaac2003-04-24 16:02:54 +0000342 eastern = 'EST+05EDT,M4.1.0,M10.5.0'
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000343 victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
344 utc='UTC+0'
345
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000346 org_TZ = environ.get('TZ',None)
347 try:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000348 # Make sure we can switch to UTC time and results are correct
349 # Note that unknown timezones default to UTC.
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000350 # Note that altzone is undefined in UTC, as there is no DST
351 environ['TZ'] = eastern
352 time.tzset()
353 environ['TZ'] = utc
354 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000355 self.assertEqual(
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000356 time.gmtime(xmas2002), time.localtime(xmas2002)
357 )
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000358 self.assertEqual(time.daylight, 0)
359 self.assertEqual(time.timezone, 0)
360 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000361
362 # Make sure we can switch to US/Eastern
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000363 environ['TZ'] = eastern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000364 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000365 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
366 self.assertEqual(time.tzname, ('EST', 'EDT'))
367 self.assertEqual(len(time.tzname), 2)
368 self.assertEqual(time.daylight, 1)
369 self.assertEqual(time.timezone, 18000)
370 self.assertEqual(time.altzone, 14400)
371 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
372 self.assertEqual(len(time.tzname), 2)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000373
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000374 # Now go to the southern hemisphere.
375 environ['TZ'] = victoria
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000376 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000377 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
Victor Stinner0cd47902011-12-08 00:32:51 +0100378
379 # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100380 # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
381 # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
382 # on some operating systems (e.g. FreeBSD), which is wrong. See for
383 # example this bug:
384 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
Victor Stinner0cd47902011-12-08 00:32:51 +0100385 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100386 self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000387 self.assertEqual(len(time.tzname), 2)
388 self.assertEqual(time.daylight, 1)
389 self.assertEqual(time.timezone, -36000)
390 self.assertEqual(time.altzone, -39600)
391 self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000392
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000393 finally:
394 # Repair TZ environment variable in case any other tests
395 # rely on it.
396 if org_TZ is not None:
397 environ['TZ'] = org_TZ
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000398 elif 'TZ' in environ:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000399 del environ['TZ']
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000400 time.tzset()
Tim Peters0eadaac2003-04-24 16:02:54 +0000401
Tim Peters1b6f7a92004-06-20 02:50:16 +0000402 def test_insane_timestamps(self):
403 # It's possible that some platform maps time_t to double,
404 # and that this test will fail there. This test should
405 # exempt such platforms (provided they return reasonable
406 # results!).
407 for func in time.ctime, time.gmtime, time.localtime:
408 for unreasonable in -1e200, 1e200:
Victor Stinner5d272cc2012-03-13 13:35:55 +0100409 self.assertRaises(OverflowError, func, unreasonable)
Fred Drakebc561982001-05-22 17:02:02 +0000410
Fred Drakef901abd2004-08-03 17:58:55 +0000411 def test_ctime_without_arg(self):
412 # Not sure how to check the values, since the clock could tick
413 # at any time. Make sure these are at least accepted and
414 # don't raise errors.
415 time.ctime()
416 time.ctime(None)
417
418 def test_gmtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000419 gt0 = time.gmtime()
420 gt1 = time.gmtime(None)
421 t0 = time.mktime(gt0)
422 t1 = time.mktime(gt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000423 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000424
425 def test_localtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000426 lt0 = time.localtime()
427 lt1 = time.localtime(None)
428 t0 = time.mktime(lt0)
429 t1 = time.mktime(lt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000430 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000431
Florent Xiclunae54371e2011-11-11 18:59:30 +0100432 def test_mktime(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100433 # Issue #1726687
434 for t in (-2, -1, 0, 1):
435 try:
436 tt = time.localtime(t)
Victor Stinner2cbae982012-01-27 00:50:33 +0100437 except (OverflowError, OSError):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100438 pass
439 else:
440 self.assertEqual(time.mktime(tt), t)
Florent Xiclunae54371e2011-11-11 18:59:30 +0100441
442 # Issue #13309: passing extreme values to mktime() or localtime()
443 # borks the glibc's internal timezone data.
444 @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
445 "disabled because of a bug in glibc. Issue #13309")
446 def test_mktime_error(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100447 # It may not be possible to reliably make mktime return error
448 # on all platfom. This will make sure that no other exception
449 # than OverflowError is raised for an extreme value.
Florent Xiclunae54371e2011-11-11 18:59:30 +0100450 tt = time.gmtime(self.t)
451 tzname = time.strftime('%Z', tt)
452 self.assertNotEqual(tzname, 'LMT')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100453 try:
454 time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
455 except OverflowError:
456 pass
Florent Xiclunae54371e2011-11-11 18:59:30 +0100457 self.assertEqual(time.strftime('%Z', tt), tzname)
Florent Xiclunabceb5282011-11-01 14:11:34 +0100458
Victor Stinnerec895392012-04-29 02:41:27 +0200459 def test_monotonic(self):
Victor Stinner6c861812013-11-23 00:15:27 +0100460 # monotonic() should not go backward
461 times = [time.monotonic() for n in range(100)]
462 t1 = times[0]
463 for t2 in times[1:]:
464 self.assertGreaterEqual(t2, t1, "times=%s" % times)
465 t1 = t2
466
467 # monotonic() includes time elapsed during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200468 t1 = time.monotonic()
Victor Stinnera9c99a62013-07-03 23:07:37 +0200469 time.sleep(0.5)
Victor Stinnerec895392012-04-29 02:41:27 +0200470 t2 = time.monotonic()
Victor Stinner2dd254d2012-01-20 02:24:18 +0100471 dt = t2 - t1
Victor Stinner8b302012012-02-07 23:29:46 +0100472 self.assertGreater(t2, t1)
Victor Stinnerd246a672019-04-24 00:15:12 +0200473 # bpo-20101: tolerate a difference of 50 ms because of bad timer
474 # resolution on Windows
475 self.assertTrue(0.450 <= dt)
Antoine Pitrou391166f2012-01-18 22:35:21 +0100476
Victor Stinner6c861812013-11-23 00:15:27 +0100477 # monotonic() is a monotonic but non adjustable clock
Victor Stinnerec895392012-04-29 02:41:27 +0200478 info = time.get_clock_info('monotonic')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400479 self.assertTrue(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +0200480 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200481
482 def test_perf_counter(self):
483 time.perf_counter()
484
485 def test_process_time(self):
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200486 # process_time() should not include time spend during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200487 start = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200488 time.sleep(0.100)
Victor Stinnerec895392012-04-29 02:41:27 +0200489 stop = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200490 # use 20 ms because process_time() has usually a resolution of 15 ms
491 # on Windows
492 self.assertLess(stop - start, 0.020)
Victor Stinnerec895392012-04-29 02:41:27 +0200493
494 info = time.get_clock_info('process_time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400495 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200496 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200497
Antoine Pitrou4bd41c92017-11-15 22:52:21 +0100498 def test_thread_time(self):
499 if not hasattr(time, 'thread_time'):
500 if sys.platform.startswith(('linux', 'win')):
501 self.fail("time.thread_time() should be available on %r"
502 % (sys.platform,))
503 else:
504 self.skipTest("need time.thread_time")
505
506 # thread_time() should not include time spend during a sleep
507 start = time.thread_time()
508 time.sleep(0.100)
509 stop = time.thread_time()
510 # use 20 ms because thread_time() has usually a resolution of 15 ms
511 # on Windows
512 self.assertLess(stop - start, 0.020)
513
Antoine Pitrou4bd41c92017-11-15 22:52:21 +0100514 info = time.get_clock_info('thread_time')
515 self.assertTrue(info.monotonic)
516 self.assertFalse(info.adjustable)
517
Victor Stinnerec895392012-04-29 02:41:27 +0200518 @unittest.skipUnless(hasattr(time, 'clock_settime'),
519 'need time.clock_settime')
520 def test_monotonic_settime(self):
521 t1 = time.monotonic()
522 realtime = time.clock_gettime(time.CLOCK_REALTIME)
523 # jump backward with an offset of 1 hour
Victor Stinner071eca32012-03-15 01:17:09 +0100524 try:
Victor Stinnerec895392012-04-29 02:41:27 +0200525 time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
526 except PermissionError as err:
527 self.skipTest(err)
528 t2 = time.monotonic()
529 time.clock_settime(time.CLOCK_REALTIME, realtime)
530 # monotonic must not be affected by system clock updates
Victor Stinner071eca32012-03-15 01:17:09 +0100531 self.assertGreaterEqual(t2, t1)
532
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100533 def test_localtime_failure(self):
534 # Issue #13847: check for localtime() failure
Victor Stinner53d36452012-01-27 01:03:25 +0100535 invalid_time_t = None
536 for time_t in (-1, 2**30, 2**33, 2**60):
537 try:
538 time.localtime(time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100539 except OverflowError:
540 self.skipTest("need 64-bit time_t")
Victor Stinner53d36452012-01-27 01:03:25 +0100541 except OSError:
542 invalid_time_t = time_t
543 break
544 if invalid_time_t is None:
545 self.skipTest("unable to find an invalid time_t value")
546
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100547 self.assertRaises(OSError, time.localtime, invalid_time_t)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100548 self.assertRaises(OSError, time.ctime, invalid_time_t)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100549
Han Lee829dacc2017-09-09 08:05:05 +0900550 # Issue #26669: check for localtime() failure
551 self.assertRaises(ValueError, time.localtime, float("nan"))
552 self.assertRaises(ValueError, time.ctime, float("nan"))
553
Victor Stinnerec895392012-04-29 02:41:27 +0200554 def test_get_clock_info(self):
pxinwrf1464f42019-04-15 17:06:21 +0800555 clocks = ['monotonic', 'perf_counter', 'process_time', 'time']
556 if hasattr(time, 'clock'):
557 clocks.append('clock')
Victor Stinnerec895392012-04-29 02:41:27 +0200558
559 for name in clocks:
Victor Stinner884d13a2017-10-17 14:46:45 -0700560 if name == 'clock':
561 with self.assertWarns(DeprecationWarning):
562 info = time.get_clock_info('clock')
563 else:
564 info = time.get_clock_info(name)
565
Victor Stinnerec895392012-04-29 02:41:27 +0200566 #self.assertIsInstance(info, dict)
567 self.assertIsInstance(info.implementation, str)
568 self.assertNotEqual(info.implementation, '')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400569 self.assertIsInstance(info.monotonic, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200570 self.assertIsInstance(info.resolution, float)
571 # 0.0 < resolution <= 1.0
572 self.assertGreater(info.resolution, 0.0)
573 self.assertLessEqual(info.resolution, 1.0)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200574 self.assertIsInstance(info.adjustable, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200575
576 self.assertRaises(ValueError, time.get_clock_info, 'xxx')
577
578
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000579class TestLocale(unittest.TestCase):
580 def setUp(self):
581 self.oldloc = locale.setlocale(locale.LC_ALL)
Fred Drake2e2be372001-09-20 21:33:42 +0000582
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000583 def tearDown(self):
584 locale.setlocale(locale.LC_ALL, self.oldloc)
585
Martin v. Löwisa6a9c4d2009-05-30 06:15:30 +0000586 def test_bug_3061(self):
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000587 try:
588 tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
589 except locale.Error:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600590 self.skipTest('could not set locale.LC_ALL to fr_FR')
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000591 # This should not cause an exception
592 time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
593
Victor Stinner73ea29c2011-01-08 01:56:31 +0000594
Victor Stinner73ea29c2011-01-08 01:56:31 +0000595class _TestAsctimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100596 _format = '%d'
597
Victor Stinner73ea29c2011-01-08 01:56:31 +0000598 def yearstr(self, y):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000599 return time.asctime((y,) + (0,) * 8).split()[-1]
Alexander Belopolskya6867252011-01-05 23:00:47 +0000600
Victor Stinner73ea29c2011-01-08 01:56:31 +0000601 def test_large_year(self):
Victor Stinner73691322011-01-08 02:00:24 +0000602 # Check that it doesn't crash for year > 9999
Victor Stinner73ea29c2011-01-08 01:56:31 +0000603 self.assertEqual(self.yearstr(12345), '12345')
604 self.assertEqual(self.yearstr(123456789), '123456789')
605
606class _TestStrftimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100607
608 # Issue 13305: For years < 1000, the value is not always
609 # padded to 4 digits across platforms. The C standard
610 # assumes year >= 1900, so it does not specify the number
611 # of digits.
612
613 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
614 _format = '%04d'
615 else:
616 _format = '%d'
617
Victor Stinner73ea29c2011-01-08 01:56:31 +0000618 def yearstr(self, y):
Florent Xicluna49ce0682011-11-01 12:56:14 +0100619 return time.strftime('%Y', (y,) + (0,) * 8)
620
621 def test_4dyear(self):
622 # Check that we can return the zero padded value.
623 if self._format == '%04d':
624 self.test_year('%04d')
625 else:
626 def year4d(y):
627 return time.strftime('%4Y', (y,) + (0,) * 8)
628 self.test_year('%04d', func=year4d)
629
Florent Xiclunabceb5282011-11-01 14:11:34 +0100630 def skip_if_not_supported(y):
631 msg = "strftime() is limited to [1; 9999] with Visual Studio"
632 # Check that it doesn't crash for year > 9999
633 try:
634 time.strftime('%Y', (y,) + (0,) * 8)
635 except ValueError:
636 cond = False
637 else:
638 cond = True
639 return unittest.skipUnless(cond, msg)
640
641 @skip_if_not_supported(10000)
642 def test_large_year(self):
643 return super().test_large_year()
644
645 @skip_if_not_supported(0)
646 def test_negative(self):
647 return super().test_negative()
648
649 del skip_if_not_supported
650
651
Ezio Melotti3836d702013-04-11 20:29:42 +0300652class _Test4dYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100653 _format = '%d'
654
655 def test_year(self, fmt=None, func=None):
656 fmt = fmt or self._format
657 func = func or self.yearstr
658 self.assertEqual(func(1), fmt % 1)
659 self.assertEqual(func(68), fmt % 68)
660 self.assertEqual(func(69), fmt % 69)
661 self.assertEqual(func(99), fmt % 99)
662 self.assertEqual(func(999), fmt % 999)
663 self.assertEqual(func(9999), fmt % 9999)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000664
665 def test_large_year(self):
Benjamin Petersone1a34ce2018-09-12 16:21:36 -0700666 self.assertEqual(self.yearstr(12345).lstrip('+'), '12345')
667 self.assertEqual(self.yearstr(123456789).lstrip('+'), '123456789')
668 self.assertEqual(self.yearstr(TIME_MAXYEAR).lstrip('+'), str(TIME_MAXYEAR))
Florent Xiclunabceb5282011-11-01 14:11:34 +0100669 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000670
Victor Stinner301f1212011-01-08 03:06:52 +0000671 def test_negative(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100672 self.assertEqual(self.yearstr(-1), self._format % -1)
Victor Stinner301f1212011-01-08 03:06:52 +0000673 self.assertEqual(self.yearstr(-1234), '-1234')
674 self.assertEqual(self.yearstr(-123456), '-123456')
Florent Xiclunad1bd7f72011-11-01 23:42:05 +0100675 self.assertEqual(self.yearstr(-123456789), str(-123456789))
676 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
Gregory P. Smith76be0ff2018-08-24 18:08:50 -0700677 self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
678 # Modules/timemodule.c checks for underflow
Florent Xiclunabceb5282011-11-01 14:11:34 +0100679 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
Gregory P. Smith76be0ff2018-08-24 18:08:50 -0700680 with self.assertRaises(OverflowError):
681 self.yearstr(-TIME_MAXYEAR - 1)
Victor Stinner301f1212011-01-08 03:06:52 +0000682
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000683
Ezio Melotti3836d702013-04-11 20:29:42 +0300684class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner73ea29c2011-01-08 01:56:31 +0000685 pass
686
Ezio Melotti3836d702013-04-11 20:29:42 +0300687class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner301f1212011-01-08 03:06:52 +0000688 pass
Victor Stinner73ea29c2011-01-08 01:56:31 +0000689
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000690
Victor Stinner643cd682012-03-02 22:54:03 +0100691class TestPytime(unittest.TestCase):
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400692 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
693 def test_localtime_timezone(self):
Victor Stinner643cd682012-03-02 22:54:03 +0100694
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400695 # Get the localtime and examine it for the offset and zone.
696 lt = time.localtime()
697 self.assertTrue(hasattr(lt, "tm_gmtoff"))
698 self.assertTrue(hasattr(lt, "tm_zone"))
699
700 # See if the offset and zone are similar to the module
701 # attributes.
702 if lt.tm_gmtoff is None:
703 self.assertTrue(not hasattr(time, "timezone"))
704 else:
705 self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
706 if lt.tm_zone is None:
707 self.assertTrue(not hasattr(time, "tzname"))
708 else:
709 self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
710
711 # Try and make UNIX times from the localtime and a 9-tuple
712 # created from the localtime. Test to see that the times are
713 # the same.
714 t = time.mktime(lt); t9 = time.mktime(lt[:9])
715 self.assertEqual(t, t9)
716
717 # Make localtimes from the UNIX times and compare them to
718 # the original localtime, thus making a round trip.
719 new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
720 self.assertEqual(new_lt, lt)
721 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
722 self.assertEqual(new_lt.tm_zone, lt.tm_zone)
723 self.assertEqual(new_lt9, lt)
724 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
725 self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
726
727 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
728 def test_strptime_timezone(self):
729 t = time.strptime("UTC", "%Z")
730 self.assertEqual(t.tm_zone, 'UTC')
731 t = time.strptime("+0500", "%z")
732 self.assertEqual(t.tm_gmtoff, 5 * 3600)
733
734 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
735 def test_short_times(self):
736
737 import pickle
738
739 # Load a short time structure using pickle.
740 st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
741 lt = pickle.loads(st)
742 self.assertIs(lt.tm_gmtoff, None)
743 self.assertIs(lt.tm_zone, None)
Victor Stinner643cd682012-03-02 22:54:03 +0100744
Fred Drake2e2be372001-09-20 21:33:42 +0000745
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200746@unittest.skipIf(_testcapi is None, 'need the _testcapi module')
747class CPyTimeTestCase:
Victor Stinneracea9f62015-09-02 10:39:40 +0200748 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200749 Base class to test the C _PyTime_t API.
Victor Stinneracea9f62015-09-02 10:39:40 +0200750 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200751 OVERFLOW_SECONDS = None
752
Victor Stinner4237d342015-09-10 10:10:39 +0200753 def setUp(self):
754 from _testcapi import SIZEOF_TIME_T
755 bits = SIZEOF_TIME_T * 8 - 1
756 self.time_t_min = -2 ** bits
757 self.time_t_max = 2 ** bits - 1
758
759 def time_t_filter(self, seconds):
760 return (self.time_t_min <= seconds <= self.time_t_max)
761
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200762 def _rounding_values(self, use_float):
763 "Build timestamps used to test rounding."
764
765 units = [1, US_TO_NS, MS_TO_NS, SEC_TO_NS]
766 if use_float:
767 # picoseconds are only tested to pytime_converter accepting floats
768 units.append(1e-3)
769
770 values = (
771 # small values
772 1, 2, 5, 7, 123, 456, 1234,
773 # 10^k - 1
774 9,
775 99,
776 999,
777 9999,
778 99999,
779 999999,
780 # test half even rounding near 0.5, 1.5, 2.5, 3.5, 4.5
781 499, 500, 501,
782 1499, 1500, 1501,
783 2500,
784 3500,
785 4500,
786 )
787
788 ns_timestamps = [0]
789 for unit in units:
790 for value in values:
791 ns = value * unit
792 ns_timestamps.extend((-ns, ns))
793 for pow2 in (0, 5, 10, 15, 22, 23, 24, 30, 33):
794 ns = (2 ** pow2) * SEC_TO_NS
795 ns_timestamps.extend((
796 -ns-1, -ns, -ns+1,
797 ns-1, ns, ns+1
798 ))
799 for seconds in (_testcapi.INT_MIN, _testcapi.INT_MAX):
800 ns_timestamps.append(seconds * SEC_TO_NS)
801 if use_float:
Victor Stinner717a32b2016-08-17 11:07:21 +0200802 # numbers with an exact representation in IEEE 754 (base 2)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200803 for pow2 in (3, 7, 10, 15):
804 ns = 2.0 ** (-pow2)
805 ns_timestamps.extend((-ns, ns))
806
807 # seconds close to _PyTime_t type limit
808 ns = (2 ** 63 // SEC_TO_NS) * SEC_TO_NS
809 ns_timestamps.extend((-ns, ns))
810
811 return ns_timestamps
812
813 def _check_rounding(self, pytime_converter, expected_func,
814 use_float, unit_to_sec, value_filter=None):
815
816 def convert_values(ns_timestamps):
817 if use_float:
818 unit_to_ns = SEC_TO_NS / float(unit_to_sec)
819 values = [ns / unit_to_ns for ns in ns_timestamps]
820 else:
821 unit_to_ns = SEC_TO_NS // unit_to_sec
822 values = [ns // unit_to_ns for ns in ns_timestamps]
823
824 if value_filter:
825 values = filter(value_filter, values)
826
827 # remove duplicates and sort
828 return sorted(set(values))
829
830 # test rounding
831 ns_timestamps = self._rounding_values(use_float)
832 valid_values = convert_values(ns_timestamps)
833 for time_rnd, decimal_rnd in ROUNDING_MODES :
Bo Bayles938045f2018-07-21 12:54:14 -0500834 with decimal.localcontext() as context:
835 context.rounding = decimal_rnd
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200836
Bo Bayles938045f2018-07-21 12:54:14 -0500837 for value in valid_values:
838 debug_info = {'value': value, 'rounding': decimal_rnd}
839 try:
840 result = pytime_converter(value, time_rnd)
841 expected = expected_func(value)
842 except Exception as exc:
843 self.fail("Error on timestamp conversion: %s" % debug_info)
844 self.assertEqual(result,
845 expected,
846 debug_info)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200847
848 # test overflow
849 ns = self.OVERFLOW_SECONDS * SEC_TO_NS
850 ns_timestamps = (-ns, ns)
851 overflow_values = convert_values(ns_timestamps)
852 for time_rnd, _ in ROUNDING_MODES :
853 for value in overflow_values:
Victor Stinnerc60542b2015-09-10 15:55:07 +0200854 debug_info = {'value': value, 'rounding': time_rnd}
855 with self.assertRaises(OverflowError, msg=debug_info):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200856 pytime_converter(value, time_rnd)
857
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200858 def check_int_rounding(self, pytime_converter, expected_func,
859 unit_to_sec=1, value_filter=None):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200860 self._check_rounding(pytime_converter, expected_func,
861 False, unit_to_sec, value_filter)
862
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200863 def check_float_rounding(self, pytime_converter, expected_func,
864 unit_to_sec=1, value_filter=None):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200865 self._check_rounding(pytime_converter, expected_func,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200866 True, unit_to_sec, value_filter)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200867
868 def decimal_round(self, x):
869 d = decimal.Decimal(x)
870 d = d.quantize(1)
871 return int(d)
872
873
874class TestCPyTime(CPyTimeTestCase, unittest.TestCase):
875 """
876 Test the C _PyTime_t API.
877 """
878 # _PyTime_t is a 64-bit signed integer
879 OVERFLOW_SECONDS = math.ceil((2**63 + 1) / SEC_TO_NS)
880
Victor Stinner13019fd2015-04-03 13:10:54 +0200881 def test_FromSeconds(self):
882 from _testcapi import PyTime_FromSeconds
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200883
884 # PyTime_FromSeconds() expects a C int, reject values out of range
885 def c_int_filter(secs):
886 return (_testcapi.INT_MIN <= secs <= _testcapi.INT_MAX)
887
888 self.check_int_rounding(lambda secs, rnd: PyTime_FromSeconds(secs),
889 lambda secs: secs * SEC_TO_NS,
890 value_filter=c_int_filter)
Victor Stinner13019fd2015-04-03 13:10:54 +0200891
Han Lee829dacc2017-09-09 08:05:05 +0900892 # test nan
893 for time_rnd, _ in ROUNDING_MODES:
894 with self.assertRaises(TypeError):
895 PyTime_FromSeconds(float('nan'))
896
Victor Stinner992c43f2015-03-27 17:12:45 +0100897 def test_FromSecondsObject(self):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100898 from _testcapi import PyTime_FromSecondsObject
Victor Stinner992c43f2015-03-27 17:12:45 +0100899
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200900 self.check_int_rounding(
901 PyTime_FromSecondsObject,
902 lambda secs: secs * SEC_TO_NS)
Victor Stinner992c43f2015-03-27 17:12:45 +0100903
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200904 self.check_float_rounding(
905 PyTime_FromSecondsObject,
906 lambda ns: self.decimal_round(ns * SEC_TO_NS))
Victor Stinner4bfb4602015-03-27 22:27:24 +0100907
Han Lee829dacc2017-09-09 08:05:05 +0900908 # test nan
909 for time_rnd, _ in ROUNDING_MODES:
910 with self.assertRaises(ValueError):
911 PyTime_FromSecondsObject(float('nan'), time_rnd)
912
Victor Stinner4bfb4602015-03-27 22:27:24 +0100913 def test_AsSecondsDouble(self):
914 from _testcapi import PyTime_AsSecondsDouble
915
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200916 def float_converter(ns):
917 if abs(ns) % SEC_TO_NS == 0:
918 return float(ns // SEC_TO_NS)
919 else:
920 return float(ns) / SEC_TO_NS
Victor Stinner4bfb4602015-03-27 22:27:24 +0100921
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200922 self.check_int_rounding(lambda ns, rnd: PyTime_AsSecondsDouble(ns),
923 float_converter,
924 NS_TO_SEC)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100925
Han Lee829dacc2017-09-09 08:05:05 +0900926 # test nan
927 for time_rnd, _ in ROUNDING_MODES:
928 with self.assertRaises(TypeError):
929 PyTime_AsSecondsDouble(float('nan'))
930
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200931 def create_decimal_converter(self, denominator):
932 denom = decimal.Decimal(denominator)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100933
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200934 def converter(value):
935 d = decimal.Decimal(value) / denom
936 return self.decimal_round(d)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100937
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200938 return converter
Victor Stinner4bfb4602015-03-27 22:27:24 +0100939
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200940 def test_AsTimeval(self):
Victor Stinner95e9cef2015-03-28 01:26:47 +0100941 from _testcapi import PyTime_AsTimeval
Victor Stinner95e9cef2015-03-28 01:26:47 +0100942
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200943 us_converter = self.create_decimal_converter(US_TO_NS)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100944
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200945 def timeval_converter(ns):
946 us = us_converter(ns)
947 return divmod(us, SEC_TO_US)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100948
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200949 if sys.platform == 'win32':
950 from _testcapi import LONG_MIN, LONG_MAX
951
952 # On Windows, timeval.tv_sec type is a C long
953 def seconds_filter(secs):
954 return LONG_MIN <= secs <= LONG_MAX
955 else:
Victor Stinner4237d342015-09-10 10:10:39 +0200956 seconds_filter = self.time_t_filter
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200957
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200958 self.check_int_rounding(PyTime_AsTimeval,
959 timeval_converter,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200960 NS_TO_SEC,
961 value_filter=seconds_filter)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100962
Victor Stinner34dc0f42015-03-27 18:19:03 +0100963 @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec'),
964 'need _testcapi.PyTime_AsTimespec')
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200965 def test_AsTimespec(self):
Victor Stinner34dc0f42015-03-27 18:19:03 +0100966 from _testcapi import PyTime_AsTimespec
Victor Stinner34dc0f42015-03-27 18:19:03 +0100967
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200968 def timespec_converter(ns):
969 return divmod(ns, SEC_TO_NS)
Victor Stinner34dc0f42015-03-27 18:19:03 +0100970
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200971 self.check_int_rounding(lambda ns, rnd: PyTime_AsTimespec(ns),
972 timespec_converter,
Victor Stinner4237d342015-09-10 10:10:39 +0200973 NS_TO_SEC,
974 value_filter=self.time_t_filter)
Victor Stinner34dc0f42015-03-27 18:19:03 +0100975
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200976 def test_AsMilliseconds(self):
Victor Stinner62d1c702015-04-01 17:47:07 +0200977 from _testcapi import PyTime_AsMilliseconds
Victor Stinner62d1c702015-04-01 17:47:07 +0200978
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200979 self.check_int_rounding(PyTime_AsMilliseconds,
980 self.create_decimal_converter(MS_TO_NS),
981 NS_TO_SEC)
Victor Stinner62d1c702015-04-01 17:47:07 +0200982
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200983 def test_AsMicroseconds(self):
Victor Stinner62d1c702015-04-01 17:47:07 +0200984 from _testcapi import PyTime_AsMicroseconds
Victor Stinner62d1c702015-04-01 17:47:07 +0200985
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200986 self.check_int_rounding(PyTime_AsMicroseconds,
987 self.create_decimal_converter(US_TO_NS),
988 NS_TO_SEC)
Victor Stinner62d1c702015-04-01 17:47:07 +0200989
Victor Stinner992c43f2015-03-27 17:12:45 +0100990
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200991class TestOldPyTime(CPyTimeTestCase, unittest.TestCase):
Victor Stinneracea9f62015-09-02 10:39:40 +0200992 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200993 Test the old C _PyTime_t API: _PyTime_ObjectToXXX() functions.
Victor Stinneracea9f62015-09-02 10:39:40 +0200994 """
Victor Stinneracea9f62015-09-02 10:39:40 +0200995
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200996 # time_t is a 32-bit or 64-bit signed integer
997 OVERFLOW_SECONDS = 2 ** 64
998
999 def test_object_to_time_t(self):
Victor Stinneracea9f62015-09-02 10:39:40 +02001000 from _testcapi import pytime_object_to_time_t
1001
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001002 self.check_int_rounding(pytime_object_to_time_t,
Victor Stinner4237d342015-09-10 10:10:39 +02001003 lambda secs: secs,
1004 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001005
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001006 self.check_float_rounding(pytime_object_to_time_t,
Victor Stinner350b5182015-09-10 11:45:06 +02001007 self.decimal_round,
1008 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001009
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001010 def create_converter(self, sec_to_unit):
1011 def converter(secs):
1012 floatpart, intpart = math.modf(secs)
1013 intpart = int(intpart)
1014 floatpart *= sec_to_unit
1015 floatpart = self.decimal_round(floatpart)
1016 if floatpart < 0:
1017 floatpart += sec_to_unit
1018 intpart -= 1
1019 elif floatpart >= sec_to_unit:
1020 floatpart -= sec_to_unit
1021 intpart += 1
1022 return (intpart, floatpart)
1023 return converter
Victor Stinneracea9f62015-09-02 10:39:40 +02001024
Victor Stinneradfefa52015-09-04 23:57:25 +02001025 def test_object_to_timeval(self):
Victor Stinneracea9f62015-09-02 10:39:40 +02001026 from _testcapi import pytime_object_to_timeval
1027
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001028 self.check_int_rounding(pytime_object_to_timeval,
Victor Stinner4237d342015-09-10 10:10:39 +02001029 lambda secs: (secs, 0),
1030 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001031
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001032 self.check_float_rounding(pytime_object_to_timeval,
Victor Stinner350b5182015-09-10 11:45:06 +02001033 self.create_converter(SEC_TO_US),
1034 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001035
Han Lee829dacc2017-09-09 08:05:05 +09001036 # test nan
1037 for time_rnd, _ in ROUNDING_MODES:
1038 with self.assertRaises(ValueError):
1039 pytime_object_to_timeval(float('nan'), time_rnd)
1040
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001041 def test_object_to_timespec(self):
Victor Stinneracea9f62015-09-02 10:39:40 +02001042 from _testcapi import pytime_object_to_timespec
1043
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001044 self.check_int_rounding(pytime_object_to_timespec,
Victor Stinner4237d342015-09-10 10:10:39 +02001045 lambda secs: (secs, 0),
1046 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001047
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001048 self.check_float_rounding(pytime_object_to_timespec,
Victor Stinner350b5182015-09-10 11:45:06 +02001049 self.create_converter(SEC_TO_NS),
1050 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001051
Han Lee829dacc2017-09-09 08:05:05 +09001052 # test nan
1053 for time_rnd, _ in ROUNDING_MODES:
1054 with self.assertRaises(ValueError):
1055 pytime_object_to_timespec(float('nan'), time_rnd)
1056
Victor Stinneracea9f62015-09-02 10:39:40 +02001057
Fred Drake2e2be372001-09-20 21:33:42 +00001058if __name__ == "__main__":
Ezio Melotti3836d702013-04-11 20:29:42 +03001059 unittest.main()