blob: a08fd1822b031c5a0da5b0bb37d1528845e6979b [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
Fred Drakebc561982001-05-22 17:02:02 +000067 def test_clock(self):
Victor Stinner884d13a2017-10-17 14:46:45 -070068 with self.assertWarns(DeprecationWarning):
69 time.clock()
Barry Warsawb0c22321996-12-06 23:30:07 +000070
Victor Stinner884d13a2017-10-17 14:46:45 -070071 with self.assertWarns(DeprecationWarning):
72 info = time.get_clock_info('clock')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040073 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +020074 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020075
Victor Stinnere0be4232011-10-25 13:06:09 +020076 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
77 'need time.clock_gettime()')
78 def test_clock_realtime(self):
79 time.clock_gettime(time.CLOCK_REALTIME)
80
81 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
82 'need time.clock_gettime()')
83 @unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'),
84 'need time.CLOCK_MONOTONIC')
85 def test_clock_monotonic(self):
86 a = time.clock_gettime(time.CLOCK_MONOTONIC)
87 b = time.clock_gettime(time.CLOCK_MONOTONIC)
88 self.assertLessEqual(a, b)
89
pdoxe14679c2017-10-05 00:01:56 -070090 @unittest.skipUnless(hasattr(time, 'pthread_getcpuclockid'),
91 'need time.pthread_getcpuclockid()')
92 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
93 'need time.clock_gettime()')
pdoxe14679c2017-10-05 00:01:56 -070094 def test_pthread_getcpuclockid(self):
95 clk_id = time.pthread_getcpuclockid(threading.get_ident())
96 self.assertTrue(type(clk_id) is int)
97 self.assertNotEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
pdoxe14679c2017-10-05 00:01:56 -070098 t1 = time.clock_gettime(clk_id)
Benjamin Peterson86566702017-10-05 22:50:42 -070099 t2 = time.clock_gettime(clk_id)
pdoxe14679c2017-10-05 00:01:56 -0700100 self.assertLessEqual(t1, t2)
pdoxe14679c2017-10-05 00:01:56 -0700101
Victor Stinnere0be4232011-10-25 13:06:09 +0200102 @unittest.skipUnless(hasattr(time, 'clock_getres'),
103 'need time.clock_getres()')
104 def test_clock_getres(self):
105 res = time.clock_getres(time.CLOCK_REALTIME)
106 self.assertGreater(res, 0.0)
107 self.assertLessEqual(res, 1.0)
108
Victor Stinner30d79472012-04-03 00:45:07 +0200109 @unittest.skipUnless(hasattr(time, 'clock_settime'),
110 'need time.clock_settime()')
111 def test_clock_settime(self):
112 t = time.clock_gettime(time.CLOCK_REALTIME)
113 try:
114 time.clock_settime(time.CLOCK_REALTIME, t)
115 except PermissionError:
116 pass
117
Victor Stinnerec895392012-04-29 02:41:27 +0200118 if hasattr(time, 'CLOCK_MONOTONIC'):
119 self.assertRaises(OSError,
120 time.clock_settime, time.CLOCK_MONOTONIC, 0)
Victor Stinner30d79472012-04-03 00:45:07 +0200121
Fred Drakebc561982001-05-22 17:02:02 +0000122 def test_conversions(self):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000123 self.assertEqual(time.ctime(self.t),
124 time.asctime(time.localtime(self.t)))
125 self.assertEqual(int(time.mktime(time.localtime(self.t))),
126 int(self.t))
Fred Drakebc561982001-05-22 17:02:02 +0000127
128 def test_sleep(self):
Victor Stinner7f53a502011-07-05 22:00:25 +0200129 self.assertRaises(ValueError, time.sleep, -2)
130 self.assertRaises(ValueError, time.sleep, -1)
Fred Drakebc561982001-05-22 17:02:02 +0000131 time.sleep(1.2)
132
133 def test_strftime(self):
134 tt = time.gmtime(self.t)
135 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
136 'j', 'm', 'M', 'p', 'S',
137 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
138 format = ' %' + directive
139 try:
140 time.strftime(format, tt)
141 except ValueError:
142 self.fail('conversion specifier: %r failed.' % format)
143
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300144 self.assertRaises(TypeError, time.strftime, b'%S', tt)
145 # embedded null character
146 self.assertRaises(ValueError, time.strftime, '%S\0', tt)
147
Florent Xicluna49ce0682011-11-01 12:56:14 +0100148 def _bounds_checking(self, func):
Brett Cannond1080a32004-03-02 04:38:10 +0000149 # Make sure that strftime() checks the bounds of the various parts
Florent Xicluna49ce0682011-11-01 12:56:14 +0100150 # of the time tuple (0 is valid for *all* values).
Brett Cannond1080a32004-03-02 04:38:10 +0000151
Victor Stinner73ea29c2011-01-08 01:56:31 +0000152 # The year field is tested by other test cases above
153
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000154 # Check month [1, 12] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100155 func((1900, 0, 1, 0, 0, 0, 0, 1, -1))
156 func((1900, 12, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000157 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000158 (1900, -1, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000159 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000160 (1900, 13, 1, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000161 # Check day of month [1, 31] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100162 func((1900, 1, 0, 0, 0, 0, 0, 1, -1))
163 func((1900, 1, 31, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000164 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000165 (1900, 1, -1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000166 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000167 (1900, 1, 32, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000168 # Check hour [0, 23]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100169 func((1900, 1, 1, 23, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000170 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000171 (1900, 1, 1, -1, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000172 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000173 (1900, 1, 1, 24, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000174 # Check minute [0, 59]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100175 func((1900, 1, 1, 0, 59, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000176 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000177 (1900, 1, 1, 0, -1, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000178 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000179 (1900, 1, 1, 0, 60, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000180 # Check second [0, 61]
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000181 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000182 (1900, 1, 1, 0, 0, -1, 0, 1, -1))
183 # C99 only requires allowing for one leap second, but Python's docs say
184 # allow two leap seconds (0..61)
Florent Xicluna49ce0682011-11-01 12:56:14 +0100185 func((1900, 1, 1, 0, 0, 60, 0, 1, -1))
186 func((1900, 1, 1, 0, 0, 61, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000187 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000188 (1900, 1, 1, 0, 0, 62, 0, 1, -1))
189 # No check for upper-bound day of week;
190 # value forced into range by a ``% 7`` calculation.
191 # Start check at -2 since gettmarg() increments value before taking
192 # modulo.
Florent Xicluna49ce0682011-11-01 12:56:14 +0100193 self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)),
194 func((1900, 1, 1, 0, 0, 0, +6, 1, -1)))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000195 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000196 (1900, 1, 1, 0, 0, 0, -2, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000197 # Check day of the year [1, 366] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100198 func((1900, 1, 1, 0, 0, 0, 0, 0, -1))
199 func((1900, 1, 1, 0, 0, 0, 0, 366, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000200 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000201 (1900, 1, 1, 0, 0, 0, 0, -1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000202 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000203 (1900, 1, 1, 0, 0, 0, 0, 367, -1))
Brett Cannond1080a32004-03-02 04:38:10 +0000204
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000205 def test_strftime_bounding_check(self):
206 self._bounds_checking(lambda tup: time.strftime('', tup))
207
Steve Dowere5b58952015-09-06 19:20:51 -0700208 def test_strftime_format_check(self):
209 # Test that strftime does not crash on invalid format strings
210 # that may trigger a buffer overread. When not triggered,
211 # strftime may succeed or raise ValueError depending on
212 # the platform.
213 for x in [ '', 'A', '%A', '%AA' ]:
214 for y in range(0x0, 0x10):
215 for z in [ '%', 'A%', 'AA%', '%A%', 'A%A%', '%#' ]:
216 try:
217 time.strftime(x * y + z)
218 except ValueError:
219 pass
220
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000221 def test_default_values_for_zero(self):
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400222 # Make sure that using all zeros uses the proper default
223 # values. No test for daylight savings since strftime() does
224 # not change output based on its value and no test for year
225 # because systems vary in their support for year 0.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000226 expected = "2000 01 01 00 00 00 1 001"
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000227 with support.check_warnings():
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400228 result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000229 self.assertEqual(expected, result)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000230
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000231 def test_strptime(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000232 # Should be able to go round-trip from strftime to strptime without
Andrew Svetlov737fb892012-12-18 21:14:22 +0200233 # raising an exception.
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000234 tt = time.gmtime(self.t)
235 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
236 'j', 'm', 'M', 'p', 'S',
237 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000238 format = '%' + directive
239 strf_output = time.strftime(format, tt)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000240 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000241 time.strptime(strf_output, format)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000242 except ValueError:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000243 self.fail("conversion specifier %r failed with '%s' input." %
244 (format, strf_output))
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000245
Brett Cannon7f6b4f82009-03-30 21:30:26 +0000246 def test_strptime_bytes(self):
247 # Make sure only strings are accepted as arguments to strptime.
248 self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
249 self.assertRaises(TypeError, time.strptime, '2009', b'%Y')
250
Ezio Melotti0f389082013-04-04 02:09:20 +0300251 def test_strptime_exception_context(self):
252 # check that this doesn't chain exceptions needlessly (see #17572)
253 with self.assertRaises(ValueError) as e:
254 time.strptime('', '%D')
255 self.assertIs(e.exception.__suppress_context__, True)
Serhiy Storchakacdac3022013-11-24 18:15:37 +0200256 # additional check for IndexError branch (issue #19545)
257 with self.assertRaises(ValueError) as e:
258 time.strptime('19', '%Y %')
259 self.assertIs(e.exception.__suppress_context__, True)
Ezio Melotti0f389082013-04-04 02:09:20 +0300260
Fred Drakebc561982001-05-22 17:02:02 +0000261 def test_asctime(self):
262 time.asctime(time.gmtime(self.t))
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000263
264 # Max year is only limited by the size of C int.
Florent Xiclunabceb5282011-11-01 14:11:34 +0100265 for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
266 asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
267 self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
268 self.assertRaises(OverflowError, time.asctime,
269 (TIME_MAXYEAR + 1,) + (0,) * 8)
270 self.assertRaises(OverflowError, time.asctime,
271 (TIME_MINYEAR - 1,) + (0,) * 8)
Fred Drakebc561982001-05-22 17:02:02 +0000272 self.assertRaises(TypeError, time.asctime, 0)
Alexander Belopolskye2dc0822011-01-02 20:48:22 +0000273 self.assertRaises(TypeError, time.asctime, ())
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000274 self.assertRaises(TypeError, time.asctime, (0,) * 10)
Fred Drakebc561982001-05-22 17:02:02 +0000275
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000276 def test_asctime_bounding_check(self):
277 self._bounds_checking(time.asctime)
278
Georg Brandle10608c2011-01-02 22:33:43 +0000279 def test_ctime(self):
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000280 t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
281 self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
282 t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
283 self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000')
Victor Stinner1ac42612014-02-21 09:27:17 +0100284 for year in [-100, 100, 1000, 2000, 2050, 10000]:
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000285 try:
286 testval = time.mktime((year, 1, 10) + (0,)*6)
287 except (ValueError, OverflowError):
288 # If mktime fails, ctime will fail too. This may happen
289 # on some platforms.
290 pass
291 else:
292 self.assertEqual(time.ctime(testval)[20:], str(year))
Georg Brandle10608c2011-01-02 22:33:43 +0000293
Florent Xiclunae54371e2011-11-11 18:59:30 +0100294 @unittest.skipUnless(hasattr(time, "tzset"),
295 "time module has no attribute tzset")
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000296 def test_tzset(self):
Guido van Rossumd2b738e2003-03-15 12:01:52 +0000297
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000298 from os import environ
299
Tim Peters0eadaac2003-04-24 16:02:54 +0000300 # Epoch time of midnight Dec 25th 2002. Never DST in northern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000301 # hemisphere.
Tim Peters0eadaac2003-04-24 16:02:54 +0000302 xmas2002 = 1040774400.0
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000303
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000304 # These formats are correct for 2002, and possibly future years
305 # This format is the 'standard' as documented at:
306 # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
307 # They are also documented in the tzset(3) man page on most Unix
308 # systems.
Tim Peters0eadaac2003-04-24 16:02:54 +0000309 eastern = 'EST+05EDT,M4.1.0,M10.5.0'
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000310 victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
311 utc='UTC+0'
312
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000313 org_TZ = environ.get('TZ',None)
314 try:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000315 # Make sure we can switch to UTC time and results are correct
316 # Note that unknown timezones default to UTC.
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000317 # Note that altzone is undefined in UTC, as there is no DST
318 environ['TZ'] = eastern
319 time.tzset()
320 environ['TZ'] = utc
321 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000322 self.assertEqual(
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000323 time.gmtime(xmas2002), time.localtime(xmas2002)
324 )
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000325 self.assertEqual(time.daylight, 0)
326 self.assertEqual(time.timezone, 0)
327 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000328
329 # Make sure we can switch to US/Eastern
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000330 environ['TZ'] = eastern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000331 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000332 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
333 self.assertEqual(time.tzname, ('EST', 'EDT'))
334 self.assertEqual(len(time.tzname), 2)
335 self.assertEqual(time.daylight, 1)
336 self.assertEqual(time.timezone, 18000)
337 self.assertEqual(time.altzone, 14400)
338 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
339 self.assertEqual(len(time.tzname), 2)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000340
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000341 # Now go to the southern hemisphere.
342 environ['TZ'] = victoria
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000343 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000344 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
Victor Stinner0cd47902011-12-08 00:32:51 +0100345
346 # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100347 # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
348 # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
349 # on some operating systems (e.g. FreeBSD), which is wrong. See for
350 # example this bug:
351 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
Victor Stinner0cd47902011-12-08 00:32:51 +0100352 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100353 self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000354 self.assertEqual(len(time.tzname), 2)
355 self.assertEqual(time.daylight, 1)
356 self.assertEqual(time.timezone, -36000)
357 self.assertEqual(time.altzone, -39600)
358 self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000359
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000360 finally:
361 # Repair TZ environment variable in case any other tests
362 # rely on it.
363 if org_TZ is not None:
364 environ['TZ'] = org_TZ
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000365 elif 'TZ' in environ:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000366 del environ['TZ']
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000367 time.tzset()
Tim Peters0eadaac2003-04-24 16:02:54 +0000368
Tim Peters1b6f7a92004-06-20 02:50:16 +0000369 def test_insane_timestamps(self):
370 # It's possible that some platform maps time_t to double,
371 # and that this test will fail there. This test should
372 # exempt such platforms (provided they return reasonable
373 # results!).
374 for func in time.ctime, time.gmtime, time.localtime:
375 for unreasonable in -1e200, 1e200:
Victor Stinner5d272cc2012-03-13 13:35:55 +0100376 self.assertRaises(OverflowError, func, unreasonable)
Fred Drakebc561982001-05-22 17:02:02 +0000377
Fred Drakef901abd2004-08-03 17:58:55 +0000378 def test_ctime_without_arg(self):
379 # Not sure how to check the values, since the clock could tick
380 # at any time. Make sure these are at least accepted and
381 # don't raise errors.
382 time.ctime()
383 time.ctime(None)
384
385 def test_gmtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000386 gt0 = time.gmtime()
387 gt1 = time.gmtime(None)
388 t0 = time.mktime(gt0)
389 t1 = time.mktime(gt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000390 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000391
392 def test_localtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000393 lt0 = time.localtime()
394 lt1 = time.localtime(None)
395 t0 = time.mktime(lt0)
396 t1 = time.mktime(lt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000397 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000398
Florent Xiclunae54371e2011-11-11 18:59:30 +0100399 def test_mktime(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100400 # Issue #1726687
401 for t in (-2, -1, 0, 1):
Victor Stinner8c8b4e02014-02-21 23:54:32 +0100402 if sys.platform.startswith('aix') and t == -1:
403 # Issue #11188, #19748: mktime() returns -1 on error. On Linux,
404 # the tm_wday field is used as a sentinel () to detect if -1 is
405 # really an error or a valid timestamp. On AIX, tm_wday is
406 # unchanged even on success and so cannot be used as a
407 # sentinel.
408 continue
Florent Xiclunabceb5282011-11-01 14:11:34 +0100409 try:
410 tt = time.localtime(t)
Victor Stinner2cbae982012-01-27 00:50:33 +0100411 except (OverflowError, OSError):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100412 pass
413 else:
414 self.assertEqual(time.mktime(tt), t)
Florent Xiclunae54371e2011-11-11 18:59:30 +0100415
416 # Issue #13309: passing extreme values to mktime() or localtime()
417 # borks the glibc's internal timezone data.
418 @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
419 "disabled because of a bug in glibc. Issue #13309")
420 def test_mktime_error(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100421 # It may not be possible to reliably make mktime return error
422 # on all platfom. This will make sure that no other exception
423 # than OverflowError is raised for an extreme value.
Florent Xiclunae54371e2011-11-11 18:59:30 +0100424 tt = time.gmtime(self.t)
425 tzname = time.strftime('%Z', tt)
426 self.assertNotEqual(tzname, 'LMT')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100427 try:
428 time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
429 except OverflowError:
430 pass
Florent Xiclunae54371e2011-11-11 18:59:30 +0100431 self.assertEqual(time.strftime('%Z', tt), tzname)
Florent Xiclunabceb5282011-11-01 14:11:34 +0100432
Victor Stinnerec895392012-04-29 02:41:27 +0200433 def test_monotonic(self):
Victor Stinner6c861812013-11-23 00:15:27 +0100434 # monotonic() should not go backward
435 times = [time.monotonic() for n in range(100)]
436 t1 = times[0]
437 for t2 in times[1:]:
438 self.assertGreaterEqual(t2, t1, "times=%s" % times)
439 t1 = t2
440
441 # monotonic() includes time elapsed during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200442 t1 = time.monotonic()
Victor Stinnera9c99a62013-07-03 23:07:37 +0200443 time.sleep(0.5)
Victor Stinnerec895392012-04-29 02:41:27 +0200444 t2 = time.monotonic()
Victor Stinner2dd254d2012-01-20 02:24:18 +0100445 dt = t2 - t1
Victor Stinner8b302012012-02-07 23:29:46 +0100446 self.assertGreater(t2, t1)
Zachary Ware487aedb2014-01-02 09:41:10 -0600447 # Issue #20101: On some Windows machines, dt may be slightly low
448 self.assertTrue(0.45 <= dt <= 1.0, dt)
Antoine Pitrou391166f2012-01-18 22:35:21 +0100449
Victor Stinner6c861812013-11-23 00:15:27 +0100450 # monotonic() is a monotonic but non adjustable clock
Victor Stinnerec895392012-04-29 02:41:27 +0200451 info = time.get_clock_info('monotonic')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400452 self.assertTrue(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +0200453 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200454
455 def test_perf_counter(self):
456 time.perf_counter()
457
458 def test_process_time(self):
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200459 # process_time() should not include time spend during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200460 start = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200461 time.sleep(0.100)
Victor Stinnerec895392012-04-29 02:41:27 +0200462 stop = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200463 # use 20 ms because process_time() has usually a resolution of 15 ms
464 # on Windows
465 self.assertLess(stop - start, 0.020)
Victor Stinnerec895392012-04-29 02:41:27 +0200466
467 info = time.get_clock_info('process_time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400468 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200469 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200470
Victor Stinnerec895392012-04-29 02:41:27 +0200471 @unittest.skipUnless(hasattr(time, 'clock_settime'),
472 'need time.clock_settime')
473 def test_monotonic_settime(self):
474 t1 = time.monotonic()
475 realtime = time.clock_gettime(time.CLOCK_REALTIME)
476 # jump backward with an offset of 1 hour
Victor Stinner071eca32012-03-15 01:17:09 +0100477 try:
Victor Stinnerec895392012-04-29 02:41:27 +0200478 time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
479 except PermissionError as err:
480 self.skipTest(err)
481 t2 = time.monotonic()
482 time.clock_settime(time.CLOCK_REALTIME, realtime)
483 # monotonic must not be affected by system clock updates
Victor Stinner071eca32012-03-15 01:17:09 +0100484 self.assertGreaterEqual(t2, t1)
485
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100486 def test_localtime_failure(self):
487 # Issue #13847: check for localtime() failure
Victor Stinner53d36452012-01-27 01:03:25 +0100488 invalid_time_t = None
489 for time_t in (-1, 2**30, 2**33, 2**60):
490 try:
491 time.localtime(time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100492 except OverflowError:
493 self.skipTest("need 64-bit time_t")
Victor Stinner53d36452012-01-27 01:03:25 +0100494 except OSError:
495 invalid_time_t = time_t
496 break
497 if invalid_time_t is None:
498 self.skipTest("unable to find an invalid time_t value")
499
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100500 self.assertRaises(OSError, time.localtime, invalid_time_t)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100501 self.assertRaises(OSError, time.ctime, invalid_time_t)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100502
Han Lee829dacc2017-09-09 08:05:05 +0900503 # Issue #26669: check for localtime() failure
504 self.assertRaises(ValueError, time.localtime, float("nan"))
505 self.assertRaises(ValueError, time.ctime, float("nan"))
506
Victor Stinnerec895392012-04-29 02:41:27 +0200507 def test_get_clock_info(self):
Victor Stinner884d13a2017-10-17 14:46:45 -0700508 clocks = ['clock', 'monotonic', 'perf_counter', 'process_time', 'time']
Victor Stinnerec895392012-04-29 02:41:27 +0200509
510 for name in clocks:
Victor Stinner884d13a2017-10-17 14:46:45 -0700511 if name == 'clock':
512 with self.assertWarns(DeprecationWarning):
513 info = time.get_clock_info('clock')
514 else:
515 info = time.get_clock_info(name)
516
Victor Stinnerec895392012-04-29 02:41:27 +0200517 #self.assertIsInstance(info, dict)
518 self.assertIsInstance(info.implementation, str)
519 self.assertNotEqual(info.implementation, '')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400520 self.assertIsInstance(info.monotonic, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200521 self.assertIsInstance(info.resolution, float)
522 # 0.0 < resolution <= 1.0
523 self.assertGreater(info.resolution, 0.0)
524 self.assertLessEqual(info.resolution, 1.0)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200525 self.assertIsInstance(info.adjustable, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200526
527 self.assertRaises(ValueError, time.get_clock_info, 'xxx')
528
529
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000530class TestLocale(unittest.TestCase):
531 def setUp(self):
532 self.oldloc = locale.setlocale(locale.LC_ALL)
Fred Drake2e2be372001-09-20 21:33:42 +0000533
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000534 def tearDown(self):
535 locale.setlocale(locale.LC_ALL, self.oldloc)
536
Martin v. Löwisa6a9c4d2009-05-30 06:15:30 +0000537 def test_bug_3061(self):
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000538 try:
539 tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
540 except locale.Error:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600541 self.skipTest('could not set locale.LC_ALL to fr_FR')
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000542 # This should not cause an exception
543 time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
544
Victor Stinner73ea29c2011-01-08 01:56:31 +0000545
Victor Stinner73ea29c2011-01-08 01:56:31 +0000546class _TestAsctimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100547 _format = '%d'
548
Victor Stinner73ea29c2011-01-08 01:56:31 +0000549 def yearstr(self, y):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000550 return time.asctime((y,) + (0,) * 8).split()[-1]
Alexander Belopolskya6867252011-01-05 23:00:47 +0000551
Victor Stinner73ea29c2011-01-08 01:56:31 +0000552 def test_large_year(self):
Victor Stinner73691322011-01-08 02:00:24 +0000553 # Check that it doesn't crash for year > 9999
Victor Stinner73ea29c2011-01-08 01:56:31 +0000554 self.assertEqual(self.yearstr(12345), '12345')
555 self.assertEqual(self.yearstr(123456789), '123456789')
556
557class _TestStrftimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100558
559 # Issue 13305: For years < 1000, the value is not always
560 # padded to 4 digits across platforms. The C standard
561 # assumes year >= 1900, so it does not specify the number
562 # of digits.
563
564 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
565 _format = '%04d'
566 else:
567 _format = '%d'
568
Victor Stinner73ea29c2011-01-08 01:56:31 +0000569 def yearstr(self, y):
Florent Xicluna49ce0682011-11-01 12:56:14 +0100570 return time.strftime('%Y', (y,) + (0,) * 8)
571
572 def test_4dyear(self):
573 # Check that we can return the zero padded value.
574 if self._format == '%04d':
575 self.test_year('%04d')
576 else:
577 def year4d(y):
578 return time.strftime('%4Y', (y,) + (0,) * 8)
579 self.test_year('%04d', func=year4d)
580
Florent Xiclunabceb5282011-11-01 14:11:34 +0100581 def skip_if_not_supported(y):
582 msg = "strftime() is limited to [1; 9999] with Visual Studio"
583 # Check that it doesn't crash for year > 9999
584 try:
585 time.strftime('%Y', (y,) + (0,) * 8)
586 except ValueError:
587 cond = False
588 else:
589 cond = True
590 return unittest.skipUnless(cond, msg)
591
592 @skip_if_not_supported(10000)
593 def test_large_year(self):
594 return super().test_large_year()
595
596 @skip_if_not_supported(0)
597 def test_negative(self):
598 return super().test_negative()
599
600 del skip_if_not_supported
601
602
Ezio Melotti3836d702013-04-11 20:29:42 +0300603class _Test4dYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100604 _format = '%d'
605
606 def test_year(self, fmt=None, func=None):
607 fmt = fmt or self._format
608 func = func or self.yearstr
609 self.assertEqual(func(1), fmt % 1)
610 self.assertEqual(func(68), fmt % 68)
611 self.assertEqual(func(69), fmt % 69)
612 self.assertEqual(func(99), fmt % 99)
613 self.assertEqual(func(999), fmt % 999)
614 self.assertEqual(func(9999), fmt % 9999)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000615
616 def test_large_year(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100617 self.assertEqual(self.yearstr(12345), '12345')
Victor Stinner13ed2ea2011-03-21 02:11:01 +0100618 self.assertEqual(self.yearstr(123456789), '123456789')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100619 self.assertEqual(self.yearstr(TIME_MAXYEAR), str(TIME_MAXYEAR))
620 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000621
Victor Stinner301f1212011-01-08 03:06:52 +0000622 def test_negative(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100623 self.assertEqual(self.yearstr(-1), self._format % -1)
Victor Stinner301f1212011-01-08 03:06:52 +0000624 self.assertEqual(self.yearstr(-1234), '-1234')
625 self.assertEqual(self.yearstr(-123456), '-123456')
Florent Xiclunad1bd7f72011-11-01 23:42:05 +0100626 self.assertEqual(self.yearstr(-123456789), str(-123456789))
627 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
Florent Xicluna2fbc1852011-11-02 08:13:43 +0100628 self.assertEqual(self.yearstr(TIME_MINYEAR + 1900), str(TIME_MINYEAR + 1900))
629 # Issue #13312: it may return wrong value for year < TIME_MINYEAR + 1900
630 # Skip the value test, but check that no error is raised
631 self.yearstr(TIME_MINYEAR)
Florent Xiclunae2a732e2011-11-02 01:28:17 +0100632 # self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
Florent Xiclunabceb5282011-11-01 14:11:34 +0100633 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
Victor Stinner301f1212011-01-08 03:06:52 +0000634
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000635
Ezio Melotti3836d702013-04-11 20:29:42 +0300636class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner73ea29c2011-01-08 01:56:31 +0000637 pass
638
Ezio Melotti3836d702013-04-11 20:29:42 +0300639class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner301f1212011-01-08 03:06:52 +0000640 pass
Victor Stinner73ea29c2011-01-08 01:56:31 +0000641
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000642
Victor Stinner643cd682012-03-02 22:54:03 +0100643class TestPytime(unittest.TestCase):
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400644 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
645 def test_localtime_timezone(self):
Victor Stinner643cd682012-03-02 22:54:03 +0100646
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400647 # Get the localtime and examine it for the offset and zone.
648 lt = time.localtime()
649 self.assertTrue(hasattr(lt, "tm_gmtoff"))
650 self.assertTrue(hasattr(lt, "tm_zone"))
651
652 # See if the offset and zone are similar to the module
653 # attributes.
654 if lt.tm_gmtoff is None:
655 self.assertTrue(not hasattr(time, "timezone"))
656 else:
657 self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
658 if lt.tm_zone is None:
659 self.assertTrue(not hasattr(time, "tzname"))
660 else:
661 self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
662
663 # Try and make UNIX times from the localtime and a 9-tuple
664 # created from the localtime. Test to see that the times are
665 # the same.
666 t = time.mktime(lt); t9 = time.mktime(lt[:9])
667 self.assertEqual(t, t9)
668
669 # Make localtimes from the UNIX times and compare them to
670 # the original localtime, thus making a round trip.
671 new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
672 self.assertEqual(new_lt, lt)
673 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
674 self.assertEqual(new_lt.tm_zone, lt.tm_zone)
675 self.assertEqual(new_lt9, lt)
676 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
677 self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
678
679 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
680 def test_strptime_timezone(self):
681 t = time.strptime("UTC", "%Z")
682 self.assertEqual(t.tm_zone, 'UTC')
683 t = time.strptime("+0500", "%z")
684 self.assertEqual(t.tm_gmtoff, 5 * 3600)
685
686 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
687 def test_short_times(self):
688
689 import pickle
690
691 # Load a short time structure using pickle.
692 st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
693 lt = pickle.loads(st)
694 self.assertIs(lt.tm_gmtoff, None)
695 self.assertIs(lt.tm_zone, None)
Victor Stinner643cd682012-03-02 22:54:03 +0100696
Fred Drake2e2be372001-09-20 21:33:42 +0000697
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200698@unittest.skipIf(_testcapi is None, 'need the _testcapi module')
699class CPyTimeTestCase:
Victor Stinneracea9f62015-09-02 10:39:40 +0200700 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200701 Base class to test the C _PyTime_t API.
Victor Stinneracea9f62015-09-02 10:39:40 +0200702 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200703 OVERFLOW_SECONDS = None
704
Victor Stinner4237d342015-09-10 10:10:39 +0200705 def setUp(self):
706 from _testcapi import SIZEOF_TIME_T
707 bits = SIZEOF_TIME_T * 8 - 1
708 self.time_t_min = -2 ** bits
709 self.time_t_max = 2 ** bits - 1
710
711 def time_t_filter(self, seconds):
712 return (self.time_t_min <= seconds <= self.time_t_max)
713
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200714 def _rounding_values(self, use_float):
715 "Build timestamps used to test rounding."
716
717 units = [1, US_TO_NS, MS_TO_NS, SEC_TO_NS]
718 if use_float:
719 # picoseconds are only tested to pytime_converter accepting floats
720 units.append(1e-3)
721
722 values = (
723 # small values
724 1, 2, 5, 7, 123, 456, 1234,
725 # 10^k - 1
726 9,
727 99,
728 999,
729 9999,
730 99999,
731 999999,
732 # test half even rounding near 0.5, 1.5, 2.5, 3.5, 4.5
733 499, 500, 501,
734 1499, 1500, 1501,
735 2500,
736 3500,
737 4500,
738 )
739
740 ns_timestamps = [0]
741 for unit in units:
742 for value in values:
743 ns = value * unit
744 ns_timestamps.extend((-ns, ns))
745 for pow2 in (0, 5, 10, 15, 22, 23, 24, 30, 33):
746 ns = (2 ** pow2) * SEC_TO_NS
747 ns_timestamps.extend((
748 -ns-1, -ns, -ns+1,
749 ns-1, ns, ns+1
750 ))
751 for seconds in (_testcapi.INT_MIN, _testcapi.INT_MAX):
752 ns_timestamps.append(seconds * SEC_TO_NS)
753 if use_float:
Victor Stinner717a32b2016-08-17 11:07:21 +0200754 # numbers with an exact representation in IEEE 754 (base 2)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200755 for pow2 in (3, 7, 10, 15):
756 ns = 2.0 ** (-pow2)
757 ns_timestamps.extend((-ns, ns))
758
759 # seconds close to _PyTime_t type limit
760 ns = (2 ** 63 // SEC_TO_NS) * SEC_TO_NS
761 ns_timestamps.extend((-ns, ns))
762
763 return ns_timestamps
764
765 def _check_rounding(self, pytime_converter, expected_func,
766 use_float, unit_to_sec, value_filter=None):
767
768 def convert_values(ns_timestamps):
769 if use_float:
770 unit_to_ns = SEC_TO_NS / float(unit_to_sec)
771 values = [ns / unit_to_ns for ns in ns_timestamps]
772 else:
773 unit_to_ns = SEC_TO_NS // unit_to_sec
774 values = [ns // unit_to_ns for ns in ns_timestamps]
775
776 if value_filter:
777 values = filter(value_filter, values)
778
779 # remove duplicates and sort
780 return sorted(set(values))
781
782 # test rounding
783 ns_timestamps = self._rounding_values(use_float)
784 valid_values = convert_values(ns_timestamps)
785 for time_rnd, decimal_rnd in ROUNDING_MODES :
786 context = decimal.getcontext()
787 context.rounding = decimal_rnd
788
789 for value in valid_values:
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200790 debug_info = {'value': value, 'rounding': decimal_rnd}
791 try:
792 result = pytime_converter(value, time_rnd)
793 expected = expected_func(value)
794 except Exception as exc:
795 self.fail("Error on timestamp conversion: %s" % debug_info)
796 self.assertEqual(result,
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200797 expected,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200798 debug_info)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200799
800 # test overflow
801 ns = self.OVERFLOW_SECONDS * SEC_TO_NS
802 ns_timestamps = (-ns, ns)
803 overflow_values = convert_values(ns_timestamps)
804 for time_rnd, _ in ROUNDING_MODES :
805 for value in overflow_values:
Victor Stinnerc60542b2015-09-10 15:55:07 +0200806 debug_info = {'value': value, 'rounding': time_rnd}
807 with self.assertRaises(OverflowError, msg=debug_info):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200808 pytime_converter(value, time_rnd)
809
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200810 def check_int_rounding(self, pytime_converter, expected_func,
811 unit_to_sec=1, value_filter=None):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200812 self._check_rounding(pytime_converter, expected_func,
813 False, unit_to_sec, value_filter)
814
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200815 def check_float_rounding(self, pytime_converter, expected_func,
816 unit_to_sec=1, value_filter=None):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200817 self._check_rounding(pytime_converter, expected_func,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200818 True, unit_to_sec, value_filter)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200819
820 def decimal_round(self, x):
821 d = decimal.Decimal(x)
822 d = d.quantize(1)
823 return int(d)
824
825
826class TestCPyTime(CPyTimeTestCase, unittest.TestCase):
827 """
828 Test the C _PyTime_t API.
829 """
830 # _PyTime_t is a 64-bit signed integer
831 OVERFLOW_SECONDS = math.ceil((2**63 + 1) / SEC_TO_NS)
832
Victor Stinner13019fd2015-04-03 13:10:54 +0200833 def test_FromSeconds(self):
834 from _testcapi import PyTime_FromSeconds
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200835
836 # PyTime_FromSeconds() expects a C int, reject values out of range
837 def c_int_filter(secs):
838 return (_testcapi.INT_MIN <= secs <= _testcapi.INT_MAX)
839
840 self.check_int_rounding(lambda secs, rnd: PyTime_FromSeconds(secs),
841 lambda secs: secs * SEC_TO_NS,
842 value_filter=c_int_filter)
Victor Stinner13019fd2015-04-03 13:10:54 +0200843
Han Lee829dacc2017-09-09 08:05:05 +0900844 # test nan
845 for time_rnd, _ in ROUNDING_MODES:
846 with self.assertRaises(TypeError):
847 PyTime_FromSeconds(float('nan'))
848
Victor Stinner992c43f2015-03-27 17:12:45 +0100849 def test_FromSecondsObject(self):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100850 from _testcapi import PyTime_FromSecondsObject
Victor Stinner992c43f2015-03-27 17:12:45 +0100851
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200852 self.check_int_rounding(
853 PyTime_FromSecondsObject,
854 lambda secs: secs * SEC_TO_NS)
Victor Stinner992c43f2015-03-27 17:12:45 +0100855
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200856 self.check_float_rounding(
857 PyTime_FromSecondsObject,
858 lambda ns: self.decimal_round(ns * SEC_TO_NS))
Victor Stinner4bfb4602015-03-27 22:27:24 +0100859
Han Lee829dacc2017-09-09 08:05:05 +0900860 # test nan
861 for time_rnd, _ in ROUNDING_MODES:
862 with self.assertRaises(ValueError):
863 PyTime_FromSecondsObject(float('nan'), time_rnd)
864
Victor Stinner4bfb4602015-03-27 22:27:24 +0100865 def test_AsSecondsDouble(self):
866 from _testcapi import PyTime_AsSecondsDouble
867
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200868 def float_converter(ns):
869 if abs(ns) % SEC_TO_NS == 0:
870 return float(ns // SEC_TO_NS)
871 else:
872 return float(ns) / SEC_TO_NS
Victor Stinner4bfb4602015-03-27 22:27:24 +0100873
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200874 self.check_int_rounding(lambda ns, rnd: PyTime_AsSecondsDouble(ns),
875 float_converter,
876 NS_TO_SEC)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100877
Han Lee829dacc2017-09-09 08:05:05 +0900878 # test nan
879 for time_rnd, _ in ROUNDING_MODES:
880 with self.assertRaises(TypeError):
881 PyTime_AsSecondsDouble(float('nan'))
882
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200883 def create_decimal_converter(self, denominator):
884 denom = decimal.Decimal(denominator)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100885
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200886 def converter(value):
887 d = decimal.Decimal(value) / denom
888 return self.decimal_round(d)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100889
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200890 return converter
Victor Stinner4bfb4602015-03-27 22:27:24 +0100891
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200892 def test_AsTimeval(self):
Victor Stinner95e9cef2015-03-28 01:26:47 +0100893 from _testcapi import PyTime_AsTimeval
Victor Stinner95e9cef2015-03-28 01:26:47 +0100894
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200895 us_converter = self.create_decimal_converter(US_TO_NS)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100896
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200897 def timeval_converter(ns):
898 us = us_converter(ns)
899 return divmod(us, SEC_TO_US)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100900
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200901 if sys.platform == 'win32':
902 from _testcapi import LONG_MIN, LONG_MAX
903
904 # On Windows, timeval.tv_sec type is a C long
905 def seconds_filter(secs):
906 return LONG_MIN <= secs <= LONG_MAX
907 else:
Victor Stinner4237d342015-09-10 10:10:39 +0200908 seconds_filter = self.time_t_filter
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200909
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200910 self.check_int_rounding(PyTime_AsTimeval,
911 timeval_converter,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200912 NS_TO_SEC,
913 value_filter=seconds_filter)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100914
Victor Stinner34dc0f42015-03-27 18:19:03 +0100915 @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec'),
916 'need _testcapi.PyTime_AsTimespec')
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200917 def test_AsTimespec(self):
Victor Stinner34dc0f42015-03-27 18:19:03 +0100918 from _testcapi import PyTime_AsTimespec
Victor Stinner34dc0f42015-03-27 18:19:03 +0100919
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200920 def timespec_converter(ns):
921 return divmod(ns, SEC_TO_NS)
Victor Stinner34dc0f42015-03-27 18:19:03 +0100922
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200923 self.check_int_rounding(lambda ns, rnd: PyTime_AsTimespec(ns),
924 timespec_converter,
Victor Stinner4237d342015-09-10 10:10:39 +0200925 NS_TO_SEC,
926 value_filter=self.time_t_filter)
Victor Stinner34dc0f42015-03-27 18:19:03 +0100927
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200928 def test_AsMilliseconds(self):
Victor Stinner62d1c702015-04-01 17:47:07 +0200929 from _testcapi import PyTime_AsMilliseconds
Victor Stinner62d1c702015-04-01 17:47:07 +0200930
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200931 self.check_int_rounding(PyTime_AsMilliseconds,
932 self.create_decimal_converter(MS_TO_NS),
933 NS_TO_SEC)
Victor Stinner62d1c702015-04-01 17:47:07 +0200934
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200935 def test_AsMicroseconds(self):
Victor Stinner62d1c702015-04-01 17:47:07 +0200936 from _testcapi import PyTime_AsMicroseconds
Victor Stinner62d1c702015-04-01 17:47:07 +0200937
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200938 self.check_int_rounding(PyTime_AsMicroseconds,
939 self.create_decimal_converter(US_TO_NS),
940 NS_TO_SEC)
Victor Stinner62d1c702015-04-01 17:47:07 +0200941
Victor Stinner992c43f2015-03-27 17:12:45 +0100942
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200943class TestOldPyTime(CPyTimeTestCase, unittest.TestCase):
Victor Stinneracea9f62015-09-02 10:39:40 +0200944 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200945 Test the old C _PyTime_t API: _PyTime_ObjectToXXX() functions.
Victor Stinneracea9f62015-09-02 10:39:40 +0200946 """
Victor Stinneracea9f62015-09-02 10:39:40 +0200947
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200948 # time_t is a 32-bit or 64-bit signed integer
949 OVERFLOW_SECONDS = 2 ** 64
950
951 def test_object_to_time_t(self):
Victor Stinneracea9f62015-09-02 10:39:40 +0200952 from _testcapi import pytime_object_to_time_t
953
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200954 self.check_int_rounding(pytime_object_to_time_t,
Victor Stinner4237d342015-09-10 10:10:39 +0200955 lambda secs: secs,
956 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200957
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200958 self.check_float_rounding(pytime_object_to_time_t,
Victor Stinner350b5182015-09-10 11:45:06 +0200959 self.decimal_round,
960 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200961
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200962 def create_converter(self, sec_to_unit):
963 def converter(secs):
964 floatpart, intpart = math.modf(secs)
965 intpart = int(intpart)
966 floatpart *= sec_to_unit
967 floatpart = self.decimal_round(floatpart)
968 if floatpart < 0:
969 floatpart += sec_to_unit
970 intpart -= 1
971 elif floatpart >= sec_to_unit:
972 floatpart -= sec_to_unit
973 intpart += 1
974 return (intpart, floatpart)
975 return converter
Victor Stinneracea9f62015-09-02 10:39:40 +0200976
Victor Stinneradfefa52015-09-04 23:57:25 +0200977 def test_object_to_timeval(self):
Victor Stinneracea9f62015-09-02 10:39:40 +0200978 from _testcapi import pytime_object_to_timeval
979
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200980 self.check_int_rounding(pytime_object_to_timeval,
Victor Stinner4237d342015-09-10 10:10:39 +0200981 lambda secs: (secs, 0),
982 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200983
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200984 self.check_float_rounding(pytime_object_to_timeval,
Victor Stinner350b5182015-09-10 11:45:06 +0200985 self.create_converter(SEC_TO_US),
986 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200987
Han Lee829dacc2017-09-09 08:05:05 +0900988 # test nan
989 for time_rnd, _ in ROUNDING_MODES:
990 with self.assertRaises(ValueError):
991 pytime_object_to_timeval(float('nan'), time_rnd)
992
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200993 def test_object_to_timespec(self):
Victor Stinneracea9f62015-09-02 10:39:40 +0200994 from _testcapi import pytime_object_to_timespec
995
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200996 self.check_int_rounding(pytime_object_to_timespec,
Victor Stinner4237d342015-09-10 10:10:39 +0200997 lambda secs: (secs, 0),
998 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200999
Victor Stinner3e2c8d82015-09-09 22:32:48 +02001000 self.check_float_rounding(pytime_object_to_timespec,
Victor Stinner350b5182015-09-10 11:45:06 +02001001 self.create_converter(SEC_TO_NS),
1002 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001003
Han Lee829dacc2017-09-09 08:05:05 +09001004 # test nan
1005 for time_rnd, _ in ROUNDING_MODES:
1006 with self.assertRaises(ValueError):
1007 pytime_object_to_timespec(float('nan'), time_rnd)
1008
Victor Stinneracea9f62015-09-02 10:39:40 +02001009
Fred Drake2e2be372001-09-20 21:33:42 +00001010if __name__ == "__main__":
Ezio Melotti3836d702013-04-11 20:29:42 +03001011 unittest.main()