blob: b44646da709ffb99ea45c7e23c8da35453be9263 [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
Fred Drakebc561982001-05-22 17:02:02 +000050class TimeTestCase(unittest.TestCase):
Barry Warsawb0c22321996-12-06 23:30:07 +000051
Fred Drakebc561982001-05-22 17:02:02 +000052 def setUp(self):
53 self.t = time.time()
Barry Warsawb0c22321996-12-06 23:30:07 +000054
Fred Drakebc561982001-05-22 17:02:02 +000055 def test_data_attributes(self):
56 time.altzone
57 time.daylight
58 time.timezone
59 time.tzname
Barry Warsawb0c22321996-12-06 23:30:07 +000060
Victor Stinnerec895392012-04-29 02:41:27 +020061 def test_time(self):
62 time.time()
63 info = time.get_clock_info('time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040064 self.assertFalse(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +020065 self.assertTrue(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020066
Victor Stinnerc29b5852017-11-02 07:28:27 -070067 def test_time_ns_type(self):
68 def check_ns(sec, ns):
69 self.assertIsInstance(ns, int)
70
71 sec_ns = int(sec * 1e9)
72 # tolerate a difference of 50 ms
73 self.assertLess((sec_ns - ns), 50 ** 6, (sec, ns))
74
75 check_ns(time.time(),
76 time.time_ns())
77 check_ns(time.monotonic(),
78 time.monotonic_ns())
79 check_ns(time.perf_counter(),
80 time.perf_counter_ns())
81 check_ns(time.process_time(),
82 time.process_time_ns())
83
84 if hasattr(time, 'clock_gettime'):
85 check_ns(time.clock_gettime(time.CLOCK_REALTIME),
86 time.clock_gettime_ns(time.CLOCK_REALTIME))
87
Fred Drakebc561982001-05-22 17:02:02 +000088 def test_clock(self):
Victor Stinner884d13a2017-10-17 14:46:45 -070089 with self.assertWarns(DeprecationWarning):
90 time.clock()
Barry Warsawb0c22321996-12-06 23:30:07 +000091
Victor Stinner884d13a2017-10-17 14:46:45 -070092 with self.assertWarns(DeprecationWarning):
93 info = time.get_clock_info('clock')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040094 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +020095 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020096
Victor Stinnere0be4232011-10-25 13:06:09 +020097 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
98 'need time.clock_gettime()')
99 def test_clock_realtime(self):
Victor Stinnerc29b5852017-11-02 07:28:27 -0700100 t = time.clock_gettime(time.CLOCK_REALTIME)
101 self.assertIsInstance(t, float)
Victor Stinnere0be4232011-10-25 13:06:09 +0200102
103 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
104 'need time.clock_gettime()')
105 @unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'),
106 'need time.CLOCK_MONOTONIC')
107 def test_clock_monotonic(self):
108 a = time.clock_gettime(time.CLOCK_MONOTONIC)
109 b = time.clock_gettime(time.CLOCK_MONOTONIC)
110 self.assertLessEqual(a, b)
111
pdoxe14679c2017-10-05 00:01:56 -0700112 @unittest.skipUnless(hasattr(time, 'pthread_getcpuclockid'),
113 'need time.pthread_getcpuclockid()')
114 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
115 'need time.clock_gettime()')
pdoxe14679c2017-10-05 00:01:56 -0700116 def test_pthread_getcpuclockid(self):
117 clk_id = time.pthread_getcpuclockid(threading.get_ident())
118 self.assertTrue(type(clk_id) is int)
119 self.assertNotEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
pdoxe14679c2017-10-05 00:01:56 -0700120 t1 = time.clock_gettime(clk_id)
Benjamin Peterson86566702017-10-05 22:50:42 -0700121 t2 = time.clock_gettime(clk_id)
pdoxe14679c2017-10-05 00:01:56 -0700122 self.assertLessEqual(t1, t2)
pdoxe14679c2017-10-05 00:01:56 -0700123
Victor Stinnere0be4232011-10-25 13:06:09 +0200124 @unittest.skipUnless(hasattr(time, 'clock_getres'),
125 'need time.clock_getres()')
126 def test_clock_getres(self):
127 res = time.clock_getres(time.CLOCK_REALTIME)
128 self.assertGreater(res, 0.0)
129 self.assertLessEqual(res, 1.0)
130
Victor Stinner30d79472012-04-03 00:45:07 +0200131 @unittest.skipUnless(hasattr(time, 'clock_settime'),
132 'need time.clock_settime()')
133 def test_clock_settime(self):
134 t = time.clock_gettime(time.CLOCK_REALTIME)
135 try:
136 time.clock_settime(time.CLOCK_REALTIME, t)
137 except PermissionError:
138 pass
139
Victor Stinnerec895392012-04-29 02:41:27 +0200140 if hasattr(time, 'CLOCK_MONOTONIC'):
141 self.assertRaises(OSError,
142 time.clock_settime, time.CLOCK_MONOTONIC, 0)
Victor Stinner30d79472012-04-03 00:45:07 +0200143
Fred Drakebc561982001-05-22 17:02:02 +0000144 def test_conversions(self):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000145 self.assertEqual(time.ctime(self.t),
146 time.asctime(time.localtime(self.t)))
147 self.assertEqual(int(time.mktime(time.localtime(self.t))),
148 int(self.t))
Fred Drakebc561982001-05-22 17:02:02 +0000149
150 def test_sleep(self):
Victor Stinner7f53a502011-07-05 22:00:25 +0200151 self.assertRaises(ValueError, time.sleep, -2)
152 self.assertRaises(ValueError, time.sleep, -1)
Fred Drakebc561982001-05-22 17:02:02 +0000153 time.sleep(1.2)
154
155 def test_strftime(self):
156 tt = time.gmtime(self.t)
157 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
158 'j', 'm', 'M', 'p', 'S',
159 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
160 format = ' %' + directive
161 try:
162 time.strftime(format, tt)
163 except ValueError:
164 self.fail('conversion specifier: %r failed.' % format)
165
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300166 self.assertRaises(TypeError, time.strftime, b'%S', tt)
167 # embedded null character
168 self.assertRaises(ValueError, time.strftime, '%S\0', tt)
169
Florent Xicluna49ce0682011-11-01 12:56:14 +0100170 def _bounds_checking(self, func):
Brett Cannond1080a32004-03-02 04:38:10 +0000171 # Make sure that strftime() checks the bounds of the various parts
Florent Xicluna49ce0682011-11-01 12:56:14 +0100172 # of the time tuple (0 is valid for *all* values).
Brett Cannond1080a32004-03-02 04:38:10 +0000173
Victor Stinner73ea29c2011-01-08 01:56:31 +0000174 # The year field is tested by other test cases above
175
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000176 # Check month [1, 12] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100177 func((1900, 0, 1, 0, 0, 0, 0, 1, -1))
178 func((1900, 12, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000179 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000180 (1900, -1, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000181 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000182 (1900, 13, 1, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000183 # Check day of month [1, 31] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100184 func((1900, 1, 0, 0, 0, 0, 0, 1, -1))
185 func((1900, 1, 31, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000186 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000187 (1900, 1, -1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000188 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000189 (1900, 1, 32, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000190 # Check hour [0, 23]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100191 func((1900, 1, 1, 23, 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, 1, 1, -1, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000194 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000195 (1900, 1, 1, 24, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000196 # Check minute [0, 59]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100197 func((1900, 1, 1, 0, 59, 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, 1, 0, -1, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000200 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000201 (1900, 1, 1, 0, 60, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000202 # Check second [0, 61]
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000203 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000204 (1900, 1, 1, 0, 0, -1, 0, 1, -1))
205 # C99 only requires allowing for one leap second, but Python's docs say
206 # allow two leap seconds (0..61)
Florent Xicluna49ce0682011-11-01 12:56:14 +0100207 func((1900, 1, 1, 0, 0, 60, 0, 1, -1))
208 func((1900, 1, 1, 0, 0, 61, 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, 0, 62, 0, 1, -1))
211 # No check for upper-bound day of week;
212 # value forced into range by a ``% 7`` calculation.
213 # Start check at -2 since gettmarg() increments value before taking
214 # modulo.
Florent Xicluna49ce0682011-11-01 12:56:14 +0100215 self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)),
216 func((1900, 1, 1, 0, 0, 0, +6, 1, -1)))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000217 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000218 (1900, 1, 1, 0, 0, 0, -2, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000219 # Check day of the year [1, 366] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100220 func((1900, 1, 1, 0, 0, 0, 0, 0, -1))
221 func((1900, 1, 1, 0, 0, 0, 0, 366, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000222 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000223 (1900, 1, 1, 0, 0, 0, 0, -1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000224 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000225 (1900, 1, 1, 0, 0, 0, 0, 367, -1))
Brett Cannond1080a32004-03-02 04:38:10 +0000226
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000227 def test_strftime_bounding_check(self):
228 self._bounds_checking(lambda tup: time.strftime('', tup))
229
Steve Dowere5b58952015-09-06 19:20:51 -0700230 def test_strftime_format_check(self):
231 # Test that strftime does not crash on invalid format strings
232 # that may trigger a buffer overread. When not triggered,
233 # strftime may succeed or raise ValueError depending on
234 # the platform.
235 for x in [ '', 'A', '%A', '%AA' ]:
236 for y in range(0x0, 0x10):
237 for z in [ '%', 'A%', 'AA%', '%A%', 'A%A%', '%#' ]:
238 try:
239 time.strftime(x * y + z)
240 except ValueError:
241 pass
242
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000243 def test_default_values_for_zero(self):
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400244 # Make sure that using all zeros uses the proper default
245 # values. No test for daylight savings since strftime() does
246 # not change output based on its value and no test for year
247 # because systems vary in their support for year 0.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000248 expected = "2000 01 01 00 00 00 1 001"
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000249 with support.check_warnings():
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400250 result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000251 self.assertEqual(expected, result)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000252
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000253 def test_strptime(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000254 # Should be able to go round-trip from strftime to strptime without
Andrew Svetlov737fb892012-12-18 21:14:22 +0200255 # raising an exception.
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000256 tt = time.gmtime(self.t)
257 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
258 'j', 'm', 'M', 'p', 'S',
259 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000260 format = '%' + directive
261 strf_output = time.strftime(format, tt)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000262 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000263 time.strptime(strf_output, format)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000264 except ValueError:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000265 self.fail("conversion specifier %r failed with '%s' input." %
266 (format, strf_output))
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000267
Brett Cannon7f6b4f82009-03-30 21:30:26 +0000268 def test_strptime_bytes(self):
269 # Make sure only strings are accepted as arguments to strptime.
270 self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
271 self.assertRaises(TypeError, time.strptime, '2009', b'%Y')
272
Ezio Melotti0f389082013-04-04 02:09:20 +0300273 def test_strptime_exception_context(self):
274 # check that this doesn't chain exceptions needlessly (see #17572)
275 with self.assertRaises(ValueError) as e:
276 time.strptime('', '%D')
277 self.assertIs(e.exception.__suppress_context__, True)
Serhiy Storchakacdac3022013-11-24 18:15:37 +0200278 # additional check for IndexError branch (issue #19545)
279 with self.assertRaises(ValueError) as e:
280 time.strptime('19', '%Y %')
281 self.assertIs(e.exception.__suppress_context__, True)
Ezio Melotti0f389082013-04-04 02:09:20 +0300282
Fred Drakebc561982001-05-22 17:02:02 +0000283 def test_asctime(self):
284 time.asctime(time.gmtime(self.t))
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000285
286 # Max year is only limited by the size of C int.
Florent Xiclunabceb5282011-11-01 14:11:34 +0100287 for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
288 asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
289 self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
290 self.assertRaises(OverflowError, time.asctime,
291 (TIME_MAXYEAR + 1,) + (0,) * 8)
292 self.assertRaises(OverflowError, time.asctime,
293 (TIME_MINYEAR - 1,) + (0,) * 8)
Fred Drakebc561982001-05-22 17:02:02 +0000294 self.assertRaises(TypeError, time.asctime, 0)
Alexander Belopolskye2dc0822011-01-02 20:48:22 +0000295 self.assertRaises(TypeError, time.asctime, ())
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000296 self.assertRaises(TypeError, time.asctime, (0,) * 10)
Fred Drakebc561982001-05-22 17:02:02 +0000297
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000298 def test_asctime_bounding_check(self):
299 self._bounds_checking(time.asctime)
300
Georg Brandle10608c2011-01-02 22:33:43 +0000301 def test_ctime(self):
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000302 t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
303 self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
304 t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
305 self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000')
Victor Stinner1ac42612014-02-21 09:27:17 +0100306 for year in [-100, 100, 1000, 2000, 2050, 10000]:
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000307 try:
308 testval = time.mktime((year, 1, 10) + (0,)*6)
309 except (ValueError, OverflowError):
310 # If mktime fails, ctime will fail too. This may happen
311 # on some platforms.
312 pass
313 else:
314 self.assertEqual(time.ctime(testval)[20:], str(year))
Georg Brandle10608c2011-01-02 22:33:43 +0000315
Florent Xiclunae54371e2011-11-11 18:59:30 +0100316 @unittest.skipUnless(hasattr(time, "tzset"),
317 "time module has no attribute tzset")
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000318 def test_tzset(self):
Guido van Rossumd2b738e2003-03-15 12:01:52 +0000319
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000320 from os import environ
321
Tim Peters0eadaac2003-04-24 16:02:54 +0000322 # Epoch time of midnight Dec 25th 2002. Never DST in northern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000323 # hemisphere.
Tim Peters0eadaac2003-04-24 16:02:54 +0000324 xmas2002 = 1040774400.0
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000325
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000326 # These formats are correct for 2002, and possibly future years
327 # This format is the 'standard' as documented at:
328 # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
329 # They are also documented in the tzset(3) man page on most Unix
330 # systems.
Tim Peters0eadaac2003-04-24 16:02:54 +0000331 eastern = 'EST+05EDT,M4.1.0,M10.5.0'
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000332 victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
333 utc='UTC+0'
334
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000335 org_TZ = environ.get('TZ',None)
336 try:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000337 # Make sure we can switch to UTC time and results are correct
338 # Note that unknown timezones default to UTC.
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000339 # Note that altzone is undefined in UTC, as there is no DST
340 environ['TZ'] = eastern
341 time.tzset()
342 environ['TZ'] = utc
343 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000344 self.assertEqual(
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000345 time.gmtime(xmas2002), time.localtime(xmas2002)
346 )
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000347 self.assertEqual(time.daylight, 0)
348 self.assertEqual(time.timezone, 0)
349 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000350
351 # Make sure we can switch to US/Eastern
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000352 environ['TZ'] = eastern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000353 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000354 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
355 self.assertEqual(time.tzname, ('EST', 'EDT'))
356 self.assertEqual(len(time.tzname), 2)
357 self.assertEqual(time.daylight, 1)
358 self.assertEqual(time.timezone, 18000)
359 self.assertEqual(time.altzone, 14400)
360 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
361 self.assertEqual(len(time.tzname), 2)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000362
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000363 # Now go to the southern hemisphere.
364 environ['TZ'] = victoria
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000365 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000366 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
Victor Stinner0cd47902011-12-08 00:32:51 +0100367
368 # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100369 # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
370 # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
371 # on some operating systems (e.g. FreeBSD), which is wrong. See for
372 # example this bug:
373 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
Victor Stinner0cd47902011-12-08 00:32:51 +0100374 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100375 self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000376 self.assertEqual(len(time.tzname), 2)
377 self.assertEqual(time.daylight, 1)
378 self.assertEqual(time.timezone, -36000)
379 self.assertEqual(time.altzone, -39600)
380 self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000381
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000382 finally:
383 # Repair TZ environment variable in case any other tests
384 # rely on it.
385 if org_TZ is not None:
386 environ['TZ'] = org_TZ
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000387 elif 'TZ' in environ:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000388 del environ['TZ']
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000389 time.tzset()
Tim Peters0eadaac2003-04-24 16:02:54 +0000390
Tim Peters1b6f7a92004-06-20 02:50:16 +0000391 def test_insane_timestamps(self):
392 # It's possible that some platform maps time_t to double,
393 # and that this test will fail there. This test should
394 # exempt such platforms (provided they return reasonable
395 # results!).
396 for func in time.ctime, time.gmtime, time.localtime:
397 for unreasonable in -1e200, 1e200:
Victor Stinner5d272cc2012-03-13 13:35:55 +0100398 self.assertRaises(OverflowError, func, unreasonable)
Fred Drakebc561982001-05-22 17:02:02 +0000399
Fred Drakef901abd2004-08-03 17:58:55 +0000400 def test_ctime_without_arg(self):
401 # Not sure how to check the values, since the clock could tick
402 # at any time. Make sure these are at least accepted and
403 # don't raise errors.
404 time.ctime()
405 time.ctime(None)
406
407 def test_gmtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000408 gt0 = time.gmtime()
409 gt1 = time.gmtime(None)
410 t0 = time.mktime(gt0)
411 t1 = time.mktime(gt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000412 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000413
414 def test_localtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000415 lt0 = time.localtime()
416 lt1 = time.localtime(None)
417 t0 = time.mktime(lt0)
418 t1 = time.mktime(lt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000419 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000420
Florent Xiclunae54371e2011-11-11 18:59:30 +0100421 def test_mktime(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100422 # Issue #1726687
423 for t in (-2, -1, 0, 1):
Victor Stinner8c8b4e02014-02-21 23:54:32 +0100424 if sys.platform.startswith('aix') and t == -1:
425 # Issue #11188, #19748: mktime() returns -1 on error. On Linux,
426 # the tm_wday field is used as a sentinel () to detect if -1 is
427 # really an error or a valid timestamp. On AIX, tm_wday is
428 # unchanged even on success and so cannot be used as a
429 # sentinel.
430 continue
Florent Xiclunabceb5282011-11-01 14:11:34 +0100431 try:
432 tt = time.localtime(t)
Victor Stinner2cbae982012-01-27 00:50:33 +0100433 except (OverflowError, OSError):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100434 pass
435 else:
436 self.assertEqual(time.mktime(tt), t)
Florent Xiclunae54371e2011-11-11 18:59:30 +0100437
438 # Issue #13309: passing extreme values to mktime() or localtime()
439 # borks the glibc's internal timezone data.
440 @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
441 "disabled because of a bug in glibc. Issue #13309")
442 def test_mktime_error(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100443 # It may not be possible to reliably make mktime return error
444 # on all platfom. This will make sure that no other exception
445 # than OverflowError is raised for an extreme value.
Florent Xiclunae54371e2011-11-11 18:59:30 +0100446 tt = time.gmtime(self.t)
447 tzname = time.strftime('%Z', tt)
448 self.assertNotEqual(tzname, 'LMT')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100449 try:
450 time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
451 except OverflowError:
452 pass
Florent Xiclunae54371e2011-11-11 18:59:30 +0100453 self.assertEqual(time.strftime('%Z', tt), tzname)
Florent Xiclunabceb5282011-11-01 14:11:34 +0100454
Victor Stinnerec895392012-04-29 02:41:27 +0200455 def test_monotonic(self):
Victor Stinner6c861812013-11-23 00:15:27 +0100456 # monotonic() should not go backward
457 times = [time.monotonic() for n in range(100)]
458 t1 = times[0]
459 for t2 in times[1:]:
460 self.assertGreaterEqual(t2, t1, "times=%s" % times)
461 t1 = t2
462
463 # monotonic() includes time elapsed during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200464 t1 = time.monotonic()
Victor Stinnera9c99a62013-07-03 23:07:37 +0200465 time.sleep(0.5)
Victor Stinnerec895392012-04-29 02:41:27 +0200466 t2 = time.monotonic()
Victor Stinner2dd254d2012-01-20 02:24:18 +0100467 dt = t2 - t1
Victor Stinner8b302012012-02-07 23:29:46 +0100468 self.assertGreater(t2, t1)
Zachary Ware487aedb2014-01-02 09:41:10 -0600469 # Issue #20101: On some Windows machines, dt may be slightly low
470 self.assertTrue(0.45 <= dt <= 1.0, dt)
Antoine Pitrou391166f2012-01-18 22:35:21 +0100471
Victor Stinner6c861812013-11-23 00:15:27 +0100472 # monotonic() is a monotonic but non adjustable clock
Victor Stinnerec895392012-04-29 02:41:27 +0200473 info = time.get_clock_info('monotonic')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400474 self.assertTrue(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +0200475 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200476
477 def test_perf_counter(self):
478 time.perf_counter()
479
480 def test_process_time(self):
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200481 # process_time() should not include time spend during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200482 start = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200483 time.sleep(0.100)
Victor Stinnerec895392012-04-29 02:41:27 +0200484 stop = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200485 # use 20 ms because process_time() has usually a resolution of 15 ms
486 # on Windows
487 self.assertLess(stop - start, 0.020)
Victor Stinnerec895392012-04-29 02:41:27 +0200488
489 info = time.get_clock_info('process_time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400490 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200491 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200492
Victor Stinnerec895392012-04-29 02:41:27 +0200493 @unittest.skipUnless(hasattr(time, 'clock_settime'),
494 'need time.clock_settime')
495 def test_monotonic_settime(self):
496 t1 = time.monotonic()
497 realtime = time.clock_gettime(time.CLOCK_REALTIME)
498 # jump backward with an offset of 1 hour
Victor Stinner071eca32012-03-15 01:17:09 +0100499 try:
Victor Stinnerec895392012-04-29 02:41:27 +0200500 time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
501 except PermissionError as err:
502 self.skipTest(err)
503 t2 = time.monotonic()
504 time.clock_settime(time.CLOCK_REALTIME, realtime)
505 # monotonic must not be affected by system clock updates
Victor Stinner071eca32012-03-15 01:17:09 +0100506 self.assertGreaterEqual(t2, t1)
507
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100508 def test_localtime_failure(self):
509 # Issue #13847: check for localtime() failure
Victor Stinner53d36452012-01-27 01:03:25 +0100510 invalid_time_t = None
511 for time_t in (-1, 2**30, 2**33, 2**60):
512 try:
513 time.localtime(time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100514 except OverflowError:
515 self.skipTest("need 64-bit time_t")
Victor Stinner53d36452012-01-27 01:03:25 +0100516 except OSError:
517 invalid_time_t = time_t
518 break
519 if invalid_time_t is None:
520 self.skipTest("unable to find an invalid time_t value")
521
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100522 self.assertRaises(OSError, time.localtime, invalid_time_t)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100523 self.assertRaises(OSError, time.ctime, invalid_time_t)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100524
Han Lee829dacc2017-09-09 08:05:05 +0900525 # Issue #26669: check for localtime() failure
526 self.assertRaises(ValueError, time.localtime, float("nan"))
527 self.assertRaises(ValueError, time.ctime, float("nan"))
528
Victor Stinnerec895392012-04-29 02:41:27 +0200529 def test_get_clock_info(self):
Victor Stinner884d13a2017-10-17 14:46:45 -0700530 clocks = ['clock', 'monotonic', 'perf_counter', 'process_time', 'time']
Victor Stinnerec895392012-04-29 02:41:27 +0200531
532 for name in clocks:
Victor Stinner884d13a2017-10-17 14:46:45 -0700533 if name == 'clock':
534 with self.assertWarns(DeprecationWarning):
535 info = time.get_clock_info('clock')
536 else:
537 info = time.get_clock_info(name)
538
Victor Stinnerec895392012-04-29 02:41:27 +0200539 #self.assertIsInstance(info, dict)
540 self.assertIsInstance(info.implementation, str)
541 self.assertNotEqual(info.implementation, '')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400542 self.assertIsInstance(info.monotonic, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200543 self.assertIsInstance(info.resolution, float)
544 # 0.0 < resolution <= 1.0
545 self.assertGreater(info.resolution, 0.0)
546 self.assertLessEqual(info.resolution, 1.0)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200547 self.assertIsInstance(info.adjustable, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200548
549 self.assertRaises(ValueError, time.get_clock_info, 'xxx')
550
551
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000552class TestLocale(unittest.TestCase):
553 def setUp(self):
554 self.oldloc = locale.setlocale(locale.LC_ALL)
Fred Drake2e2be372001-09-20 21:33:42 +0000555
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000556 def tearDown(self):
557 locale.setlocale(locale.LC_ALL, self.oldloc)
558
Martin v. Löwisa6a9c4d2009-05-30 06:15:30 +0000559 def test_bug_3061(self):
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000560 try:
561 tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
562 except locale.Error:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600563 self.skipTest('could not set locale.LC_ALL to fr_FR')
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000564 # This should not cause an exception
565 time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
566
Victor Stinner73ea29c2011-01-08 01:56:31 +0000567
Victor Stinner73ea29c2011-01-08 01:56:31 +0000568class _TestAsctimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100569 _format = '%d'
570
Victor Stinner73ea29c2011-01-08 01:56:31 +0000571 def yearstr(self, y):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000572 return time.asctime((y,) + (0,) * 8).split()[-1]
Alexander Belopolskya6867252011-01-05 23:00:47 +0000573
Victor Stinner73ea29c2011-01-08 01:56:31 +0000574 def test_large_year(self):
Victor Stinner73691322011-01-08 02:00:24 +0000575 # Check that it doesn't crash for year > 9999
Victor Stinner73ea29c2011-01-08 01:56:31 +0000576 self.assertEqual(self.yearstr(12345), '12345')
577 self.assertEqual(self.yearstr(123456789), '123456789')
578
579class _TestStrftimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100580
581 # Issue 13305: For years < 1000, the value is not always
582 # padded to 4 digits across platforms. The C standard
583 # assumes year >= 1900, so it does not specify the number
584 # of digits.
585
586 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
587 _format = '%04d'
588 else:
589 _format = '%d'
590
Victor Stinner73ea29c2011-01-08 01:56:31 +0000591 def yearstr(self, y):
Florent Xicluna49ce0682011-11-01 12:56:14 +0100592 return time.strftime('%Y', (y,) + (0,) * 8)
593
594 def test_4dyear(self):
595 # Check that we can return the zero padded value.
596 if self._format == '%04d':
597 self.test_year('%04d')
598 else:
599 def year4d(y):
600 return time.strftime('%4Y', (y,) + (0,) * 8)
601 self.test_year('%04d', func=year4d)
602
Florent Xiclunabceb5282011-11-01 14:11:34 +0100603 def skip_if_not_supported(y):
604 msg = "strftime() is limited to [1; 9999] with Visual Studio"
605 # Check that it doesn't crash for year > 9999
606 try:
607 time.strftime('%Y', (y,) + (0,) * 8)
608 except ValueError:
609 cond = False
610 else:
611 cond = True
612 return unittest.skipUnless(cond, msg)
613
614 @skip_if_not_supported(10000)
615 def test_large_year(self):
616 return super().test_large_year()
617
618 @skip_if_not_supported(0)
619 def test_negative(self):
620 return super().test_negative()
621
622 del skip_if_not_supported
623
624
Ezio Melotti3836d702013-04-11 20:29:42 +0300625class _Test4dYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100626 _format = '%d'
627
628 def test_year(self, fmt=None, func=None):
629 fmt = fmt or self._format
630 func = func or self.yearstr
631 self.assertEqual(func(1), fmt % 1)
632 self.assertEqual(func(68), fmt % 68)
633 self.assertEqual(func(69), fmt % 69)
634 self.assertEqual(func(99), fmt % 99)
635 self.assertEqual(func(999), fmt % 999)
636 self.assertEqual(func(9999), fmt % 9999)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000637
638 def test_large_year(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100639 self.assertEqual(self.yearstr(12345), '12345')
Victor Stinner13ed2ea2011-03-21 02:11:01 +0100640 self.assertEqual(self.yearstr(123456789), '123456789')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100641 self.assertEqual(self.yearstr(TIME_MAXYEAR), str(TIME_MAXYEAR))
642 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000643
Victor Stinner301f1212011-01-08 03:06:52 +0000644 def test_negative(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100645 self.assertEqual(self.yearstr(-1), self._format % -1)
Victor Stinner301f1212011-01-08 03:06:52 +0000646 self.assertEqual(self.yearstr(-1234), '-1234')
647 self.assertEqual(self.yearstr(-123456), '-123456')
Florent Xiclunad1bd7f72011-11-01 23:42:05 +0100648 self.assertEqual(self.yearstr(-123456789), str(-123456789))
649 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
Florent Xicluna2fbc1852011-11-02 08:13:43 +0100650 self.assertEqual(self.yearstr(TIME_MINYEAR + 1900), str(TIME_MINYEAR + 1900))
651 # Issue #13312: it may return wrong value for year < TIME_MINYEAR + 1900
652 # Skip the value test, but check that no error is raised
653 self.yearstr(TIME_MINYEAR)
Florent Xiclunae2a732e2011-11-02 01:28:17 +0100654 # self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
Florent Xiclunabceb5282011-11-01 14:11:34 +0100655 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
Victor Stinner301f1212011-01-08 03:06:52 +0000656
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000657
Ezio Melotti3836d702013-04-11 20:29:42 +0300658class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner73ea29c2011-01-08 01:56:31 +0000659 pass
660
Ezio Melotti3836d702013-04-11 20:29:42 +0300661class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner301f1212011-01-08 03:06:52 +0000662 pass
Victor Stinner73ea29c2011-01-08 01:56:31 +0000663
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000664
Victor Stinner643cd682012-03-02 22:54:03 +0100665class TestPytime(unittest.TestCase):
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400666 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
667 def test_localtime_timezone(self):
Victor Stinner643cd682012-03-02 22:54:03 +0100668
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400669 # Get the localtime and examine it for the offset and zone.
670 lt = time.localtime()
671 self.assertTrue(hasattr(lt, "tm_gmtoff"))
672 self.assertTrue(hasattr(lt, "tm_zone"))
673
674 # See if the offset and zone are similar to the module
675 # attributes.
676 if lt.tm_gmtoff is None:
677 self.assertTrue(not hasattr(time, "timezone"))
678 else:
679 self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
680 if lt.tm_zone is None:
681 self.assertTrue(not hasattr(time, "tzname"))
682 else:
683 self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
684
685 # Try and make UNIX times from the localtime and a 9-tuple
686 # created from the localtime. Test to see that the times are
687 # the same.
688 t = time.mktime(lt); t9 = time.mktime(lt[:9])
689 self.assertEqual(t, t9)
690
691 # Make localtimes from the UNIX times and compare them to
692 # the original localtime, thus making a round trip.
693 new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
694 self.assertEqual(new_lt, lt)
695 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
696 self.assertEqual(new_lt.tm_zone, lt.tm_zone)
697 self.assertEqual(new_lt9, lt)
698 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
699 self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
700
701 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
702 def test_strptime_timezone(self):
703 t = time.strptime("UTC", "%Z")
704 self.assertEqual(t.tm_zone, 'UTC')
705 t = time.strptime("+0500", "%z")
706 self.assertEqual(t.tm_gmtoff, 5 * 3600)
707
708 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
709 def test_short_times(self):
710
711 import pickle
712
713 # Load a short time structure using pickle.
714 st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
715 lt = pickle.loads(st)
716 self.assertIs(lt.tm_gmtoff, None)
717 self.assertIs(lt.tm_zone, None)
Victor Stinner643cd682012-03-02 22:54:03 +0100718
Fred Drake2e2be372001-09-20 21:33:42 +0000719
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200720@unittest.skipIf(_testcapi is None, 'need the _testcapi module')
721class CPyTimeTestCase:
Victor Stinneracea9f62015-09-02 10:39:40 +0200722 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200723 Base class to test the C _PyTime_t API.
Victor Stinneracea9f62015-09-02 10:39:40 +0200724 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200725 OVERFLOW_SECONDS = None
726
Victor Stinner4237d342015-09-10 10:10:39 +0200727 def setUp(self):
728 from _testcapi import SIZEOF_TIME_T
729 bits = SIZEOF_TIME_T * 8 - 1
730 self.time_t_min = -2 ** bits
731 self.time_t_max = 2 ** bits - 1
732
733 def time_t_filter(self, seconds):
734 return (self.time_t_min <= seconds <= self.time_t_max)
735
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200736 def _rounding_values(self, use_float):
737 "Build timestamps used to test rounding."
738
739 units = [1, US_TO_NS, MS_TO_NS, SEC_TO_NS]
740 if use_float:
741 # picoseconds are only tested to pytime_converter accepting floats
742 units.append(1e-3)
743
744 values = (
745 # small values
746 1, 2, 5, 7, 123, 456, 1234,
747 # 10^k - 1
748 9,
749 99,
750 999,
751 9999,
752 99999,
753 999999,
754 # test half even rounding near 0.5, 1.5, 2.5, 3.5, 4.5
755 499, 500, 501,
756 1499, 1500, 1501,
757 2500,
758 3500,
759 4500,
760 )
761
762 ns_timestamps = [0]
763 for unit in units:
764 for value in values:
765 ns = value * unit
766 ns_timestamps.extend((-ns, ns))
767 for pow2 in (0, 5, 10, 15, 22, 23, 24, 30, 33):
768 ns = (2 ** pow2) * SEC_TO_NS
769 ns_timestamps.extend((
770 -ns-1, -ns, -ns+1,
771 ns-1, ns, ns+1
772 ))
773 for seconds in (_testcapi.INT_MIN, _testcapi.INT_MAX):
774 ns_timestamps.append(seconds * SEC_TO_NS)
775 if use_float:
Victor Stinner717a32b2016-08-17 11:07:21 +0200776 # numbers with an exact representation in IEEE 754 (base 2)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200777 for pow2 in (3, 7, 10, 15):
778 ns = 2.0 ** (-pow2)
779 ns_timestamps.extend((-ns, ns))
780
781 # seconds close to _PyTime_t type limit
782 ns = (2 ** 63 // SEC_TO_NS) * SEC_TO_NS
783 ns_timestamps.extend((-ns, ns))
784
785 return ns_timestamps
786
787 def _check_rounding(self, pytime_converter, expected_func,
788 use_float, unit_to_sec, value_filter=None):
789
790 def convert_values(ns_timestamps):
791 if use_float:
792 unit_to_ns = SEC_TO_NS / float(unit_to_sec)
793 values = [ns / unit_to_ns for ns in ns_timestamps]
794 else:
795 unit_to_ns = SEC_TO_NS // unit_to_sec
796 values = [ns // unit_to_ns for ns in ns_timestamps]
797
798 if value_filter:
799 values = filter(value_filter, values)
800
801 # remove duplicates and sort
802 return sorted(set(values))
803
804 # test rounding
805 ns_timestamps = self._rounding_values(use_float)
806 valid_values = convert_values(ns_timestamps)
807 for time_rnd, decimal_rnd in ROUNDING_MODES :
808 context = decimal.getcontext()
809 context.rounding = decimal_rnd
810
811 for value in valid_values:
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200812 debug_info = {'value': value, 'rounding': decimal_rnd}
813 try:
814 result = pytime_converter(value, time_rnd)
815 expected = expected_func(value)
816 except Exception as exc:
817 self.fail("Error on timestamp conversion: %s" % debug_info)
818 self.assertEqual(result,
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200819 expected,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200820 debug_info)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200821
822 # test overflow
823 ns = self.OVERFLOW_SECONDS * SEC_TO_NS
824 ns_timestamps = (-ns, ns)
825 overflow_values = convert_values(ns_timestamps)
826 for time_rnd, _ in ROUNDING_MODES :
827 for value in overflow_values:
Victor Stinnerc60542b2015-09-10 15:55:07 +0200828 debug_info = {'value': value, 'rounding': time_rnd}
829 with self.assertRaises(OverflowError, msg=debug_info):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200830 pytime_converter(value, time_rnd)
831
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200832 def check_int_rounding(self, pytime_converter, expected_func,
833 unit_to_sec=1, value_filter=None):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200834 self._check_rounding(pytime_converter, expected_func,
835 False, unit_to_sec, value_filter)
836
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200837 def check_float_rounding(self, pytime_converter, expected_func,
838 unit_to_sec=1, value_filter=None):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200839 self._check_rounding(pytime_converter, expected_func,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200840 True, unit_to_sec, value_filter)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200841
842 def decimal_round(self, x):
843 d = decimal.Decimal(x)
844 d = d.quantize(1)
845 return int(d)
846
847
848class TestCPyTime(CPyTimeTestCase, unittest.TestCase):
849 """
850 Test the C _PyTime_t API.
851 """
852 # _PyTime_t is a 64-bit signed integer
853 OVERFLOW_SECONDS = math.ceil((2**63 + 1) / SEC_TO_NS)
854
Victor Stinner13019fd2015-04-03 13:10:54 +0200855 def test_FromSeconds(self):
856 from _testcapi import PyTime_FromSeconds
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200857
858 # PyTime_FromSeconds() expects a C int, reject values out of range
859 def c_int_filter(secs):
860 return (_testcapi.INT_MIN <= secs <= _testcapi.INT_MAX)
861
862 self.check_int_rounding(lambda secs, rnd: PyTime_FromSeconds(secs),
863 lambda secs: secs * SEC_TO_NS,
864 value_filter=c_int_filter)
Victor Stinner13019fd2015-04-03 13:10:54 +0200865
Han Lee829dacc2017-09-09 08:05:05 +0900866 # test nan
867 for time_rnd, _ in ROUNDING_MODES:
868 with self.assertRaises(TypeError):
869 PyTime_FromSeconds(float('nan'))
870
Victor Stinner992c43f2015-03-27 17:12:45 +0100871 def test_FromSecondsObject(self):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100872 from _testcapi import PyTime_FromSecondsObject
Victor Stinner992c43f2015-03-27 17:12:45 +0100873
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200874 self.check_int_rounding(
875 PyTime_FromSecondsObject,
876 lambda secs: secs * SEC_TO_NS)
Victor Stinner992c43f2015-03-27 17:12:45 +0100877
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200878 self.check_float_rounding(
879 PyTime_FromSecondsObject,
880 lambda ns: self.decimal_round(ns * SEC_TO_NS))
Victor Stinner4bfb4602015-03-27 22:27:24 +0100881
Han Lee829dacc2017-09-09 08:05:05 +0900882 # test nan
883 for time_rnd, _ in ROUNDING_MODES:
884 with self.assertRaises(ValueError):
885 PyTime_FromSecondsObject(float('nan'), time_rnd)
886
Victor Stinner4bfb4602015-03-27 22:27:24 +0100887 def test_AsSecondsDouble(self):
888 from _testcapi import PyTime_AsSecondsDouble
889
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200890 def float_converter(ns):
891 if abs(ns) % SEC_TO_NS == 0:
892 return float(ns // SEC_TO_NS)
893 else:
894 return float(ns) / SEC_TO_NS
Victor Stinner4bfb4602015-03-27 22:27:24 +0100895
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200896 self.check_int_rounding(lambda ns, rnd: PyTime_AsSecondsDouble(ns),
897 float_converter,
898 NS_TO_SEC)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100899
Han Lee829dacc2017-09-09 08:05:05 +0900900 # test nan
901 for time_rnd, _ in ROUNDING_MODES:
902 with self.assertRaises(TypeError):
903 PyTime_AsSecondsDouble(float('nan'))
904
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200905 def create_decimal_converter(self, denominator):
906 denom = decimal.Decimal(denominator)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100907
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200908 def converter(value):
909 d = decimal.Decimal(value) / denom
910 return self.decimal_round(d)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100911
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200912 return converter
Victor Stinner4bfb4602015-03-27 22:27:24 +0100913
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200914 def test_AsTimeval(self):
Victor Stinner95e9cef2015-03-28 01:26:47 +0100915 from _testcapi import PyTime_AsTimeval
Victor Stinner95e9cef2015-03-28 01:26:47 +0100916
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200917 us_converter = self.create_decimal_converter(US_TO_NS)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100918
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200919 def timeval_converter(ns):
920 us = us_converter(ns)
921 return divmod(us, SEC_TO_US)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100922
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200923 if sys.platform == 'win32':
924 from _testcapi import LONG_MIN, LONG_MAX
925
926 # On Windows, timeval.tv_sec type is a C long
927 def seconds_filter(secs):
928 return LONG_MIN <= secs <= LONG_MAX
929 else:
Victor Stinner4237d342015-09-10 10:10:39 +0200930 seconds_filter = self.time_t_filter
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200931
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200932 self.check_int_rounding(PyTime_AsTimeval,
933 timeval_converter,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200934 NS_TO_SEC,
935 value_filter=seconds_filter)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100936
Victor Stinner34dc0f42015-03-27 18:19:03 +0100937 @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec'),
938 'need _testcapi.PyTime_AsTimespec')
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200939 def test_AsTimespec(self):
Victor Stinner34dc0f42015-03-27 18:19:03 +0100940 from _testcapi import PyTime_AsTimespec
Victor Stinner34dc0f42015-03-27 18:19:03 +0100941
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200942 def timespec_converter(ns):
943 return divmod(ns, SEC_TO_NS)
Victor Stinner34dc0f42015-03-27 18:19:03 +0100944
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200945 self.check_int_rounding(lambda ns, rnd: PyTime_AsTimespec(ns),
946 timespec_converter,
Victor Stinner4237d342015-09-10 10:10:39 +0200947 NS_TO_SEC,
948 value_filter=self.time_t_filter)
Victor Stinner34dc0f42015-03-27 18:19:03 +0100949
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200950 def test_AsMilliseconds(self):
Victor Stinner62d1c702015-04-01 17:47:07 +0200951 from _testcapi import PyTime_AsMilliseconds
Victor Stinner62d1c702015-04-01 17:47:07 +0200952
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200953 self.check_int_rounding(PyTime_AsMilliseconds,
954 self.create_decimal_converter(MS_TO_NS),
955 NS_TO_SEC)
Victor Stinner62d1c702015-04-01 17:47:07 +0200956
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200957 def test_AsMicroseconds(self):
Victor Stinner62d1c702015-04-01 17:47:07 +0200958 from _testcapi import PyTime_AsMicroseconds
Victor Stinner62d1c702015-04-01 17:47:07 +0200959
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200960 self.check_int_rounding(PyTime_AsMicroseconds,
961 self.create_decimal_converter(US_TO_NS),
962 NS_TO_SEC)
Victor Stinner62d1c702015-04-01 17:47:07 +0200963
Victor Stinner992c43f2015-03-27 17:12:45 +0100964
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200965class TestOldPyTime(CPyTimeTestCase, unittest.TestCase):
Victor Stinneracea9f62015-09-02 10:39:40 +0200966 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200967 Test the old C _PyTime_t API: _PyTime_ObjectToXXX() functions.
Victor Stinneracea9f62015-09-02 10:39:40 +0200968 """
Victor Stinneracea9f62015-09-02 10:39:40 +0200969
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200970 # time_t is a 32-bit or 64-bit signed integer
971 OVERFLOW_SECONDS = 2 ** 64
972
973 def test_object_to_time_t(self):
Victor Stinneracea9f62015-09-02 10:39:40 +0200974 from _testcapi import pytime_object_to_time_t
975
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200976 self.check_int_rounding(pytime_object_to_time_t,
Victor Stinner4237d342015-09-10 10:10:39 +0200977 lambda secs: secs,
978 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200979
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200980 self.check_float_rounding(pytime_object_to_time_t,
Victor Stinner350b5182015-09-10 11:45:06 +0200981 self.decimal_round,
982 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200983
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200984 def create_converter(self, sec_to_unit):
985 def converter(secs):
986 floatpart, intpart = math.modf(secs)
987 intpart = int(intpart)
988 floatpart *= sec_to_unit
989 floatpart = self.decimal_round(floatpart)
990 if floatpart < 0:
991 floatpart += sec_to_unit
992 intpart -= 1
993 elif floatpart >= sec_to_unit:
994 floatpart -= sec_to_unit
995 intpart += 1
996 return (intpart, floatpart)
997 return converter
Victor Stinneracea9f62015-09-02 10:39:40 +0200998
Victor Stinneradfefa52015-09-04 23:57:25 +0200999 def test_object_to_timeval(self):
Victor Stinneracea9f62015-09-02 10:39:40 +02001000 from _testcapi import pytime_object_to_timeval
1001
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001002 self.check_int_rounding(pytime_object_to_timeval,
Victor Stinner4237d342015-09-10 10:10:39 +02001003 lambda secs: (secs, 0),
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_timeval,
Victor Stinner350b5182015-09-10 11:45:06 +02001007 self.create_converter(SEC_TO_US),
1008 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001009
Han Lee829dacc2017-09-09 08:05:05 +09001010 # test nan
1011 for time_rnd, _ in ROUNDING_MODES:
1012 with self.assertRaises(ValueError):
1013 pytime_object_to_timeval(float('nan'), time_rnd)
1014
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001015 def test_object_to_timespec(self):
Victor Stinneracea9f62015-09-02 10:39:40 +02001016 from _testcapi import pytime_object_to_timespec
1017
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001018 self.check_int_rounding(pytime_object_to_timespec,
Victor Stinner4237d342015-09-10 10:10:39 +02001019 lambda secs: (secs, 0),
1020 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001021
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001022 self.check_float_rounding(pytime_object_to_timespec,
Victor Stinner350b5182015-09-10 11:45:06 +02001023 self.create_converter(SEC_TO_NS),
1024 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001025
Han Lee829dacc2017-09-09 08:05:05 +09001026 # test nan
1027 for time_rnd, _ in ROUNDING_MODES:
1028 with self.assertRaises(ValueError):
1029 pytime_object_to_timespec(float('nan'), time_rnd)
1030
Victor Stinneracea9f62015-09-02 10:39:40 +02001031
Fred Drake2e2be372001-09-20 21:33:42 +00001032if __name__ == "__main__":
Ezio Melotti3836d702013-04-11 20:29:42 +03001033 unittest.main()