blob: eda3885ad575f355da714d91916d6ec15042afc7 [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 Stinner884d13a2017-10-17 14:46:45 -070012import warnings
Victor Stinnerec895392012-04-29 02:41:27 +020013try:
Victor Stinner34dc0f42015-03-27 18:19:03 +010014 import _testcapi
15except ImportError:
16 _testcapi = None
17
Barry Warsawb0c22321996-12-06 23:30:07 +000018
Florent Xiclunabceb5282011-11-01 14:11:34 +010019# Max year is only limited by the size of C int.
20SIZEOF_INT = sysconfig.get_config_var('SIZEOF_INT') or 4
21TIME_MAXYEAR = (1 << 8 * SIZEOF_INT - 1) - 1
22TIME_MINYEAR = -TIME_MAXYEAR - 1
Victor Stinner992c43f2015-03-27 17:12:45 +010023
Victor Stinner3e2c8d82015-09-09 22:32:48 +020024SEC_TO_US = 10 ** 6
Victor Stinner62d1c702015-04-01 17:47:07 +020025US_TO_NS = 10 ** 3
26MS_TO_NS = 10 ** 6
Victor Stinner4bfb4602015-03-27 22:27:24 +010027SEC_TO_NS = 10 ** 9
Victor Stinner3e2c8d82015-09-09 22:32:48 +020028NS_TO_SEC = 10 ** 9
Victor Stinner992c43f2015-03-27 17:12:45 +010029
30class _PyTime(enum.IntEnum):
Victor Stinnerbcdd7772015-03-30 03:52:49 +020031 # Round towards minus infinity (-inf)
Victor Stinnera695f832015-03-30 03:57:14 +020032 ROUND_FLOOR = 0
Victor Stinnerbcdd7772015-03-30 03:52:49 +020033 # Round towards infinity (+inf)
Victor Stinnera695f832015-03-30 03:57:14 +020034 ROUND_CEILING = 1
Victor Stinner7667f582015-09-09 01:02:23 +020035 # Round to nearest with ties going to nearest even integer
36 ROUND_HALF_EVEN = 2
Pablo Galindo2c15b292017-10-17 15:14:41 +010037 # Round away from zero
38 ROUND_UP = 3
Victor Stinner992c43f2015-03-27 17:12:45 +010039
Victor Stinner3e2c8d82015-09-09 22:32:48 +020040# Rounding modes supported by PyTime
41ROUNDING_MODES = (
42 # (PyTime rounding method, decimal rounding method)
43 (_PyTime.ROUND_FLOOR, decimal.ROUND_FLOOR),
44 (_PyTime.ROUND_CEILING, decimal.ROUND_CEILING),
45 (_PyTime.ROUND_HALF_EVEN, decimal.ROUND_HALF_EVEN),
Pablo Galindo2c15b292017-10-17 15:14:41 +010046 (_PyTime.ROUND_UP, decimal.ROUND_UP),
Victor Stinner3e2c8d82015-09-09 22:32:48 +020047)
Florent Xiclunabceb5282011-11-01 14:11:34 +010048
49
Antoine Pitrou4bd41c92017-11-15 22:52:21 +010050def busy_wait(duration):
51 deadline = time.monotonic() + duration
52 while time.monotonic() < deadline:
53 pass
54
55
Fred Drakebc561982001-05-22 17:02:02 +000056class TimeTestCase(unittest.TestCase):
Barry Warsawb0c22321996-12-06 23:30:07 +000057
Fred Drakebc561982001-05-22 17:02:02 +000058 def setUp(self):
59 self.t = time.time()
Barry Warsawb0c22321996-12-06 23:30:07 +000060
Fred Drakebc561982001-05-22 17:02:02 +000061 def test_data_attributes(self):
62 time.altzone
63 time.daylight
64 time.timezone
65 time.tzname
Barry Warsawb0c22321996-12-06 23:30:07 +000066
Victor Stinnerec895392012-04-29 02:41:27 +020067 def test_time(self):
68 time.time()
69 info = time.get_clock_info('time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040070 self.assertFalse(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +020071 self.assertTrue(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020072
Victor Stinnerc29b5852017-11-02 07:28:27 -070073 def test_time_ns_type(self):
74 def check_ns(sec, ns):
75 self.assertIsInstance(ns, int)
76
77 sec_ns = int(sec * 1e9)
78 # tolerate a difference of 50 ms
79 self.assertLess((sec_ns - ns), 50 ** 6, (sec, ns))
80
81 check_ns(time.time(),
82 time.time_ns())
83 check_ns(time.monotonic(),
84 time.monotonic_ns())
85 check_ns(time.perf_counter(),
86 time.perf_counter_ns())
87 check_ns(time.process_time(),
88 time.process_time_ns())
89
Antoine Pitrou4bd41c92017-11-15 22:52:21 +010090 if hasattr(time, 'thread_time'):
91 check_ns(time.thread_time(),
92 time.thread_time_ns())
93
Victor Stinnerc29b5852017-11-02 07:28:27 -070094 if hasattr(time, 'clock_gettime'):
95 check_ns(time.clock_gettime(time.CLOCK_REALTIME),
96 time.clock_gettime_ns(time.CLOCK_REALTIME))
97
Fred Drakebc561982001-05-22 17:02:02 +000098 def test_clock(self):
Victor Stinner884d13a2017-10-17 14:46:45 -070099 with self.assertWarns(DeprecationWarning):
100 time.clock()
Barry Warsawb0c22321996-12-06 23:30:07 +0000101
Victor Stinner884d13a2017-10-17 14:46:45 -0700102 with self.assertWarns(DeprecationWarning):
103 info = time.get_clock_info('clock')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400104 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200105 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200106
Victor Stinnere0be4232011-10-25 13:06:09 +0200107 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
108 'need time.clock_gettime()')
109 def test_clock_realtime(self):
Victor Stinnerc29b5852017-11-02 07:28:27 -0700110 t = time.clock_gettime(time.CLOCK_REALTIME)
111 self.assertIsInstance(t, float)
Victor Stinnere0be4232011-10-25 13:06:09 +0200112
113 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
114 'need time.clock_gettime()')
115 @unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'),
116 'need time.CLOCK_MONOTONIC')
117 def test_clock_monotonic(self):
118 a = time.clock_gettime(time.CLOCK_MONOTONIC)
119 b = time.clock_gettime(time.CLOCK_MONOTONIC)
120 self.assertLessEqual(a, b)
121
pdoxe14679c2017-10-05 00:01:56 -0700122 @unittest.skipUnless(hasattr(time, 'pthread_getcpuclockid'),
123 'need time.pthread_getcpuclockid()')
124 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
125 'need time.clock_gettime()')
pdoxe14679c2017-10-05 00:01:56 -0700126 def test_pthread_getcpuclockid(self):
127 clk_id = time.pthread_getcpuclockid(threading.get_ident())
128 self.assertTrue(type(clk_id) is int)
129 self.assertNotEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
pdoxe14679c2017-10-05 00:01:56 -0700130 t1 = time.clock_gettime(clk_id)
Benjamin Peterson86566702017-10-05 22:50:42 -0700131 t2 = time.clock_gettime(clk_id)
pdoxe14679c2017-10-05 00:01:56 -0700132 self.assertLessEqual(t1, t2)
pdoxe14679c2017-10-05 00:01:56 -0700133
Victor Stinnere0be4232011-10-25 13:06:09 +0200134 @unittest.skipUnless(hasattr(time, 'clock_getres'),
135 'need time.clock_getres()')
136 def test_clock_getres(self):
137 res = time.clock_getres(time.CLOCK_REALTIME)
138 self.assertGreater(res, 0.0)
139 self.assertLessEqual(res, 1.0)
140
Victor Stinner30d79472012-04-03 00:45:07 +0200141 @unittest.skipUnless(hasattr(time, 'clock_settime'),
142 'need time.clock_settime()')
143 def test_clock_settime(self):
144 t = time.clock_gettime(time.CLOCK_REALTIME)
145 try:
146 time.clock_settime(time.CLOCK_REALTIME, t)
147 except PermissionError:
148 pass
149
Victor Stinnerec895392012-04-29 02:41:27 +0200150 if hasattr(time, 'CLOCK_MONOTONIC'):
151 self.assertRaises(OSError,
152 time.clock_settime, time.CLOCK_MONOTONIC, 0)
Victor Stinner30d79472012-04-03 00:45:07 +0200153
Fred Drakebc561982001-05-22 17:02:02 +0000154 def test_conversions(self):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000155 self.assertEqual(time.ctime(self.t),
156 time.asctime(time.localtime(self.t)))
157 self.assertEqual(int(time.mktime(time.localtime(self.t))),
158 int(self.t))
Fred Drakebc561982001-05-22 17:02:02 +0000159
160 def test_sleep(self):
Victor Stinner7f53a502011-07-05 22:00:25 +0200161 self.assertRaises(ValueError, time.sleep, -2)
162 self.assertRaises(ValueError, time.sleep, -1)
Fred Drakebc561982001-05-22 17:02:02 +0000163 time.sleep(1.2)
164
165 def test_strftime(self):
166 tt = time.gmtime(self.t)
167 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
168 'j', 'm', 'M', 'p', 'S',
169 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
170 format = ' %' + directive
171 try:
172 time.strftime(format, tt)
173 except ValueError:
174 self.fail('conversion specifier: %r failed.' % format)
175
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300176 self.assertRaises(TypeError, time.strftime, b'%S', tt)
177 # embedded null character
178 self.assertRaises(ValueError, time.strftime, '%S\0', tt)
179
Florent Xicluna49ce0682011-11-01 12:56:14 +0100180 def _bounds_checking(self, func):
Brett Cannond1080a32004-03-02 04:38:10 +0000181 # Make sure that strftime() checks the bounds of the various parts
Florent Xicluna49ce0682011-11-01 12:56:14 +0100182 # of the time tuple (0 is valid for *all* values).
Brett Cannond1080a32004-03-02 04:38:10 +0000183
Victor Stinner73ea29c2011-01-08 01:56:31 +0000184 # The year field is tested by other test cases above
185
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000186 # Check month [1, 12] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100187 func((1900, 0, 1, 0, 0, 0, 0, 1, -1))
188 func((1900, 12, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000189 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000190 (1900, -1, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000191 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000192 (1900, 13, 1, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000193 # Check day of month [1, 31] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100194 func((1900, 1, 0, 0, 0, 0, 0, 1, -1))
195 func((1900, 1, 31, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000196 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000197 (1900, 1, -1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000198 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000199 (1900, 1, 32, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000200 # Check hour [0, 23]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100201 func((1900, 1, 1, 23, 0, 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, -1, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000204 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000205 (1900, 1, 1, 24, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000206 # Check minute [0, 59]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100207 func((1900, 1, 1, 0, 59, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000208 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000209 (1900, 1, 1, 0, -1, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000210 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000211 (1900, 1, 1, 0, 60, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000212 # Check second [0, 61]
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000213 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000214 (1900, 1, 1, 0, 0, -1, 0, 1, -1))
215 # C99 only requires allowing for one leap second, but Python's docs say
216 # allow two leap seconds (0..61)
Florent Xicluna49ce0682011-11-01 12:56:14 +0100217 func((1900, 1, 1, 0, 0, 60, 0, 1, -1))
218 func((1900, 1, 1, 0, 0, 61, 0, 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, 62, 0, 1, -1))
221 # No check for upper-bound day of week;
222 # value forced into range by a ``% 7`` calculation.
223 # Start check at -2 since gettmarg() increments value before taking
224 # modulo.
Florent Xicluna49ce0682011-11-01 12:56:14 +0100225 self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)),
226 func((1900, 1, 1, 0, 0, 0, +6, 1, -1)))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000227 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000228 (1900, 1, 1, 0, 0, 0, -2, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000229 # Check day of the year [1, 366] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100230 func((1900, 1, 1, 0, 0, 0, 0, 0, -1))
231 func((1900, 1, 1, 0, 0, 0, 0, 366, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000232 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000233 (1900, 1, 1, 0, 0, 0, 0, -1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000234 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000235 (1900, 1, 1, 0, 0, 0, 0, 367, -1))
Brett Cannond1080a32004-03-02 04:38:10 +0000236
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000237 def test_strftime_bounding_check(self):
238 self._bounds_checking(lambda tup: time.strftime('', tup))
239
Steve Dowere5b58952015-09-06 19:20:51 -0700240 def test_strftime_format_check(self):
241 # Test that strftime does not crash on invalid format strings
242 # that may trigger a buffer overread. When not triggered,
243 # strftime may succeed or raise ValueError depending on
244 # the platform.
245 for x in [ '', 'A', '%A', '%AA' ]:
246 for y in range(0x0, 0x10):
247 for z in [ '%', 'A%', 'AA%', '%A%', 'A%A%', '%#' ]:
248 try:
249 time.strftime(x * y + z)
250 except ValueError:
251 pass
252
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000253 def test_default_values_for_zero(self):
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400254 # Make sure that using all zeros uses the proper default
255 # values. No test for daylight savings since strftime() does
256 # not change output based on its value and no test for year
257 # because systems vary in their support for year 0.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000258 expected = "2000 01 01 00 00 00 1 001"
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000259 with support.check_warnings():
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400260 result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000261 self.assertEqual(expected, result)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000262
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000263 def test_strptime(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000264 # Should be able to go round-trip from strftime to strptime without
Andrew Svetlov737fb892012-12-18 21:14:22 +0200265 # raising an exception.
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000266 tt = time.gmtime(self.t)
267 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
268 'j', 'm', 'M', 'p', 'S',
269 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000270 format = '%' + directive
271 strf_output = time.strftime(format, tt)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000272 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000273 time.strptime(strf_output, format)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000274 except ValueError:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000275 self.fail("conversion specifier %r failed with '%s' input." %
276 (format, strf_output))
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000277
Brett Cannon7f6b4f82009-03-30 21:30:26 +0000278 def test_strptime_bytes(self):
279 # Make sure only strings are accepted as arguments to strptime.
280 self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
281 self.assertRaises(TypeError, time.strptime, '2009', b'%Y')
282
Ezio Melotti0f389082013-04-04 02:09:20 +0300283 def test_strptime_exception_context(self):
284 # check that this doesn't chain exceptions needlessly (see #17572)
285 with self.assertRaises(ValueError) as e:
286 time.strptime('', '%D')
287 self.assertIs(e.exception.__suppress_context__, True)
Serhiy Storchakacdac3022013-11-24 18:15:37 +0200288 # additional check for IndexError branch (issue #19545)
289 with self.assertRaises(ValueError) as e:
290 time.strptime('19', '%Y %')
291 self.assertIs(e.exception.__suppress_context__, True)
Ezio Melotti0f389082013-04-04 02:09:20 +0300292
Fred Drakebc561982001-05-22 17:02:02 +0000293 def test_asctime(self):
294 time.asctime(time.gmtime(self.t))
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000295
296 # Max year is only limited by the size of C int.
Florent Xiclunabceb5282011-11-01 14:11:34 +0100297 for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
298 asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
299 self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
300 self.assertRaises(OverflowError, time.asctime,
301 (TIME_MAXYEAR + 1,) + (0,) * 8)
302 self.assertRaises(OverflowError, time.asctime,
303 (TIME_MINYEAR - 1,) + (0,) * 8)
Fred Drakebc561982001-05-22 17:02:02 +0000304 self.assertRaises(TypeError, time.asctime, 0)
Alexander Belopolskye2dc0822011-01-02 20:48:22 +0000305 self.assertRaises(TypeError, time.asctime, ())
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000306 self.assertRaises(TypeError, time.asctime, (0,) * 10)
Fred Drakebc561982001-05-22 17:02:02 +0000307
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000308 def test_asctime_bounding_check(self):
309 self._bounds_checking(time.asctime)
310
Georg Brandle10608c2011-01-02 22:33:43 +0000311 def test_ctime(self):
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000312 t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
313 self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
314 t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
315 self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000')
Victor Stinner1ac42612014-02-21 09:27:17 +0100316 for year in [-100, 100, 1000, 2000, 2050, 10000]:
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000317 try:
318 testval = time.mktime((year, 1, 10) + (0,)*6)
319 except (ValueError, OverflowError):
320 # If mktime fails, ctime will fail too. This may happen
321 # on some platforms.
322 pass
323 else:
324 self.assertEqual(time.ctime(testval)[20:], str(year))
Georg Brandle10608c2011-01-02 22:33:43 +0000325
Florent Xiclunae54371e2011-11-11 18:59:30 +0100326 @unittest.skipUnless(hasattr(time, "tzset"),
327 "time module has no attribute tzset")
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000328 def test_tzset(self):
Guido van Rossumd2b738e2003-03-15 12:01:52 +0000329
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000330 from os import environ
331
Tim Peters0eadaac2003-04-24 16:02:54 +0000332 # Epoch time of midnight Dec 25th 2002. Never DST in northern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000333 # hemisphere.
Tim Peters0eadaac2003-04-24 16:02:54 +0000334 xmas2002 = 1040774400.0
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000335
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000336 # These formats are correct for 2002, and possibly future years
337 # This format is the 'standard' as documented at:
338 # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
339 # They are also documented in the tzset(3) man page on most Unix
340 # systems.
Tim Peters0eadaac2003-04-24 16:02:54 +0000341 eastern = 'EST+05EDT,M4.1.0,M10.5.0'
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000342 victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
343 utc='UTC+0'
344
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000345 org_TZ = environ.get('TZ',None)
346 try:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000347 # Make sure we can switch to UTC time and results are correct
348 # Note that unknown timezones default to UTC.
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000349 # Note that altzone is undefined in UTC, as there is no DST
350 environ['TZ'] = eastern
351 time.tzset()
352 environ['TZ'] = utc
353 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000354 self.assertEqual(
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000355 time.gmtime(xmas2002), time.localtime(xmas2002)
356 )
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000357 self.assertEqual(time.daylight, 0)
358 self.assertEqual(time.timezone, 0)
359 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000360
361 # Make sure we can switch to US/Eastern
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000362 environ['TZ'] = eastern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000363 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000364 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
365 self.assertEqual(time.tzname, ('EST', 'EDT'))
366 self.assertEqual(len(time.tzname), 2)
367 self.assertEqual(time.daylight, 1)
368 self.assertEqual(time.timezone, 18000)
369 self.assertEqual(time.altzone, 14400)
370 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
371 self.assertEqual(len(time.tzname), 2)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000372
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000373 # Now go to the southern hemisphere.
374 environ['TZ'] = victoria
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000375 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000376 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
Victor Stinner0cd47902011-12-08 00:32:51 +0100377
378 # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100379 # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
380 # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
381 # on some operating systems (e.g. FreeBSD), which is wrong. See for
382 # example this bug:
383 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
Victor Stinner0cd47902011-12-08 00:32:51 +0100384 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100385 self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000386 self.assertEqual(len(time.tzname), 2)
387 self.assertEqual(time.daylight, 1)
388 self.assertEqual(time.timezone, -36000)
389 self.assertEqual(time.altzone, -39600)
390 self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000391
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000392 finally:
393 # Repair TZ environment variable in case any other tests
394 # rely on it.
395 if org_TZ is not None:
396 environ['TZ'] = org_TZ
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000397 elif 'TZ' in environ:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000398 del environ['TZ']
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000399 time.tzset()
Tim Peters0eadaac2003-04-24 16:02:54 +0000400
Tim Peters1b6f7a92004-06-20 02:50:16 +0000401 def test_insane_timestamps(self):
402 # It's possible that some platform maps time_t to double,
403 # and that this test will fail there. This test should
404 # exempt such platforms (provided they return reasonable
405 # results!).
406 for func in time.ctime, time.gmtime, time.localtime:
407 for unreasonable in -1e200, 1e200:
Victor Stinner5d272cc2012-03-13 13:35:55 +0100408 self.assertRaises(OverflowError, func, unreasonable)
Fred Drakebc561982001-05-22 17:02:02 +0000409
Fred Drakef901abd2004-08-03 17:58:55 +0000410 def test_ctime_without_arg(self):
411 # Not sure how to check the values, since the clock could tick
412 # at any time. Make sure these are at least accepted and
413 # don't raise errors.
414 time.ctime()
415 time.ctime(None)
416
417 def test_gmtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000418 gt0 = time.gmtime()
419 gt1 = time.gmtime(None)
420 t0 = time.mktime(gt0)
421 t1 = time.mktime(gt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000422 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000423
424 def test_localtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000425 lt0 = time.localtime()
426 lt1 = time.localtime(None)
427 t0 = time.mktime(lt0)
428 t1 = time.mktime(lt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000429 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000430
Florent Xiclunae54371e2011-11-11 18:59:30 +0100431 def test_mktime(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100432 # Issue #1726687
433 for t in (-2, -1, 0, 1):
Victor Stinner8c8b4e02014-02-21 23:54:32 +0100434 if sys.platform.startswith('aix') and t == -1:
435 # Issue #11188, #19748: mktime() returns -1 on error. On Linux,
436 # the tm_wday field is used as a sentinel () to detect if -1 is
437 # really an error or a valid timestamp. On AIX, tm_wday is
438 # unchanged even on success and so cannot be used as a
439 # sentinel.
440 continue
Florent Xiclunabceb5282011-11-01 14:11:34 +0100441 try:
442 tt = time.localtime(t)
Victor Stinner2cbae982012-01-27 00:50:33 +0100443 except (OverflowError, OSError):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100444 pass
445 else:
446 self.assertEqual(time.mktime(tt), t)
Florent Xiclunae54371e2011-11-11 18:59:30 +0100447
448 # Issue #13309: passing extreme values to mktime() or localtime()
449 # borks the glibc's internal timezone data.
450 @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
451 "disabled because of a bug in glibc. Issue #13309")
452 def test_mktime_error(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100453 # It may not be possible to reliably make mktime return error
454 # on all platfom. This will make sure that no other exception
455 # than OverflowError is raised for an extreme value.
Florent Xiclunae54371e2011-11-11 18:59:30 +0100456 tt = time.gmtime(self.t)
457 tzname = time.strftime('%Z', tt)
458 self.assertNotEqual(tzname, 'LMT')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100459 try:
460 time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
461 except OverflowError:
462 pass
Florent Xiclunae54371e2011-11-11 18:59:30 +0100463 self.assertEqual(time.strftime('%Z', tt), tzname)
Florent Xiclunabceb5282011-11-01 14:11:34 +0100464
Victor Stinnerec895392012-04-29 02:41:27 +0200465 def test_monotonic(self):
Victor Stinner6c861812013-11-23 00:15:27 +0100466 # monotonic() should not go backward
467 times = [time.monotonic() for n in range(100)]
468 t1 = times[0]
469 for t2 in times[1:]:
470 self.assertGreaterEqual(t2, t1, "times=%s" % times)
471 t1 = t2
472
473 # monotonic() includes time elapsed during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200474 t1 = time.monotonic()
Victor Stinnera9c99a62013-07-03 23:07:37 +0200475 time.sleep(0.5)
Victor Stinnerec895392012-04-29 02:41:27 +0200476 t2 = time.monotonic()
Victor Stinner2dd254d2012-01-20 02:24:18 +0100477 dt = t2 - t1
Victor Stinner8b302012012-02-07 23:29:46 +0100478 self.assertGreater(t2, t1)
Zachary Ware487aedb2014-01-02 09:41:10 -0600479 # Issue #20101: On some Windows machines, dt may be slightly low
480 self.assertTrue(0.45 <= dt <= 1.0, dt)
Antoine Pitrou391166f2012-01-18 22:35:21 +0100481
Victor Stinner6c861812013-11-23 00:15:27 +0100482 # monotonic() is a monotonic but non adjustable clock
Victor Stinnerec895392012-04-29 02:41:27 +0200483 info = time.get_clock_info('monotonic')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400484 self.assertTrue(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +0200485 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200486
487 def test_perf_counter(self):
488 time.perf_counter()
489
490 def test_process_time(self):
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200491 # process_time() should not include time spend during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200492 start = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200493 time.sleep(0.100)
Victor Stinnerec895392012-04-29 02:41:27 +0200494 stop = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200495 # use 20 ms because process_time() has usually a resolution of 15 ms
496 # on Windows
497 self.assertLess(stop - start, 0.020)
Victor Stinnerec895392012-04-29 02:41:27 +0200498
Antoine Pitrou4bd41c92017-11-15 22:52:21 +0100499 # process_time() should include CPU time spent in any thread
500 start = time.process_time()
501 busy_wait(0.100)
502 stop = time.process_time()
503 self.assertGreaterEqual(stop - start, 0.020) # machine busy?
504
505 t = threading.Thread(target=busy_wait, args=(0.100,))
506 start = time.process_time()
507 t.start()
508 t.join()
509 stop = time.process_time()
510 self.assertGreaterEqual(stop - start, 0.020) # machine busy?
511
Victor Stinnerec895392012-04-29 02:41:27 +0200512 info = time.get_clock_info('process_time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400513 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200514 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200515
Antoine Pitrou4bd41c92017-11-15 22:52:21 +0100516 def test_thread_time(self):
517 if not hasattr(time, 'thread_time'):
518 if sys.platform.startswith(('linux', 'win')):
519 self.fail("time.thread_time() should be available on %r"
520 % (sys.platform,))
521 else:
522 self.skipTest("need time.thread_time")
523
524 # thread_time() should not include time spend during a sleep
525 start = time.thread_time()
526 time.sleep(0.100)
527 stop = time.thread_time()
528 # use 20 ms because thread_time() has usually a resolution of 15 ms
529 # on Windows
530 self.assertLess(stop - start, 0.020)
531
532 # thread_time() should include CPU time spent in current thread...
533 start = time.thread_time()
534 busy_wait(0.100)
535 stop = time.thread_time()
536 self.assertGreaterEqual(stop - start, 0.020) # machine busy?
537
538 # ...but not in other threads
539 t = threading.Thread(target=busy_wait, args=(0.100,))
540 start = time.thread_time()
541 t.start()
542 t.join()
543 stop = time.thread_time()
544 self.assertLess(stop - start, 0.020)
545
546 info = time.get_clock_info('thread_time')
547 self.assertTrue(info.monotonic)
548 self.assertFalse(info.adjustable)
549
Victor Stinnerec895392012-04-29 02:41:27 +0200550 @unittest.skipUnless(hasattr(time, 'clock_settime'),
551 'need time.clock_settime')
552 def test_monotonic_settime(self):
553 t1 = time.monotonic()
554 realtime = time.clock_gettime(time.CLOCK_REALTIME)
555 # jump backward with an offset of 1 hour
Victor Stinner071eca32012-03-15 01:17:09 +0100556 try:
Victor Stinnerec895392012-04-29 02:41:27 +0200557 time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
558 except PermissionError as err:
559 self.skipTest(err)
560 t2 = time.monotonic()
561 time.clock_settime(time.CLOCK_REALTIME, realtime)
562 # monotonic must not be affected by system clock updates
Victor Stinner071eca32012-03-15 01:17:09 +0100563 self.assertGreaterEqual(t2, t1)
564
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100565 def test_localtime_failure(self):
566 # Issue #13847: check for localtime() failure
Victor Stinner53d36452012-01-27 01:03:25 +0100567 invalid_time_t = None
568 for time_t in (-1, 2**30, 2**33, 2**60):
569 try:
570 time.localtime(time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100571 except OverflowError:
572 self.skipTest("need 64-bit time_t")
Victor Stinner53d36452012-01-27 01:03:25 +0100573 except OSError:
574 invalid_time_t = time_t
575 break
576 if invalid_time_t is None:
577 self.skipTest("unable to find an invalid time_t value")
578
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100579 self.assertRaises(OSError, time.localtime, invalid_time_t)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100580 self.assertRaises(OSError, time.ctime, invalid_time_t)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100581
Han Lee829dacc2017-09-09 08:05:05 +0900582 # Issue #26669: check for localtime() failure
583 self.assertRaises(ValueError, time.localtime, float("nan"))
584 self.assertRaises(ValueError, time.ctime, float("nan"))
585
Victor Stinnerec895392012-04-29 02:41:27 +0200586 def test_get_clock_info(self):
Victor Stinner884d13a2017-10-17 14:46:45 -0700587 clocks = ['clock', 'monotonic', 'perf_counter', 'process_time', 'time']
Victor Stinnerec895392012-04-29 02:41:27 +0200588
589 for name in clocks:
Victor Stinner884d13a2017-10-17 14:46:45 -0700590 if name == 'clock':
591 with self.assertWarns(DeprecationWarning):
592 info = time.get_clock_info('clock')
593 else:
594 info = time.get_clock_info(name)
595
Victor Stinnerec895392012-04-29 02:41:27 +0200596 #self.assertIsInstance(info, dict)
597 self.assertIsInstance(info.implementation, str)
598 self.assertNotEqual(info.implementation, '')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400599 self.assertIsInstance(info.monotonic, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200600 self.assertIsInstance(info.resolution, float)
601 # 0.0 < resolution <= 1.0
602 self.assertGreater(info.resolution, 0.0)
603 self.assertLessEqual(info.resolution, 1.0)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200604 self.assertIsInstance(info.adjustable, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200605
606 self.assertRaises(ValueError, time.get_clock_info, 'xxx')
607
608
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000609class TestLocale(unittest.TestCase):
610 def setUp(self):
611 self.oldloc = locale.setlocale(locale.LC_ALL)
Fred Drake2e2be372001-09-20 21:33:42 +0000612
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000613 def tearDown(self):
614 locale.setlocale(locale.LC_ALL, self.oldloc)
615
Martin v. Löwisa6a9c4d2009-05-30 06:15:30 +0000616 def test_bug_3061(self):
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000617 try:
618 tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
619 except locale.Error:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600620 self.skipTest('could not set locale.LC_ALL to fr_FR')
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000621 # This should not cause an exception
622 time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
623
Victor Stinner73ea29c2011-01-08 01:56:31 +0000624
Victor Stinner73ea29c2011-01-08 01:56:31 +0000625class _TestAsctimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100626 _format = '%d'
627
Victor Stinner73ea29c2011-01-08 01:56:31 +0000628 def yearstr(self, y):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000629 return time.asctime((y,) + (0,) * 8).split()[-1]
Alexander Belopolskya6867252011-01-05 23:00:47 +0000630
Victor Stinner73ea29c2011-01-08 01:56:31 +0000631 def test_large_year(self):
Victor Stinner73691322011-01-08 02:00:24 +0000632 # Check that it doesn't crash for year > 9999
Victor Stinner73ea29c2011-01-08 01:56:31 +0000633 self.assertEqual(self.yearstr(12345), '12345')
634 self.assertEqual(self.yearstr(123456789), '123456789')
635
636class _TestStrftimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100637
638 # Issue 13305: For years < 1000, the value is not always
639 # padded to 4 digits across platforms. The C standard
640 # assumes year >= 1900, so it does not specify the number
641 # of digits.
642
643 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
644 _format = '%04d'
645 else:
646 _format = '%d'
647
Victor Stinner73ea29c2011-01-08 01:56:31 +0000648 def yearstr(self, y):
Florent Xicluna49ce0682011-11-01 12:56:14 +0100649 return time.strftime('%Y', (y,) + (0,) * 8)
650
651 def test_4dyear(self):
652 # Check that we can return the zero padded value.
653 if self._format == '%04d':
654 self.test_year('%04d')
655 else:
656 def year4d(y):
657 return time.strftime('%4Y', (y,) + (0,) * 8)
658 self.test_year('%04d', func=year4d)
659
Florent Xiclunabceb5282011-11-01 14:11:34 +0100660 def skip_if_not_supported(y):
661 msg = "strftime() is limited to [1; 9999] with Visual Studio"
662 # Check that it doesn't crash for year > 9999
663 try:
664 time.strftime('%Y', (y,) + (0,) * 8)
665 except ValueError:
666 cond = False
667 else:
668 cond = True
669 return unittest.skipUnless(cond, msg)
670
671 @skip_if_not_supported(10000)
672 def test_large_year(self):
673 return super().test_large_year()
674
675 @skip_if_not_supported(0)
676 def test_negative(self):
677 return super().test_negative()
678
679 del skip_if_not_supported
680
681
Ezio Melotti3836d702013-04-11 20:29:42 +0300682class _Test4dYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100683 _format = '%d'
684
685 def test_year(self, fmt=None, func=None):
686 fmt = fmt or self._format
687 func = func or self.yearstr
688 self.assertEqual(func(1), fmt % 1)
689 self.assertEqual(func(68), fmt % 68)
690 self.assertEqual(func(69), fmt % 69)
691 self.assertEqual(func(99), fmt % 99)
692 self.assertEqual(func(999), fmt % 999)
693 self.assertEqual(func(9999), fmt % 9999)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000694
695 def test_large_year(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100696 self.assertEqual(self.yearstr(12345), '12345')
Victor Stinner13ed2ea2011-03-21 02:11:01 +0100697 self.assertEqual(self.yearstr(123456789), '123456789')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100698 self.assertEqual(self.yearstr(TIME_MAXYEAR), str(TIME_MAXYEAR))
699 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000700
Victor Stinner301f1212011-01-08 03:06:52 +0000701 def test_negative(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100702 self.assertEqual(self.yearstr(-1), self._format % -1)
Victor Stinner301f1212011-01-08 03:06:52 +0000703 self.assertEqual(self.yearstr(-1234), '-1234')
704 self.assertEqual(self.yearstr(-123456), '-123456')
Florent Xiclunad1bd7f72011-11-01 23:42:05 +0100705 self.assertEqual(self.yearstr(-123456789), str(-123456789))
706 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
Florent Xicluna2fbc1852011-11-02 08:13:43 +0100707 self.assertEqual(self.yearstr(TIME_MINYEAR + 1900), str(TIME_MINYEAR + 1900))
708 # Issue #13312: it may return wrong value for year < TIME_MINYEAR + 1900
709 # Skip the value test, but check that no error is raised
710 self.yearstr(TIME_MINYEAR)
Florent Xiclunae2a732e2011-11-02 01:28:17 +0100711 # self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
Florent Xiclunabceb5282011-11-01 14:11:34 +0100712 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
Victor Stinner301f1212011-01-08 03:06:52 +0000713
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000714
Ezio Melotti3836d702013-04-11 20:29:42 +0300715class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner73ea29c2011-01-08 01:56:31 +0000716 pass
717
Ezio Melotti3836d702013-04-11 20:29:42 +0300718class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner301f1212011-01-08 03:06:52 +0000719 pass
Victor Stinner73ea29c2011-01-08 01:56:31 +0000720
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000721
Victor Stinner643cd682012-03-02 22:54:03 +0100722class TestPytime(unittest.TestCase):
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400723 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
724 def test_localtime_timezone(self):
Victor Stinner643cd682012-03-02 22:54:03 +0100725
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400726 # Get the localtime and examine it for the offset and zone.
727 lt = time.localtime()
728 self.assertTrue(hasattr(lt, "tm_gmtoff"))
729 self.assertTrue(hasattr(lt, "tm_zone"))
730
731 # See if the offset and zone are similar to the module
732 # attributes.
733 if lt.tm_gmtoff is None:
734 self.assertTrue(not hasattr(time, "timezone"))
735 else:
736 self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
737 if lt.tm_zone is None:
738 self.assertTrue(not hasattr(time, "tzname"))
739 else:
740 self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
741
742 # Try and make UNIX times from the localtime and a 9-tuple
743 # created from the localtime. Test to see that the times are
744 # the same.
745 t = time.mktime(lt); t9 = time.mktime(lt[:9])
746 self.assertEqual(t, t9)
747
748 # Make localtimes from the UNIX times and compare them to
749 # the original localtime, thus making a round trip.
750 new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
751 self.assertEqual(new_lt, lt)
752 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
753 self.assertEqual(new_lt.tm_zone, lt.tm_zone)
754 self.assertEqual(new_lt9, lt)
755 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
756 self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
757
758 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
759 def test_strptime_timezone(self):
760 t = time.strptime("UTC", "%Z")
761 self.assertEqual(t.tm_zone, 'UTC')
762 t = time.strptime("+0500", "%z")
763 self.assertEqual(t.tm_gmtoff, 5 * 3600)
764
765 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
766 def test_short_times(self):
767
768 import pickle
769
770 # Load a short time structure using pickle.
771 st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
772 lt = pickle.loads(st)
773 self.assertIs(lt.tm_gmtoff, None)
774 self.assertIs(lt.tm_zone, None)
Victor Stinner643cd682012-03-02 22:54:03 +0100775
Fred Drake2e2be372001-09-20 21:33:42 +0000776
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200777@unittest.skipIf(_testcapi is None, 'need the _testcapi module')
778class CPyTimeTestCase:
Victor Stinneracea9f62015-09-02 10:39:40 +0200779 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200780 Base class to test the C _PyTime_t API.
Victor Stinneracea9f62015-09-02 10:39:40 +0200781 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200782 OVERFLOW_SECONDS = None
783
Victor Stinner4237d342015-09-10 10:10:39 +0200784 def setUp(self):
785 from _testcapi import SIZEOF_TIME_T
786 bits = SIZEOF_TIME_T * 8 - 1
787 self.time_t_min = -2 ** bits
788 self.time_t_max = 2 ** bits - 1
789
790 def time_t_filter(self, seconds):
791 return (self.time_t_min <= seconds <= self.time_t_max)
792
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200793 def _rounding_values(self, use_float):
794 "Build timestamps used to test rounding."
795
796 units = [1, US_TO_NS, MS_TO_NS, SEC_TO_NS]
797 if use_float:
798 # picoseconds are only tested to pytime_converter accepting floats
799 units.append(1e-3)
800
801 values = (
802 # small values
803 1, 2, 5, 7, 123, 456, 1234,
804 # 10^k - 1
805 9,
806 99,
807 999,
808 9999,
809 99999,
810 999999,
811 # test half even rounding near 0.5, 1.5, 2.5, 3.5, 4.5
812 499, 500, 501,
813 1499, 1500, 1501,
814 2500,
815 3500,
816 4500,
817 )
818
819 ns_timestamps = [0]
820 for unit in units:
821 for value in values:
822 ns = value * unit
823 ns_timestamps.extend((-ns, ns))
824 for pow2 in (0, 5, 10, 15, 22, 23, 24, 30, 33):
825 ns = (2 ** pow2) * SEC_TO_NS
826 ns_timestamps.extend((
827 -ns-1, -ns, -ns+1,
828 ns-1, ns, ns+1
829 ))
830 for seconds in (_testcapi.INT_MIN, _testcapi.INT_MAX):
831 ns_timestamps.append(seconds * SEC_TO_NS)
832 if use_float:
Victor Stinner717a32b2016-08-17 11:07:21 +0200833 # numbers with an exact representation in IEEE 754 (base 2)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200834 for pow2 in (3, 7, 10, 15):
835 ns = 2.0 ** (-pow2)
836 ns_timestamps.extend((-ns, ns))
837
838 # seconds close to _PyTime_t type limit
839 ns = (2 ** 63 // SEC_TO_NS) * SEC_TO_NS
840 ns_timestamps.extend((-ns, ns))
841
842 return ns_timestamps
843
844 def _check_rounding(self, pytime_converter, expected_func,
845 use_float, unit_to_sec, value_filter=None):
846
847 def convert_values(ns_timestamps):
848 if use_float:
849 unit_to_ns = SEC_TO_NS / float(unit_to_sec)
850 values = [ns / unit_to_ns for ns in ns_timestamps]
851 else:
852 unit_to_ns = SEC_TO_NS // unit_to_sec
853 values = [ns // unit_to_ns for ns in ns_timestamps]
854
855 if value_filter:
856 values = filter(value_filter, values)
857
858 # remove duplicates and sort
859 return sorted(set(values))
860
861 # test rounding
862 ns_timestamps = self._rounding_values(use_float)
863 valid_values = convert_values(ns_timestamps)
864 for time_rnd, decimal_rnd in ROUNDING_MODES :
865 context = decimal.getcontext()
866 context.rounding = decimal_rnd
867
868 for value in valid_values:
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200869 debug_info = {'value': value, 'rounding': decimal_rnd}
870 try:
871 result = pytime_converter(value, time_rnd)
872 expected = expected_func(value)
873 except Exception as exc:
874 self.fail("Error on timestamp conversion: %s" % debug_info)
875 self.assertEqual(result,
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200876 expected,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200877 debug_info)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200878
879 # test overflow
880 ns = self.OVERFLOW_SECONDS * SEC_TO_NS
881 ns_timestamps = (-ns, ns)
882 overflow_values = convert_values(ns_timestamps)
883 for time_rnd, _ in ROUNDING_MODES :
884 for value in overflow_values:
Victor Stinnerc60542b2015-09-10 15:55:07 +0200885 debug_info = {'value': value, 'rounding': time_rnd}
886 with self.assertRaises(OverflowError, msg=debug_info):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200887 pytime_converter(value, time_rnd)
888
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200889 def check_int_rounding(self, pytime_converter, expected_func,
890 unit_to_sec=1, value_filter=None):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200891 self._check_rounding(pytime_converter, expected_func,
892 False, unit_to_sec, value_filter)
893
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200894 def check_float_rounding(self, pytime_converter, expected_func,
895 unit_to_sec=1, value_filter=None):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200896 self._check_rounding(pytime_converter, expected_func,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200897 True, unit_to_sec, value_filter)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200898
899 def decimal_round(self, x):
900 d = decimal.Decimal(x)
901 d = d.quantize(1)
902 return int(d)
903
904
905class TestCPyTime(CPyTimeTestCase, unittest.TestCase):
906 """
907 Test the C _PyTime_t API.
908 """
909 # _PyTime_t is a 64-bit signed integer
910 OVERFLOW_SECONDS = math.ceil((2**63 + 1) / SEC_TO_NS)
911
Victor Stinner13019fd2015-04-03 13:10:54 +0200912 def test_FromSeconds(self):
913 from _testcapi import PyTime_FromSeconds
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200914
915 # PyTime_FromSeconds() expects a C int, reject values out of range
916 def c_int_filter(secs):
917 return (_testcapi.INT_MIN <= secs <= _testcapi.INT_MAX)
918
919 self.check_int_rounding(lambda secs, rnd: PyTime_FromSeconds(secs),
920 lambda secs: secs * SEC_TO_NS,
921 value_filter=c_int_filter)
Victor Stinner13019fd2015-04-03 13:10:54 +0200922
Han Lee829dacc2017-09-09 08:05:05 +0900923 # test nan
924 for time_rnd, _ in ROUNDING_MODES:
925 with self.assertRaises(TypeError):
926 PyTime_FromSeconds(float('nan'))
927
Victor Stinner992c43f2015-03-27 17:12:45 +0100928 def test_FromSecondsObject(self):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100929 from _testcapi import PyTime_FromSecondsObject
Victor Stinner992c43f2015-03-27 17:12:45 +0100930
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200931 self.check_int_rounding(
932 PyTime_FromSecondsObject,
933 lambda secs: secs * SEC_TO_NS)
Victor Stinner992c43f2015-03-27 17:12:45 +0100934
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200935 self.check_float_rounding(
936 PyTime_FromSecondsObject,
937 lambda ns: self.decimal_round(ns * SEC_TO_NS))
Victor Stinner4bfb4602015-03-27 22:27:24 +0100938
Han Lee829dacc2017-09-09 08:05:05 +0900939 # test nan
940 for time_rnd, _ in ROUNDING_MODES:
941 with self.assertRaises(ValueError):
942 PyTime_FromSecondsObject(float('nan'), time_rnd)
943
Victor Stinner4bfb4602015-03-27 22:27:24 +0100944 def test_AsSecondsDouble(self):
945 from _testcapi import PyTime_AsSecondsDouble
946
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200947 def float_converter(ns):
948 if abs(ns) % SEC_TO_NS == 0:
949 return float(ns // SEC_TO_NS)
950 else:
951 return float(ns) / SEC_TO_NS
Victor Stinner4bfb4602015-03-27 22:27:24 +0100952
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200953 self.check_int_rounding(lambda ns, rnd: PyTime_AsSecondsDouble(ns),
954 float_converter,
955 NS_TO_SEC)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100956
Han Lee829dacc2017-09-09 08:05:05 +0900957 # test nan
958 for time_rnd, _ in ROUNDING_MODES:
959 with self.assertRaises(TypeError):
960 PyTime_AsSecondsDouble(float('nan'))
961
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200962 def create_decimal_converter(self, denominator):
963 denom = decimal.Decimal(denominator)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100964
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200965 def converter(value):
966 d = decimal.Decimal(value) / denom
967 return self.decimal_round(d)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100968
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200969 return converter
Victor Stinner4bfb4602015-03-27 22:27:24 +0100970
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200971 def test_AsTimeval(self):
Victor Stinner95e9cef2015-03-28 01:26:47 +0100972 from _testcapi import PyTime_AsTimeval
Victor Stinner95e9cef2015-03-28 01:26:47 +0100973
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200974 us_converter = self.create_decimal_converter(US_TO_NS)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100975
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200976 def timeval_converter(ns):
977 us = us_converter(ns)
978 return divmod(us, SEC_TO_US)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100979
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200980 if sys.platform == 'win32':
981 from _testcapi import LONG_MIN, LONG_MAX
982
983 # On Windows, timeval.tv_sec type is a C long
984 def seconds_filter(secs):
985 return LONG_MIN <= secs <= LONG_MAX
986 else:
Victor Stinner4237d342015-09-10 10:10:39 +0200987 seconds_filter = self.time_t_filter
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200988
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200989 self.check_int_rounding(PyTime_AsTimeval,
990 timeval_converter,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200991 NS_TO_SEC,
992 value_filter=seconds_filter)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100993
Victor Stinner34dc0f42015-03-27 18:19:03 +0100994 @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec'),
995 'need _testcapi.PyTime_AsTimespec')
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200996 def test_AsTimespec(self):
Victor Stinner34dc0f42015-03-27 18:19:03 +0100997 from _testcapi import PyTime_AsTimespec
Victor Stinner34dc0f42015-03-27 18:19:03 +0100998
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200999 def timespec_converter(ns):
1000 return divmod(ns, SEC_TO_NS)
Victor Stinner34dc0f42015-03-27 18:19:03 +01001001
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001002 self.check_int_rounding(lambda ns, rnd: PyTime_AsTimespec(ns),
1003 timespec_converter,
Victor Stinner4237d342015-09-10 10:10:39 +02001004 NS_TO_SEC,
1005 value_filter=self.time_t_filter)
Victor Stinner34dc0f42015-03-27 18:19:03 +01001006
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001007 def test_AsMilliseconds(self):
Victor Stinner62d1c702015-04-01 17:47:07 +02001008 from _testcapi import PyTime_AsMilliseconds
Victor Stinner62d1c702015-04-01 17:47:07 +02001009
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001010 self.check_int_rounding(PyTime_AsMilliseconds,
1011 self.create_decimal_converter(MS_TO_NS),
1012 NS_TO_SEC)
Victor Stinner62d1c702015-04-01 17:47:07 +02001013
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001014 def test_AsMicroseconds(self):
Victor Stinner62d1c702015-04-01 17:47:07 +02001015 from _testcapi import PyTime_AsMicroseconds
Victor Stinner62d1c702015-04-01 17:47:07 +02001016
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001017 self.check_int_rounding(PyTime_AsMicroseconds,
1018 self.create_decimal_converter(US_TO_NS),
1019 NS_TO_SEC)
Victor Stinner62d1c702015-04-01 17:47:07 +02001020
Victor Stinner992c43f2015-03-27 17:12:45 +01001021
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001022class TestOldPyTime(CPyTimeTestCase, unittest.TestCase):
Victor Stinneracea9f62015-09-02 10:39:40 +02001023 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001024 Test the old C _PyTime_t API: _PyTime_ObjectToXXX() functions.
Victor Stinneracea9f62015-09-02 10:39:40 +02001025 """
Victor Stinneracea9f62015-09-02 10:39:40 +02001026
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001027 # time_t is a 32-bit or 64-bit signed integer
1028 OVERFLOW_SECONDS = 2 ** 64
1029
1030 def test_object_to_time_t(self):
Victor Stinneracea9f62015-09-02 10:39:40 +02001031 from _testcapi import pytime_object_to_time_t
1032
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001033 self.check_int_rounding(pytime_object_to_time_t,
Victor Stinner4237d342015-09-10 10:10:39 +02001034 lambda secs: secs,
1035 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001036
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001037 self.check_float_rounding(pytime_object_to_time_t,
Victor Stinner350b5182015-09-10 11:45:06 +02001038 self.decimal_round,
1039 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001040
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001041 def create_converter(self, sec_to_unit):
1042 def converter(secs):
1043 floatpart, intpart = math.modf(secs)
1044 intpart = int(intpart)
1045 floatpart *= sec_to_unit
1046 floatpart = self.decimal_round(floatpart)
1047 if floatpart < 0:
1048 floatpart += sec_to_unit
1049 intpart -= 1
1050 elif floatpart >= sec_to_unit:
1051 floatpart -= sec_to_unit
1052 intpart += 1
1053 return (intpart, floatpart)
1054 return converter
Victor Stinneracea9f62015-09-02 10:39:40 +02001055
Victor Stinneradfefa52015-09-04 23:57:25 +02001056 def test_object_to_timeval(self):
Victor Stinneracea9f62015-09-02 10:39:40 +02001057 from _testcapi import pytime_object_to_timeval
1058
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001059 self.check_int_rounding(pytime_object_to_timeval,
Victor Stinner4237d342015-09-10 10:10:39 +02001060 lambda secs: (secs, 0),
1061 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001062
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001063 self.check_float_rounding(pytime_object_to_timeval,
Victor Stinner350b5182015-09-10 11:45:06 +02001064 self.create_converter(SEC_TO_US),
1065 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001066
Han Lee829dacc2017-09-09 08:05:05 +09001067 # test nan
1068 for time_rnd, _ in ROUNDING_MODES:
1069 with self.assertRaises(ValueError):
1070 pytime_object_to_timeval(float('nan'), time_rnd)
1071
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001072 def test_object_to_timespec(self):
Victor Stinneracea9f62015-09-02 10:39:40 +02001073 from _testcapi import pytime_object_to_timespec
1074
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001075 self.check_int_rounding(pytime_object_to_timespec,
Victor Stinner4237d342015-09-10 10:10:39 +02001076 lambda secs: (secs, 0),
1077 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001078
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001079 self.check_float_rounding(pytime_object_to_timespec,
Victor Stinner350b5182015-09-10 11:45:06 +02001080 self.create_converter(SEC_TO_NS),
1081 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001082
Han Lee829dacc2017-09-09 08:05:05 +09001083 # test nan
1084 for time_rnd, _ in ROUNDING_MODES:
1085 with self.assertRaises(ValueError):
1086 pytime_object_to_timespec(float('nan'), time_rnd)
1087
Victor Stinneracea9f62015-09-02 10:39:40 +02001088
Fred Drake2e2be372001-09-20 21:33:42 +00001089if __name__ == "__main__":
Ezio Melotti3836d702013-04-11 20:29:42 +03001090 unittest.main()