blob: 136ad29e20adf09ed20b4d0a65cece444290659e [file] [log] [blame]
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001from test import support
Victor Stinner3e2c8d82015-09-09 22:32:48 +02002import decimal
Victor Stinner992c43f2015-03-27 17:12:45 +01003import enum
4import locale
Victor Stinner3e2c8d82015-09-09 22:32:48 +02005import math
Victor Stinner992c43f2015-03-27 17:12:45 +01006import platform
7import sys
8import sysconfig
Barry Warsawb0c22321996-12-06 23:30:07 +00009import time
pdoxe14679c2017-10-05 00:01:56 -070010import threading
Fred Drakebc561982001-05-22 17:02:02 +000011import unittest
Victor Stinnerec895392012-04-29 02:41:27 +020012try:
Victor Stinner34dc0f42015-03-27 18:19:03 +010013 import _testcapi
14except ImportError:
15 _testcapi = None
16
Barry Warsawb0c22321996-12-06 23:30:07 +000017
Florent Xiclunabceb5282011-11-01 14:11:34 +010018# Max year is only limited by the size of C int.
19SIZEOF_INT = sysconfig.get_config_var('SIZEOF_INT') or 4
20TIME_MAXYEAR = (1 << 8 * SIZEOF_INT - 1) - 1
Gregory P. Smith76be0ff2018-08-24 18:08:50 -070021TIME_MINYEAR = -TIME_MAXYEAR - 1 + 1900
Victor Stinner992c43f2015-03-27 17:12:45 +010022
Victor Stinner3e2c8d82015-09-09 22:32:48 +020023SEC_TO_US = 10 ** 6
Victor Stinner62d1c702015-04-01 17:47:07 +020024US_TO_NS = 10 ** 3
25MS_TO_NS = 10 ** 6
Victor Stinner4bfb4602015-03-27 22:27:24 +010026SEC_TO_NS = 10 ** 9
Victor Stinner3e2c8d82015-09-09 22:32:48 +020027NS_TO_SEC = 10 ** 9
Victor Stinner992c43f2015-03-27 17:12:45 +010028
29class _PyTime(enum.IntEnum):
Victor Stinnerbcdd7772015-03-30 03:52:49 +020030 # Round towards minus infinity (-inf)
Victor Stinnera695f832015-03-30 03:57:14 +020031 ROUND_FLOOR = 0
Victor Stinnerbcdd7772015-03-30 03:52:49 +020032 # Round towards infinity (+inf)
Victor Stinnera695f832015-03-30 03:57:14 +020033 ROUND_CEILING = 1
Victor Stinner7667f582015-09-09 01:02:23 +020034 # Round to nearest with ties going to nearest even integer
35 ROUND_HALF_EVEN = 2
Pablo Galindo2c15b292017-10-17 15:14:41 +010036 # Round away from zero
37 ROUND_UP = 3
Victor Stinner992c43f2015-03-27 17:12:45 +010038
Victor Stinner3e2c8d82015-09-09 22:32:48 +020039# Rounding modes supported by PyTime
40ROUNDING_MODES = (
41 # (PyTime rounding method, decimal rounding method)
42 (_PyTime.ROUND_FLOOR, decimal.ROUND_FLOOR),
43 (_PyTime.ROUND_CEILING, decimal.ROUND_CEILING),
44 (_PyTime.ROUND_HALF_EVEN, decimal.ROUND_HALF_EVEN),
Pablo Galindo2c15b292017-10-17 15:14:41 +010045 (_PyTime.ROUND_UP, decimal.ROUND_UP),
Victor Stinner3e2c8d82015-09-09 22:32:48 +020046)
Florent Xiclunabceb5282011-11-01 14:11:34 +010047
48
Fred Drakebc561982001-05-22 17:02:02 +000049class TimeTestCase(unittest.TestCase):
Barry Warsawb0c22321996-12-06 23:30:07 +000050
Fred Drakebc561982001-05-22 17:02:02 +000051 def setUp(self):
52 self.t = time.time()
Barry Warsawb0c22321996-12-06 23:30:07 +000053
Fred Drakebc561982001-05-22 17:02:02 +000054 def test_data_attributes(self):
55 time.altzone
56 time.daylight
57 time.timezone
58 time.tzname
Barry Warsawb0c22321996-12-06 23:30:07 +000059
Victor Stinnerec895392012-04-29 02:41:27 +020060 def test_time(self):
61 time.time()
62 info = time.get_clock_info('time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040063 self.assertFalse(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +020064 self.assertTrue(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020065
Victor Stinnerc29b5852017-11-02 07:28:27 -070066 def test_time_ns_type(self):
67 def check_ns(sec, ns):
68 self.assertIsInstance(ns, int)
69
70 sec_ns = int(sec * 1e9)
71 # tolerate a difference of 50 ms
72 self.assertLess((sec_ns - ns), 50 ** 6, (sec, ns))
73
74 check_ns(time.time(),
75 time.time_ns())
76 check_ns(time.monotonic(),
77 time.monotonic_ns())
78 check_ns(time.perf_counter(),
79 time.perf_counter_ns())
80 check_ns(time.process_time(),
81 time.process_time_ns())
82
Antoine Pitrou4bd41c92017-11-15 22:52:21 +010083 if hasattr(time, 'thread_time'):
84 check_ns(time.thread_time(),
85 time.thread_time_ns())
86
Victor Stinnerc29b5852017-11-02 07:28:27 -070087 if hasattr(time, 'clock_gettime'):
88 check_ns(time.clock_gettime(time.CLOCK_REALTIME),
89 time.clock_gettime_ns(time.CLOCK_REALTIME))
90
Fred Drakebc561982001-05-22 17:02:02 +000091 def test_clock(self):
Victor Stinner884d13a2017-10-17 14:46:45 -070092 with self.assertWarns(DeprecationWarning):
93 time.clock()
Barry Warsawb0c22321996-12-06 23:30:07 +000094
Victor Stinner884d13a2017-10-17 14:46:45 -070095 with self.assertWarns(DeprecationWarning):
96 info = time.get_clock_info('clock')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040097 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +020098 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020099
Victor Stinnere0be4232011-10-25 13:06:09 +0200100 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
101 'need time.clock_gettime()')
102 def test_clock_realtime(self):
Victor Stinnerc29b5852017-11-02 07:28:27 -0700103 t = time.clock_gettime(time.CLOCK_REALTIME)
104 self.assertIsInstance(t, float)
Victor Stinnere0be4232011-10-25 13:06:09 +0200105
106 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
107 'need time.clock_gettime()')
108 @unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'),
109 'need time.CLOCK_MONOTONIC')
110 def test_clock_monotonic(self):
111 a = time.clock_gettime(time.CLOCK_MONOTONIC)
112 b = time.clock_gettime(time.CLOCK_MONOTONIC)
113 self.assertLessEqual(a, b)
114
pdoxe14679c2017-10-05 00:01:56 -0700115 @unittest.skipUnless(hasattr(time, 'pthread_getcpuclockid'),
116 'need time.pthread_getcpuclockid()')
117 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
118 'need time.clock_gettime()')
pdoxe14679c2017-10-05 00:01:56 -0700119 def test_pthread_getcpuclockid(self):
120 clk_id = time.pthread_getcpuclockid(threading.get_ident())
121 self.assertTrue(type(clk_id) is int)
Michael Felte2926b72018-12-28 14:57:37 +0100122 # when in 32-bit mode AIX only returns the predefined constant
123 if not platform.system() == "AIX":
124 self.assertNotEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
125 elif (sys.maxsize.bit_length() > 32):
126 self.assertNotEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
127 else:
128 self.assertEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
pdoxe14679c2017-10-05 00:01:56 -0700129 t1 = time.clock_gettime(clk_id)
Benjamin Peterson86566702017-10-05 22:50:42 -0700130 t2 = time.clock_gettime(clk_id)
pdoxe14679c2017-10-05 00:01:56 -0700131 self.assertLessEqual(t1, t2)
pdoxe14679c2017-10-05 00:01:56 -0700132
Victor Stinnere0be4232011-10-25 13:06:09 +0200133 @unittest.skipUnless(hasattr(time, 'clock_getres'),
134 'need time.clock_getres()')
135 def test_clock_getres(self):
136 res = time.clock_getres(time.CLOCK_REALTIME)
137 self.assertGreater(res, 0.0)
138 self.assertLessEqual(res, 1.0)
139
Victor Stinner30d79472012-04-03 00:45:07 +0200140 @unittest.skipUnless(hasattr(time, 'clock_settime'),
141 'need time.clock_settime()')
142 def test_clock_settime(self):
143 t = time.clock_gettime(time.CLOCK_REALTIME)
144 try:
145 time.clock_settime(time.CLOCK_REALTIME, t)
146 except PermissionError:
147 pass
148
Victor Stinnerec895392012-04-29 02:41:27 +0200149 if hasattr(time, 'CLOCK_MONOTONIC'):
150 self.assertRaises(OSError,
151 time.clock_settime, time.CLOCK_MONOTONIC, 0)
Victor Stinner30d79472012-04-03 00:45:07 +0200152
Fred Drakebc561982001-05-22 17:02:02 +0000153 def test_conversions(self):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000154 self.assertEqual(time.ctime(self.t),
155 time.asctime(time.localtime(self.t)))
156 self.assertEqual(int(time.mktime(time.localtime(self.t))),
157 int(self.t))
Fred Drakebc561982001-05-22 17:02:02 +0000158
159 def test_sleep(self):
Victor Stinner7f53a502011-07-05 22:00:25 +0200160 self.assertRaises(ValueError, time.sleep, -2)
161 self.assertRaises(ValueError, time.sleep, -1)
Fred Drakebc561982001-05-22 17:02:02 +0000162 time.sleep(1.2)
163
164 def test_strftime(self):
165 tt = time.gmtime(self.t)
166 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
167 'j', 'm', 'M', 'p', 'S',
168 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
169 format = ' %' + directive
170 try:
171 time.strftime(format, tt)
172 except ValueError:
173 self.fail('conversion specifier: %r failed.' % format)
174
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300175 self.assertRaises(TypeError, time.strftime, b'%S', tt)
176 # embedded null character
177 self.assertRaises(ValueError, time.strftime, '%S\0', tt)
178
Florent Xicluna49ce0682011-11-01 12:56:14 +0100179 def _bounds_checking(self, func):
Brett Cannond1080a32004-03-02 04:38:10 +0000180 # Make sure that strftime() checks the bounds of the various parts
Florent Xicluna49ce0682011-11-01 12:56:14 +0100181 # of the time tuple (0 is valid for *all* values).
Brett Cannond1080a32004-03-02 04:38:10 +0000182
Victor Stinner73ea29c2011-01-08 01:56:31 +0000183 # The year field is tested by other test cases above
184
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000185 # Check month [1, 12] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100186 func((1900, 0, 1, 0, 0, 0, 0, 1, -1))
187 func((1900, 12, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000188 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000189 (1900, -1, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000190 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000191 (1900, 13, 1, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000192 # Check day of month [1, 31] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100193 func((1900, 1, 0, 0, 0, 0, 0, 1, -1))
194 func((1900, 1, 31, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000195 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000196 (1900, 1, -1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000197 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000198 (1900, 1, 32, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000199 # Check hour [0, 23]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100200 func((1900, 1, 1, 23, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000201 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000202 (1900, 1, 1, -1, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000203 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000204 (1900, 1, 1, 24, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000205 # Check minute [0, 59]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100206 func((1900, 1, 1, 0, 59, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000207 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000208 (1900, 1, 1, 0, -1, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000209 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000210 (1900, 1, 1, 0, 60, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000211 # Check second [0, 61]
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000212 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000213 (1900, 1, 1, 0, 0, -1, 0, 1, -1))
214 # C99 only requires allowing for one leap second, but Python's docs say
215 # allow two leap seconds (0..61)
Florent Xicluna49ce0682011-11-01 12:56:14 +0100216 func((1900, 1, 1, 0, 0, 60, 0, 1, -1))
217 func((1900, 1, 1, 0, 0, 61, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000218 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000219 (1900, 1, 1, 0, 0, 62, 0, 1, -1))
220 # No check for upper-bound day of week;
221 # value forced into range by a ``% 7`` calculation.
222 # Start check at -2 since gettmarg() increments value before taking
223 # modulo.
Florent Xicluna49ce0682011-11-01 12:56:14 +0100224 self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)),
225 func((1900, 1, 1, 0, 0, 0, +6, 1, -1)))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000226 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000227 (1900, 1, 1, 0, 0, 0, -2, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000228 # Check day of the year [1, 366] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100229 func((1900, 1, 1, 0, 0, 0, 0, 0, -1))
230 func((1900, 1, 1, 0, 0, 0, 0, 366, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000231 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000232 (1900, 1, 1, 0, 0, 0, 0, -1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000233 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000234 (1900, 1, 1, 0, 0, 0, 0, 367, -1))
Brett Cannond1080a32004-03-02 04:38:10 +0000235
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000236 def test_strftime_bounding_check(self):
237 self._bounds_checking(lambda tup: time.strftime('', tup))
238
Steve Dowere5b58952015-09-06 19:20:51 -0700239 def test_strftime_format_check(self):
240 # Test that strftime does not crash on invalid format strings
241 # that may trigger a buffer overread. When not triggered,
242 # strftime may succeed or raise ValueError depending on
243 # the platform.
244 for x in [ '', 'A', '%A', '%AA' ]:
245 for y in range(0x0, 0x10):
246 for z in [ '%', 'A%', 'AA%', '%A%', 'A%A%', '%#' ]:
247 try:
248 time.strftime(x * y + z)
249 except ValueError:
250 pass
251
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000252 def test_default_values_for_zero(self):
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400253 # Make sure that using all zeros uses the proper default
254 # values. No test for daylight savings since strftime() does
255 # not change output based on its value and no test for year
256 # because systems vary in their support for year 0.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000257 expected = "2000 01 01 00 00 00 1 001"
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000258 with support.check_warnings():
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400259 result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000260 self.assertEqual(expected, result)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000261
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000262 def test_strptime(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000263 # Should be able to go round-trip from strftime to strptime without
Andrew Svetlov737fb892012-12-18 21:14:22 +0200264 # raising an exception.
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000265 tt = time.gmtime(self.t)
266 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
267 'j', 'm', 'M', 'p', 'S',
268 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000269 format = '%' + directive
270 strf_output = time.strftime(format, tt)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000271 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000272 time.strptime(strf_output, format)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000273 except ValueError:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000274 self.fail("conversion specifier %r failed with '%s' input." %
275 (format, strf_output))
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000276
Brett Cannon7f6b4f82009-03-30 21:30:26 +0000277 def test_strptime_bytes(self):
278 # Make sure only strings are accepted as arguments to strptime.
279 self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
280 self.assertRaises(TypeError, time.strptime, '2009', b'%Y')
281
Ezio Melotti0f389082013-04-04 02:09:20 +0300282 def test_strptime_exception_context(self):
283 # check that this doesn't chain exceptions needlessly (see #17572)
284 with self.assertRaises(ValueError) as e:
285 time.strptime('', '%D')
286 self.assertIs(e.exception.__suppress_context__, True)
Serhiy Storchakacdac3022013-11-24 18:15:37 +0200287 # additional check for IndexError branch (issue #19545)
288 with self.assertRaises(ValueError) as e:
289 time.strptime('19', '%Y %')
290 self.assertIs(e.exception.__suppress_context__, True)
Ezio Melotti0f389082013-04-04 02:09:20 +0300291
Fred Drakebc561982001-05-22 17:02:02 +0000292 def test_asctime(self):
293 time.asctime(time.gmtime(self.t))
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000294
295 # Max year is only limited by the size of C int.
Florent Xiclunabceb5282011-11-01 14:11:34 +0100296 for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
297 asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
298 self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
299 self.assertRaises(OverflowError, time.asctime,
300 (TIME_MAXYEAR + 1,) + (0,) * 8)
301 self.assertRaises(OverflowError, time.asctime,
302 (TIME_MINYEAR - 1,) + (0,) * 8)
Fred Drakebc561982001-05-22 17:02:02 +0000303 self.assertRaises(TypeError, time.asctime, 0)
Alexander Belopolskye2dc0822011-01-02 20:48:22 +0000304 self.assertRaises(TypeError, time.asctime, ())
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000305 self.assertRaises(TypeError, time.asctime, (0,) * 10)
Fred Drakebc561982001-05-22 17:02:02 +0000306
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000307 def test_asctime_bounding_check(self):
308 self._bounds_checking(time.asctime)
309
Georg Brandle10608c2011-01-02 22:33:43 +0000310 def test_ctime(self):
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000311 t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
312 self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
313 t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
314 self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000')
Victor Stinner1ac42612014-02-21 09:27:17 +0100315 for year in [-100, 100, 1000, 2000, 2050, 10000]:
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000316 try:
317 testval = time.mktime((year, 1, 10) + (0,)*6)
318 except (ValueError, OverflowError):
319 # If mktime fails, ctime will fail too. This may happen
320 # on some platforms.
321 pass
322 else:
323 self.assertEqual(time.ctime(testval)[20:], str(year))
Georg Brandle10608c2011-01-02 22:33:43 +0000324
Florent Xiclunae54371e2011-11-11 18:59:30 +0100325 @unittest.skipUnless(hasattr(time, "tzset"),
326 "time module has no attribute tzset")
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000327 def test_tzset(self):
Guido van Rossumd2b738e2003-03-15 12:01:52 +0000328
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000329 from os import environ
330
Tim Peters0eadaac2003-04-24 16:02:54 +0000331 # Epoch time of midnight Dec 25th 2002. Never DST in northern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000332 # hemisphere.
Tim Peters0eadaac2003-04-24 16:02:54 +0000333 xmas2002 = 1040774400.0
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000334
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000335 # These formats are correct for 2002, and possibly future years
336 # This format is the 'standard' as documented at:
337 # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
338 # They are also documented in the tzset(3) man page on most Unix
339 # systems.
Tim Peters0eadaac2003-04-24 16:02:54 +0000340 eastern = 'EST+05EDT,M4.1.0,M10.5.0'
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000341 victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
342 utc='UTC+0'
343
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000344 org_TZ = environ.get('TZ',None)
345 try:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000346 # Make sure we can switch to UTC time and results are correct
347 # Note that unknown timezones default to UTC.
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000348 # Note that altzone is undefined in UTC, as there is no DST
349 environ['TZ'] = eastern
350 time.tzset()
351 environ['TZ'] = utc
352 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000353 self.assertEqual(
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000354 time.gmtime(xmas2002), time.localtime(xmas2002)
355 )
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000356 self.assertEqual(time.daylight, 0)
357 self.assertEqual(time.timezone, 0)
358 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000359
360 # Make sure we can switch to US/Eastern
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000361 environ['TZ'] = eastern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000362 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000363 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
364 self.assertEqual(time.tzname, ('EST', 'EDT'))
365 self.assertEqual(len(time.tzname), 2)
366 self.assertEqual(time.daylight, 1)
367 self.assertEqual(time.timezone, 18000)
368 self.assertEqual(time.altzone, 14400)
369 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
370 self.assertEqual(len(time.tzname), 2)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000371
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000372 # Now go to the southern hemisphere.
373 environ['TZ'] = victoria
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000374 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000375 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
Victor Stinner0cd47902011-12-08 00:32:51 +0100376
377 # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100378 # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
379 # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
380 # on some operating systems (e.g. FreeBSD), which is wrong. See for
381 # example this bug:
382 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
Victor Stinner0cd47902011-12-08 00:32:51 +0100383 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100384 self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000385 self.assertEqual(len(time.tzname), 2)
386 self.assertEqual(time.daylight, 1)
387 self.assertEqual(time.timezone, -36000)
388 self.assertEqual(time.altzone, -39600)
389 self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000390
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000391 finally:
392 # Repair TZ environment variable in case any other tests
393 # rely on it.
394 if org_TZ is not None:
395 environ['TZ'] = org_TZ
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000396 elif 'TZ' in environ:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000397 del environ['TZ']
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000398 time.tzset()
Tim Peters0eadaac2003-04-24 16:02:54 +0000399
Tim Peters1b6f7a92004-06-20 02:50:16 +0000400 def test_insane_timestamps(self):
401 # It's possible that some platform maps time_t to double,
402 # and that this test will fail there. This test should
403 # exempt such platforms (provided they return reasonable
404 # results!).
405 for func in time.ctime, time.gmtime, time.localtime:
406 for unreasonable in -1e200, 1e200:
Victor Stinner5d272cc2012-03-13 13:35:55 +0100407 self.assertRaises(OverflowError, func, unreasonable)
Fred Drakebc561982001-05-22 17:02:02 +0000408
Fred Drakef901abd2004-08-03 17:58:55 +0000409 def test_ctime_without_arg(self):
410 # Not sure how to check the values, since the clock could tick
411 # at any time. Make sure these are at least accepted and
412 # don't raise errors.
413 time.ctime()
414 time.ctime(None)
415
416 def test_gmtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000417 gt0 = time.gmtime()
418 gt1 = time.gmtime(None)
419 t0 = time.mktime(gt0)
420 t1 = time.mktime(gt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000421 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000422
423 def test_localtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000424 lt0 = time.localtime()
425 lt1 = time.localtime(None)
426 t0 = time.mktime(lt0)
427 t1 = time.mktime(lt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000428 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000429
Florent Xiclunae54371e2011-11-11 18:59:30 +0100430 def test_mktime(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100431 # Issue #1726687
432 for t in (-2, -1, 0, 1):
433 try:
434 tt = time.localtime(t)
Victor Stinner2cbae982012-01-27 00:50:33 +0100435 except (OverflowError, OSError):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100436 pass
437 else:
438 self.assertEqual(time.mktime(tt), t)
Florent Xiclunae54371e2011-11-11 18:59:30 +0100439
440 # Issue #13309: passing extreme values to mktime() or localtime()
441 # borks the glibc's internal timezone data.
442 @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
443 "disabled because of a bug in glibc. Issue #13309")
444 def test_mktime_error(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100445 # It may not be possible to reliably make mktime return error
446 # on all platfom. This will make sure that no other exception
447 # than OverflowError is raised for an extreme value.
Florent Xiclunae54371e2011-11-11 18:59:30 +0100448 tt = time.gmtime(self.t)
449 tzname = time.strftime('%Z', tt)
450 self.assertNotEqual(tzname, 'LMT')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100451 try:
452 time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
453 except OverflowError:
454 pass
Florent Xiclunae54371e2011-11-11 18:59:30 +0100455 self.assertEqual(time.strftime('%Z', tt), tzname)
Florent Xiclunabceb5282011-11-01 14:11:34 +0100456
Victor Stinnerec895392012-04-29 02:41:27 +0200457 def test_monotonic(self):
Victor Stinner6c861812013-11-23 00:15:27 +0100458 # monotonic() should not go backward
459 times = [time.monotonic() for n in range(100)]
460 t1 = times[0]
461 for t2 in times[1:]:
462 self.assertGreaterEqual(t2, t1, "times=%s" % times)
463 t1 = t2
464
465 # monotonic() includes time elapsed during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200466 t1 = time.monotonic()
Victor Stinnera9c99a62013-07-03 23:07:37 +0200467 time.sleep(0.5)
Victor Stinnerec895392012-04-29 02:41:27 +0200468 t2 = time.monotonic()
Victor Stinner2dd254d2012-01-20 02:24:18 +0100469 dt = t2 - t1
Victor Stinner8b302012012-02-07 23:29:46 +0100470 self.assertGreater(t2, t1)
Zachary Ware487aedb2014-01-02 09:41:10 -0600471 # Issue #20101: On some Windows machines, dt may be slightly low
472 self.assertTrue(0.45 <= dt <= 1.0, dt)
Antoine Pitrou391166f2012-01-18 22:35:21 +0100473
Victor Stinner6c861812013-11-23 00:15:27 +0100474 # monotonic() is a monotonic but non adjustable clock
Victor Stinnerec895392012-04-29 02:41:27 +0200475 info = time.get_clock_info('monotonic')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400476 self.assertTrue(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +0200477 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200478
479 def test_perf_counter(self):
480 time.perf_counter()
481
482 def test_process_time(self):
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200483 # process_time() should not include time spend during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200484 start = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200485 time.sleep(0.100)
Victor Stinnerec895392012-04-29 02:41:27 +0200486 stop = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200487 # use 20 ms because process_time() has usually a resolution of 15 ms
488 # on Windows
489 self.assertLess(stop - start, 0.020)
Victor Stinnerec895392012-04-29 02:41:27 +0200490
491 info = time.get_clock_info('process_time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400492 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200493 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200494
Antoine Pitrou4bd41c92017-11-15 22:52:21 +0100495 def test_thread_time(self):
496 if not hasattr(time, 'thread_time'):
497 if sys.platform.startswith(('linux', 'win')):
498 self.fail("time.thread_time() should be available on %r"
499 % (sys.platform,))
500 else:
501 self.skipTest("need time.thread_time")
502
503 # thread_time() should not include time spend during a sleep
504 start = time.thread_time()
505 time.sleep(0.100)
506 stop = time.thread_time()
507 # use 20 ms because thread_time() has usually a resolution of 15 ms
508 # on Windows
509 self.assertLess(stop - start, 0.020)
510
Antoine Pitrou4bd41c92017-11-15 22:52:21 +0100511 info = time.get_clock_info('thread_time')
512 self.assertTrue(info.monotonic)
513 self.assertFalse(info.adjustable)
514
Victor Stinnerec895392012-04-29 02:41:27 +0200515 @unittest.skipUnless(hasattr(time, 'clock_settime'),
516 'need time.clock_settime')
517 def test_monotonic_settime(self):
518 t1 = time.monotonic()
519 realtime = time.clock_gettime(time.CLOCK_REALTIME)
520 # jump backward with an offset of 1 hour
Victor Stinner071eca32012-03-15 01:17:09 +0100521 try:
Victor Stinnerec895392012-04-29 02:41:27 +0200522 time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
523 except PermissionError as err:
524 self.skipTest(err)
525 t2 = time.monotonic()
526 time.clock_settime(time.CLOCK_REALTIME, realtime)
527 # monotonic must not be affected by system clock updates
Victor Stinner071eca32012-03-15 01:17:09 +0100528 self.assertGreaterEqual(t2, t1)
529
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100530 def test_localtime_failure(self):
531 # Issue #13847: check for localtime() failure
Victor Stinner53d36452012-01-27 01:03:25 +0100532 invalid_time_t = None
533 for time_t in (-1, 2**30, 2**33, 2**60):
534 try:
535 time.localtime(time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100536 except OverflowError:
537 self.skipTest("need 64-bit time_t")
Victor Stinner53d36452012-01-27 01:03:25 +0100538 except OSError:
539 invalid_time_t = time_t
540 break
541 if invalid_time_t is None:
542 self.skipTest("unable to find an invalid time_t value")
543
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100544 self.assertRaises(OSError, time.localtime, invalid_time_t)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100545 self.assertRaises(OSError, time.ctime, invalid_time_t)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100546
Han Lee829dacc2017-09-09 08:05:05 +0900547 # Issue #26669: check for localtime() failure
548 self.assertRaises(ValueError, time.localtime, float("nan"))
549 self.assertRaises(ValueError, time.ctime, float("nan"))
550
Victor Stinnerec895392012-04-29 02:41:27 +0200551 def test_get_clock_info(self):
Victor Stinner884d13a2017-10-17 14:46:45 -0700552 clocks = ['clock', 'monotonic', 'perf_counter', 'process_time', 'time']
Victor Stinnerec895392012-04-29 02:41:27 +0200553
554 for name in clocks:
Victor Stinner884d13a2017-10-17 14:46:45 -0700555 if name == 'clock':
556 with self.assertWarns(DeprecationWarning):
557 info = time.get_clock_info('clock')
558 else:
559 info = time.get_clock_info(name)
560
Victor Stinnerec895392012-04-29 02:41:27 +0200561 #self.assertIsInstance(info, dict)
562 self.assertIsInstance(info.implementation, str)
563 self.assertNotEqual(info.implementation, '')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400564 self.assertIsInstance(info.monotonic, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200565 self.assertIsInstance(info.resolution, float)
566 # 0.0 < resolution <= 1.0
567 self.assertGreater(info.resolution, 0.0)
568 self.assertLessEqual(info.resolution, 1.0)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200569 self.assertIsInstance(info.adjustable, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200570
571 self.assertRaises(ValueError, time.get_clock_info, 'xxx')
572
573
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000574class TestLocale(unittest.TestCase):
575 def setUp(self):
576 self.oldloc = locale.setlocale(locale.LC_ALL)
Fred Drake2e2be372001-09-20 21:33:42 +0000577
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000578 def tearDown(self):
579 locale.setlocale(locale.LC_ALL, self.oldloc)
580
Martin v. Löwisa6a9c4d2009-05-30 06:15:30 +0000581 def test_bug_3061(self):
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000582 try:
583 tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
584 except locale.Error:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600585 self.skipTest('could not set locale.LC_ALL to fr_FR')
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000586 # This should not cause an exception
587 time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
588
Victor Stinner73ea29c2011-01-08 01:56:31 +0000589
Victor Stinner73ea29c2011-01-08 01:56:31 +0000590class _TestAsctimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100591 _format = '%d'
592
Victor Stinner73ea29c2011-01-08 01:56:31 +0000593 def yearstr(self, y):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000594 return time.asctime((y,) + (0,) * 8).split()[-1]
Alexander Belopolskya6867252011-01-05 23:00:47 +0000595
Victor Stinner73ea29c2011-01-08 01:56:31 +0000596 def test_large_year(self):
Victor Stinner73691322011-01-08 02:00:24 +0000597 # Check that it doesn't crash for year > 9999
Victor Stinner73ea29c2011-01-08 01:56:31 +0000598 self.assertEqual(self.yearstr(12345), '12345')
599 self.assertEqual(self.yearstr(123456789), '123456789')
600
601class _TestStrftimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100602
603 # Issue 13305: For years < 1000, the value is not always
604 # padded to 4 digits across platforms. The C standard
605 # assumes year >= 1900, so it does not specify the number
606 # of digits.
607
608 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
609 _format = '%04d'
610 else:
611 _format = '%d'
612
Victor Stinner73ea29c2011-01-08 01:56:31 +0000613 def yearstr(self, y):
Florent Xicluna49ce0682011-11-01 12:56:14 +0100614 return time.strftime('%Y', (y,) + (0,) * 8)
615
616 def test_4dyear(self):
617 # Check that we can return the zero padded value.
618 if self._format == '%04d':
619 self.test_year('%04d')
620 else:
621 def year4d(y):
622 return time.strftime('%4Y', (y,) + (0,) * 8)
623 self.test_year('%04d', func=year4d)
624
Florent Xiclunabceb5282011-11-01 14:11:34 +0100625 def skip_if_not_supported(y):
626 msg = "strftime() is limited to [1; 9999] with Visual Studio"
627 # Check that it doesn't crash for year > 9999
628 try:
629 time.strftime('%Y', (y,) + (0,) * 8)
630 except ValueError:
631 cond = False
632 else:
633 cond = True
634 return unittest.skipUnless(cond, msg)
635
636 @skip_if_not_supported(10000)
637 def test_large_year(self):
638 return super().test_large_year()
639
640 @skip_if_not_supported(0)
641 def test_negative(self):
642 return super().test_negative()
643
644 del skip_if_not_supported
645
646
Ezio Melotti3836d702013-04-11 20:29:42 +0300647class _Test4dYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100648 _format = '%d'
649
650 def test_year(self, fmt=None, func=None):
651 fmt = fmt or self._format
652 func = func or self.yearstr
653 self.assertEqual(func(1), fmt % 1)
654 self.assertEqual(func(68), fmt % 68)
655 self.assertEqual(func(69), fmt % 69)
656 self.assertEqual(func(99), fmt % 99)
657 self.assertEqual(func(999), fmt % 999)
658 self.assertEqual(func(9999), fmt % 9999)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000659
660 def test_large_year(self):
Benjamin Petersone1a34ce2018-09-12 16:21:36 -0700661 self.assertEqual(self.yearstr(12345).lstrip('+'), '12345')
662 self.assertEqual(self.yearstr(123456789).lstrip('+'), '123456789')
663 self.assertEqual(self.yearstr(TIME_MAXYEAR).lstrip('+'), str(TIME_MAXYEAR))
Florent Xiclunabceb5282011-11-01 14:11:34 +0100664 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000665
Victor Stinner301f1212011-01-08 03:06:52 +0000666 def test_negative(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100667 self.assertEqual(self.yearstr(-1), self._format % -1)
Victor Stinner301f1212011-01-08 03:06:52 +0000668 self.assertEqual(self.yearstr(-1234), '-1234')
669 self.assertEqual(self.yearstr(-123456), '-123456')
Florent Xiclunad1bd7f72011-11-01 23:42:05 +0100670 self.assertEqual(self.yearstr(-123456789), str(-123456789))
671 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
Gregory P. Smith76be0ff2018-08-24 18:08:50 -0700672 self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
673 # Modules/timemodule.c checks for underflow
Florent Xiclunabceb5282011-11-01 14:11:34 +0100674 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
Gregory P. Smith76be0ff2018-08-24 18:08:50 -0700675 with self.assertRaises(OverflowError):
676 self.yearstr(-TIME_MAXYEAR - 1)
Victor Stinner301f1212011-01-08 03:06:52 +0000677
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000678
Ezio Melotti3836d702013-04-11 20:29:42 +0300679class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner73ea29c2011-01-08 01:56:31 +0000680 pass
681
Ezio Melotti3836d702013-04-11 20:29:42 +0300682class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner301f1212011-01-08 03:06:52 +0000683 pass
Victor Stinner73ea29c2011-01-08 01:56:31 +0000684
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000685
Victor Stinner643cd682012-03-02 22:54:03 +0100686class TestPytime(unittest.TestCase):
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400687 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
688 def test_localtime_timezone(self):
Victor Stinner643cd682012-03-02 22:54:03 +0100689
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400690 # Get the localtime and examine it for the offset and zone.
691 lt = time.localtime()
692 self.assertTrue(hasattr(lt, "tm_gmtoff"))
693 self.assertTrue(hasattr(lt, "tm_zone"))
694
695 # See if the offset and zone are similar to the module
696 # attributes.
697 if lt.tm_gmtoff is None:
698 self.assertTrue(not hasattr(time, "timezone"))
699 else:
700 self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
701 if lt.tm_zone is None:
702 self.assertTrue(not hasattr(time, "tzname"))
703 else:
704 self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
705
706 # Try and make UNIX times from the localtime and a 9-tuple
707 # created from the localtime. Test to see that the times are
708 # the same.
709 t = time.mktime(lt); t9 = time.mktime(lt[:9])
710 self.assertEqual(t, t9)
711
712 # Make localtimes from the UNIX times and compare them to
713 # the original localtime, thus making a round trip.
714 new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
715 self.assertEqual(new_lt, lt)
716 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
717 self.assertEqual(new_lt.tm_zone, lt.tm_zone)
718 self.assertEqual(new_lt9, lt)
719 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
720 self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
721
722 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
723 def test_strptime_timezone(self):
724 t = time.strptime("UTC", "%Z")
725 self.assertEqual(t.tm_zone, 'UTC')
726 t = time.strptime("+0500", "%z")
727 self.assertEqual(t.tm_gmtoff, 5 * 3600)
728
729 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
730 def test_short_times(self):
731
732 import pickle
733
734 # Load a short time structure using pickle.
735 st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
736 lt = pickle.loads(st)
737 self.assertIs(lt.tm_gmtoff, None)
738 self.assertIs(lt.tm_zone, None)
Victor Stinner643cd682012-03-02 22:54:03 +0100739
Fred Drake2e2be372001-09-20 21:33:42 +0000740
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200741@unittest.skipIf(_testcapi is None, 'need the _testcapi module')
742class CPyTimeTestCase:
Victor Stinneracea9f62015-09-02 10:39:40 +0200743 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200744 Base class to test the C _PyTime_t API.
Victor Stinneracea9f62015-09-02 10:39:40 +0200745 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200746 OVERFLOW_SECONDS = None
747
Victor Stinner4237d342015-09-10 10:10:39 +0200748 def setUp(self):
749 from _testcapi import SIZEOF_TIME_T
750 bits = SIZEOF_TIME_T * 8 - 1
751 self.time_t_min = -2 ** bits
752 self.time_t_max = 2 ** bits - 1
753
754 def time_t_filter(self, seconds):
755 return (self.time_t_min <= seconds <= self.time_t_max)
756
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200757 def _rounding_values(self, use_float):
758 "Build timestamps used to test rounding."
759
760 units = [1, US_TO_NS, MS_TO_NS, SEC_TO_NS]
761 if use_float:
762 # picoseconds are only tested to pytime_converter accepting floats
763 units.append(1e-3)
764
765 values = (
766 # small values
767 1, 2, 5, 7, 123, 456, 1234,
768 # 10^k - 1
769 9,
770 99,
771 999,
772 9999,
773 99999,
774 999999,
775 # test half even rounding near 0.5, 1.5, 2.5, 3.5, 4.5
776 499, 500, 501,
777 1499, 1500, 1501,
778 2500,
779 3500,
780 4500,
781 )
782
783 ns_timestamps = [0]
784 for unit in units:
785 for value in values:
786 ns = value * unit
787 ns_timestamps.extend((-ns, ns))
788 for pow2 in (0, 5, 10, 15, 22, 23, 24, 30, 33):
789 ns = (2 ** pow2) * SEC_TO_NS
790 ns_timestamps.extend((
791 -ns-1, -ns, -ns+1,
792 ns-1, ns, ns+1
793 ))
794 for seconds in (_testcapi.INT_MIN, _testcapi.INT_MAX):
795 ns_timestamps.append(seconds * SEC_TO_NS)
796 if use_float:
Victor Stinner717a32b2016-08-17 11:07:21 +0200797 # numbers with an exact representation in IEEE 754 (base 2)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200798 for pow2 in (3, 7, 10, 15):
799 ns = 2.0 ** (-pow2)
800 ns_timestamps.extend((-ns, ns))
801
802 # seconds close to _PyTime_t type limit
803 ns = (2 ** 63 // SEC_TO_NS) * SEC_TO_NS
804 ns_timestamps.extend((-ns, ns))
805
806 return ns_timestamps
807
808 def _check_rounding(self, pytime_converter, expected_func,
809 use_float, unit_to_sec, value_filter=None):
810
811 def convert_values(ns_timestamps):
812 if use_float:
813 unit_to_ns = SEC_TO_NS / float(unit_to_sec)
814 values = [ns / unit_to_ns for ns in ns_timestamps]
815 else:
816 unit_to_ns = SEC_TO_NS // unit_to_sec
817 values = [ns // unit_to_ns for ns in ns_timestamps]
818
819 if value_filter:
820 values = filter(value_filter, values)
821
822 # remove duplicates and sort
823 return sorted(set(values))
824
825 # test rounding
826 ns_timestamps = self._rounding_values(use_float)
827 valid_values = convert_values(ns_timestamps)
828 for time_rnd, decimal_rnd in ROUNDING_MODES :
Bo Bayles938045f2018-07-21 12:54:14 -0500829 with decimal.localcontext() as context:
830 context.rounding = decimal_rnd
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200831
Bo Bayles938045f2018-07-21 12:54:14 -0500832 for value in valid_values:
833 debug_info = {'value': value, 'rounding': decimal_rnd}
834 try:
835 result = pytime_converter(value, time_rnd)
836 expected = expected_func(value)
837 except Exception as exc:
838 self.fail("Error on timestamp conversion: %s" % debug_info)
839 self.assertEqual(result,
840 expected,
841 debug_info)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200842
843 # test overflow
844 ns = self.OVERFLOW_SECONDS * SEC_TO_NS
845 ns_timestamps = (-ns, ns)
846 overflow_values = convert_values(ns_timestamps)
847 for time_rnd, _ in ROUNDING_MODES :
848 for value in overflow_values:
Victor Stinnerc60542b2015-09-10 15:55:07 +0200849 debug_info = {'value': value, 'rounding': time_rnd}
850 with self.assertRaises(OverflowError, msg=debug_info):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200851 pytime_converter(value, time_rnd)
852
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200853 def check_int_rounding(self, pytime_converter, expected_func,
854 unit_to_sec=1, value_filter=None):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200855 self._check_rounding(pytime_converter, expected_func,
856 False, unit_to_sec, value_filter)
857
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200858 def check_float_rounding(self, pytime_converter, expected_func,
859 unit_to_sec=1, value_filter=None):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200860 self._check_rounding(pytime_converter, expected_func,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200861 True, unit_to_sec, value_filter)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200862
863 def decimal_round(self, x):
864 d = decimal.Decimal(x)
865 d = d.quantize(1)
866 return int(d)
867
868
869class TestCPyTime(CPyTimeTestCase, unittest.TestCase):
870 """
871 Test the C _PyTime_t API.
872 """
873 # _PyTime_t is a 64-bit signed integer
874 OVERFLOW_SECONDS = math.ceil((2**63 + 1) / SEC_TO_NS)
875
Victor Stinner13019fd2015-04-03 13:10:54 +0200876 def test_FromSeconds(self):
877 from _testcapi import PyTime_FromSeconds
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200878
879 # PyTime_FromSeconds() expects a C int, reject values out of range
880 def c_int_filter(secs):
881 return (_testcapi.INT_MIN <= secs <= _testcapi.INT_MAX)
882
883 self.check_int_rounding(lambda secs, rnd: PyTime_FromSeconds(secs),
884 lambda secs: secs * SEC_TO_NS,
885 value_filter=c_int_filter)
Victor Stinner13019fd2015-04-03 13:10:54 +0200886
Han Lee829dacc2017-09-09 08:05:05 +0900887 # test nan
888 for time_rnd, _ in ROUNDING_MODES:
889 with self.assertRaises(TypeError):
890 PyTime_FromSeconds(float('nan'))
891
Victor Stinner992c43f2015-03-27 17:12:45 +0100892 def test_FromSecondsObject(self):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100893 from _testcapi import PyTime_FromSecondsObject
Victor Stinner992c43f2015-03-27 17:12:45 +0100894
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200895 self.check_int_rounding(
896 PyTime_FromSecondsObject,
897 lambda secs: secs * SEC_TO_NS)
Victor Stinner992c43f2015-03-27 17:12:45 +0100898
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200899 self.check_float_rounding(
900 PyTime_FromSecondsObject,
901 lambda ns: self.decimal_round(ns * SEC_TO_NS))
Victor Stinner4bfb4602015-03-27 22:27:24 +0100902
Han Lee829dacc2017-09-09 08:05:05 +0900903 # test nan
904 for time_rnd, _ in ROUNDING_MODES:
905 with self.assertRaises(ValueError):
906 PyTime_FromSecondsObject(float('nan'), time_rnd)
907
Victor Stinner4bfb4602015-03-27 22:27:24 +0100908 def test_AsSecondsDouble(self):
909 from _testcapi import PyTime_AsSecondsDouble
910
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200911 def float_converter(ns):
912 if abs(ns) % SEC_TO_NS == 0:
913 return float(ns // SEC_TO_NS)
914 else:
915 return float(ns) / SEC_TO_NS
Victor Stinner4bfb4602015-03-27 22:27:24 +0100916
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200917 self.check_int_rounding(lambda ns, rnd: PyTime_AsSecondsDouble(ns),
918 float_converter,
919 NS_TO_SEC)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100920
Han Lee829dacc2017-09-09 08:05:05 +0900921 # test nan
922 for time_rnd, _ in ROUNDING_MODES:
923 with self.assertRaises(TypeError):
924 PyTime_AsSecondsDouble(float('nan'))
925
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200926 def create_decimal_converter(self, denominator):
927 denom = decimal.Decimal(denominator)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100928
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200929 def converter(value):
930 d = decimal.Decimal(value) / denom
931 return self.decimal_round(d)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100932
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200933 return converter
Victor Stinner4bfb4602015-03-27 22:27:24 +0100934
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200935 def test_AsTimeval(self):
Victor Stinner95e9cef2015-03-28 01:26:47 +0100936 from _testcapi import PyTime_AsTimeval
Victor Stinner95e9cef2015-03-28 01:26:47 +0100937
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200938 us_converter = self.create_decimal_converter(US_TO_NS)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100939
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200940 def timeval_converter(ns):
941 us = us_converter(ns)
942 return divmod(us, SEC_TO_US)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100943
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200944 if sys.platform == 'win32':
945 from _testcapi import LONG_MIN, LONG_MAX
946
947 # On Windows, timeval.tv_sec type is a C long
948 def seconds_filter(secs):
949 return LONG_MIN <= secs <= LONG_MAX
950 else:
Victor Stinner4237d342015-09-10 10:10:39 +0200951 seconds_filter = self.time_t_filter
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200952
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200953 self.check_int_rounding(PyTime_AsTimeval,
954 timeval_converter,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200955 NS_TO_SEC,
956 value_filter=seconds_filter)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100957
Victor Stinner34dc0f42015-03-27 18:19:03 +0100958 @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec'),
959 'need _testcapi.PyTime_AsTimespec')
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200960 def test_AsTimespec(self):
Victor Stinner34dc0f42015-03-27 18:19:03 +0100961 from _testcapi import PyTime_AsTimespec
Victor Stinner34dc0f42015-03-27 18:19:03 +0100962
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200963 def timespec_converter(ns):
964 return divmod(ns, SEC_TO_NS)
Victor Stinner34dc0f42015-03-27 18:19:03 +0100965
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200966 self.check_int_rounding(lambda ns, rnd: PyTime_AsTimespec(ns),
967 timespec_converter,
Victor Stinner4237d342015-09-10 10:10:39 +0200968 NS_TO_SEC,
969 value_filter=self.time_t_filter)
Victor Stinner34dc0f42015-03-27 18:19:03 +0100970
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200971 def test_AsMilliseconds(self):
Victor Stinner62d1c702015-04-01 17:47:07 +0200972 from _testcapi import PyTime_AsMilliseconds
Victor Stinner62d1c702015-04-01 17:47:07 +0200973
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200974 self.check_int_rounding(PyTime_AsMilliseconds,
975 self.create_decimal_converter(MS_TO_NS),
976 NS_TO_SEC)
Victor Stinner62d1c702015-04-01 17:47:07 +0200977
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200978 def test_AsMicroseconds(self):
Victor Stinner62d1c702015-04-01 17:47:07 +0200979 from _testcapi import PyTime_AsMicroseconds
Victor Stinner62d1c702015-04-01 17:47:07 +0200980
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200981 self.check_int_rounding(PyTime_AsMicroseconds,
982 self.create_decimal_converter(US_TO_NS),
983 NS_TO_SEC)
Victor Stinner62d1c702015-04-01 17:47:07 +0200984
Victor Stinner992c43f2015-03-27 17:12:45 +0100985
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200986class TestOldPyTime(CPyTimeTestCase, unittest.TestCase):
Victor Stinneracea9f62015-09-02 10:39:40 +0200987 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200988 Test the old C _PyTime_t API: _PyTime_ObjectToXXX() functions.
Victor Stinneracea9f62015-09-02 10:39:40 +0200989 """
Victor Stinneracea9f62015-09-02 10:39:40 +0200990
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200991 # time_t is a 32-bit or 64-bit signed integer
992 OVERFLOW_SECONDS = 2 ** 64
993
994 def test_object_to_time_t(self):
Victor Stinneracea9f62015-09-02 10:39:40 +0200995 from _testcapi import pytime_object_to_time_t
996
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200997 self.check_int_rounding(pytime_object_to_time_t,
Victor Stinner4237d342015-09-10 10:10:39 +0200998 lambda secs: secs,
999 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001000
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001001 self.check_float_rounding(pytime_object_to_time_t,
Victor Stinner350b5182015-09-10 11:45:06 +02001002 self.decimal_round,
1003 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001004
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001005 def create_converter(self, sec_to_unit):
1006 def converter(secs):
1007 floatpart, intpart = math.modf(secs)
1008 intpart = int(intpart)
1009 floatpart *= sec_to_unit
1010 floatpart = self.decimal_round(floatpart)
1011 if floatpart < 0:
1012 floatpart += sec_to_unit
1013 intpart -= 1
1014 elif floatpart >= sec_to_unit:
1015 floatpart -= sec_to_unit
1016 intpart += 1
1017 return (intpart, floatpart)
1018 return converter
Victor Stinneracea9f62015-09-02 10:39:40 +02001019
Victor Stinneradfefa52015-09-04 23:57:25 +02001020 def test_object_to_timeval(self):
Victor Stinneracea9f62015-09-02 10:39:40 +02001021 from _testcapi import pytime_object_to_timeval
1022
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001023 self.check_int_rounding(pytime_object_to_timeval,
Victor Stinner4237d342015-09-10 10:10:39 +02001024 lambda secs: (secs, 0),
1025 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001026
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001027 self.check_float_rounding(pytime_object_to_timeval,
Victor Stinner350b5182015-09-10 11:45:06 +02001028 self.create_converter(SEC_TO_US),
1029 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001030
Han Lee829dacc2017-09-09 08:05:05 +09001031 # test nan
1032 for time_rnd, _ in ROUNDING_MODES:
1033 with self.assertRaises(ValueError):
1034 pytime_object_to_timeval(float('nan'), time_rnd)
1035
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001036 def test_object_to_timespec(self):
Victor Stinneracea9f62015-09-02 10:39:40 +02001037 from _testcapi import pytime_object_to_timespec
1038
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001039 self.check_int_rounding(pytime_object_to_timespec,
Victor Stinner4237d342015-09-10 10:10:39 +02001040 lambda secs: (secs, 0),
1041 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001042
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001043 self.check_float_rounding(pytime_object_to_timespec,
Victor Stinner350b5182015-09-10 11:45:06 +02001044 self.create_converter(SEC_TO_NS),
1045 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001046
Han Lee829dacc2017-09-09 08:05:05 +09001047 # test nan
1048 for time_rnd, _ in ROUNDING_MODES:
1049 with self.assertRaises(ValueError):
1050 pytime_object_to_timespec(float('nan'), time_rnd)
1051
Victor Stinneracea9f62015-09-02 10:39:40 +02001052
Fred Drake2e2be372001-09-20 21:33:42 +00001053if __name__ == "__main__":
Ezio Melotti3836d702013-04-11 20:29:42 +03001054 unittest.main()