blob: c92e66bf49a01d0e05623a569237f195f038c13c [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
21TIME_MINYEAR = -TIME_MAXYEAR - 1
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
Victor Stinner992c43f2015-03-27 17:12:45 +010036
Victor Stinner3e2c8d82015-09-09 22:32:48 +020037# Rounding modes supported by PyTime
38ROUNDING_MODES = (
39 # (PyTime rounding method, decimal rounding method)
40 (_PyTime.ROUND_FLOOR, decimal.ROUND_FLOOR),
41 (_PyTime.ROUND_CEILING, decimal.ROUND_CEILING),
42 (_PyTime.ROUND_HALF_EVEN, decimal.ROUND_HALF_EVEN),
43)
Florent Xiclunabceb5282011-11-01 14:11:34 +010044
45
Fred Drakebc561982001-05-22 17:02:02 +000046class TimeTestCase(unittest.TestCase):
Barry Warsawb0c22321996-12-06 23:30:07 +000047
Fred Drakebc561982001-05-22 17:02:02 +000048 def setUp(self):
49 self.t = time.time()
Barry Warsawb0c22321996-12-06 23:30:07 +000050
Fred Drakebc561982001-05-22 17:02:02 +000051 def test_data_attributes(self):
52 time.altzone
53 time.daylight
54 time.timezone
55 time.tzname
Barry Warsawb0c22321996-12-06 23:30:07 +000056
Victor Stinnerec895392012-04-29 02:41:27 +020057 def test_time(self):
58 time.time()
59 info = time.get_clock_info('time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040060 self.assertFalse(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +020061 self.assertTrue(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020062
Fred Drakebc561982001-05-22 17:02:02 +000063 def test_clock(self):
64 time.clock()
Barry Warsawb0c22321996-12-06 23:30:07 +000065
Victor Stinnerec895392012-04-29 02:41:27 +020066 info = time.get_clock_info('clock')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040067 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +020068 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020069
Victor Stinnere0be4232011-10-25 13:06:09 +020070 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
71 'need time.clock_gettime()')
72 def test_clock_realtime(self):
73 time.clock_gettime(time.CLOCK_REALTIME)
74
75 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
76 'need time.clock_gettime()')
77 @unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'),
78 'need time.CLOCK_MONOTONIC')
79 def test_clock_monotonic(self):
80 a = time.clock_gettime(time.CLOCK_MONOTONIC)
81 b = time.clock_gettime(time.CLOCK_MONOTONIC)
82 self.assertLessEqual(a, b)
83
pdoxe14679c2017-10-05 00:01:56 -070084 @unittest.skipUnless(hasattr(time, 'pthread_getcpuclockid'),
85 'need time.pthread_getcpuclockid()')
86 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
87 'need time.clock_gettime()')
pdoxe14679c2017-10-05 00:01:56 -070088 def test_pthread_getcpuclockid(self):
89 clk_id = time.pthread_getcpuclockid(threading.get_ident())
90 self.assertTrue(type(clk_id) is int)
91 self.assertNotEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
pdoxe14679c2017-10-05 00:01:56 -070092 t1 = time.clock_gettime(clk_id)
Benjamin Peterson86566702017-10-05 22:50:42 -070093 t2 = time.clock_gettime(clk_id)
pdoxe14679c2017-10-05 00:01:56 -070094 self.assertLessEqual(t1, t2)
pdoxe14679c2017-10-05 00:01:56 -070095
Victor Stinnere0be4232011-10-25 13:06:09 +020096 @unittest.skipUnless(hasattr(time, 'clock_getres'),
97 'need time.clock_getres()')
98 def test_clock_getres(self):
99 res = time.clock_getres(time.CLOCK_REALTIME)
100 self.assertGreater(res, 0.0)
101 self.assertLessEqual(res, 1.0)
102
Victor Stinner30d79472012-04-03 00:45:07 +0200103 @unittest.skipUnless(hasattr(time, 'clock_settime'),
104 'need time.clock_settime()')
105 def test_clock_settime(self):
106 t = time.clock_gettime(time.CLOCK_REALTIME)
107 try:
108 time.clock_settime(time.CLOCK_REALTIME, t)
109 except PermissionError:
110 pass
111
Victor Stinnerec895392012-04-29 02:41:27 +0200112 if hasattr(time, 'CLOCK_MONOTONIC'):
113 self.assertRaises(OSError,
114 time.clock_settime, time.CLOCK_MONOTONIC, 0)
Victor Stinner30d79472012-04-03 00:45:07 +0200115
Fred Drakebc561982001-05-22 17:02:02 +0000116 def test_conversions(self):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000117 self.assertEqual(time.ctime(self.t),
118 time.asctime(time.localtime(self.t)))
119 self.assertEqual(int(time.mktime(time.localtime(self.t))),
120 int(self.t))
Fred Drakebc561982001-05-22 17:02:02 +0000121
122 def test_sleep(self):
Victor Stinner7f53a502011-07-05 22:00:25 +0200123 self.assertRaises(ValueError, time.sleep, -2)
124 self.assertRaises(ValueError, time.sleep, -1)
Fred Drakebc561982001-05-22 17:02:02 +0000125 time.sleep(1.2)
126
127 def test_strftime(self):
128 tt = time.gmtime(self.t)
129 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
130 'j', 'm', 'M', 'p', 'S',
131 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
132 format = ' %' + directive
133 try:
134 time.strftime(format, tt)
135 except ValueError:
136 self.fail('conversion specifier: %r failed.' % format)
137
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300138 self.assertRaises(TypeError, time.strftime, b'%S', tt)
139 # embedded null character
140 self.assertRaises(ValueError, time.strftime, '%S\0', tt)
141
Florent Xicluna49ce0682011-11-01 12:56:14 +0100142 def _bounds_checking(self, func):
Brett Cannond1080a32004-03-02 04:38:10 +0000143 # Make sure that strftime() checks the bounds of the various parts
Florent Xicluna49ce0682011-11-01 12:56:14 +0100144 # of the time tuple (0 is valid for *all* values).
Brett Cannond1080a32004-03-02 04:38:10 +0000145
Victor Stinner73ea29c2011-01-08 01:56:31 +0000146 # The year field is tested by other test cases above
147
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000148 # Check month [1, 12] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100149 func((1900, 0, 1, 0, 0, 0, 0, 1, -1))
150 func((1900, 12, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000151 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000152 (1900, -1, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000153 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000154 (1900, 13, 1, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000155 # Check day of month [1, 31] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100156 func((1900, 1, 0, 0, 0, 0, 0, 1, -1))
157 func((1900, 1, 31, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000158 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000159 (1900, 1, -1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000160 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000161 (1900, 1, 32, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000162 # Check hour [0, 23]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100163 func((1900, 1, 1, 23, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000164 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000165 (1900, 1, 1, -1, 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, 1, 24, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000168 # Check minute [0, 59]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100169 func((1900, 1, 1, 0, 59, 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, 0, -1, 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, 0, 60, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000174 # Check second [0, 61]
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000175 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000176 (1900, 1, 1, 0, 0, -1, 0, 1, -1))
177 # C99 only requires allowing for one leap second, but Python's docs say
178 # allow two leap seconds (0..61)
Florent Xicluna49ce0682011-11-01 12:56:14 +0100179 func((1900, 1, 1, 0, 0, 60, 0, 1, -1))
180 func((1900, 1, 1, 0, 0, 61, 0, 1, -1))
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, 62, 0, 1, -1))
183 # No check for upper-bound day of week;
184 # value forced into range by a ``% 7`` calculation.
185 # Start check at -2 since gettmarg() increments value before taking
186 # modulo.
Florent Xicluna49ce0682011-11-01 12:56:14 +0100187 self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)),
188 func((1900, 1, 1, 0, 0, 0, +6, 1, -1)))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000189 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000190 (1900, 1, 1, 0, 0, 0, -2, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000191 # Check day of the year [1, 366] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100192 func((1900, 1, 1, 0, 0, 0, 0, 0, -1))
193 func((1900, 1, 1, 0, 0, 0, 0, 366, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000194 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000195 (1900, 1, 1, 0, 0, 0, 0, -1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000196 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000197 (1900, 1, 1, 0, 0, 0, 0, 367, -1))
Brett Cannond1080a32004-03-02 04:38:10 +0000198
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000199 def test_strftime_bounding_check(self):
200 self._bounds_checking(lambda tup: time.strftime('', tup))
201
Steve Dowere5b58952015-09-06 19:20:51 -0700202 def test_strftime_format_check(self):
203 # Test that strftime does not crash on invalid format strings
204 # that may trigger a buffer overread. When not triggered,
205 # strftime may succeed or raise ValueError depending on
206 # the platform.
207 for x in [ '', 'A', '%A', '%AA' ]:
208 for y in range(0x0, 0x10):
209 for z in [ '%', 'A%', 'AA%', '%A%', 'A%A%', '%#' ]:
210 try:
211 time.strftime(x * y + z)
212 except ValueError:
213 pass
214
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000215 def test_default_values_for_zero(self):
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400216 # Make sure that using all zeros uses the proper default
217 # values. No test for daylight savings since strftime() does
218 # not change output based on its value and no test for year
219 # because systems vary in their support for year 0.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000220 expected = "2000 01 01 00 00 00 1 001"
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000221 with support.check_warnings():
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400222 result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000223 self.assertEqual(expected, result)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000224
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000225 def test_strptime(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000226 # Should be able to go round-trip from strftime to strptime without
Andrew Svetlov737fb892012-12-18 21:14:22 +0200227 # raising an exception.
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000228 tt = time.gmtime(self.t)
229 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
230 'j', 'm', 'M', 'p', 'S',
231 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000232 format = '%' + directive
233 strf_output = time.strftime(format, tt)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000234 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000235 time.strptime(strf_output, format)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000236 except ValueError:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000237 self.fail("conversion specifier %r failed with '%s' input." %
238 (format, strf_output))
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000239
Brett Cannon7f6b4f82009-03-30 21:30:26 +0000240 def test_strptime_bytes(self):
241 # Make sure only strings are accepted as arguments to strptime.
242 self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
243 self.assertRaises(TypeError, time.strptime, '2009', b'%Y')
244
Ezio Melotti0f389082013-04-04 02:09:20 +0300245 def test_strptime_exception_context(self):
246 # check that this doesn't chain exceptions needlessly (see #17572)
247 with self.assertRaises(ValueError) as e:
248 time.strptime('', '%D')
249 self.assertIs(e.exception.__suppress_context__, True)
Serhiy Storchakacdac3022013-11-24 18:15:37 +0200250 # additional check for IndexError branch (issue #19545)
251 with self.assertRaises(ValueError) as e:
252 time.strptime('19', '%Y %')
253 self.assertIs(e.exception.__suppress_context__, True)
Ezio Melotti0f389082013-04-04 02:09:20 +0300254
Fred Drakebc561982001-05-22 17:02:02 +0000255 def test_asctime(self):
256 time.asctime(time.gmtime(self.t))
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000257
258 # Max year is only limited by the size of C int.
Florent Xiclunabceb5282011-11-01 14:11:34 +0100259 for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
260 asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
261 self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
262 self.assertRaises(OverflowError, time.asctime,
263 (TIME_MAXYEAR + 1,) + (0,) * 8)
264 self.assertRaises(OverflowError, time.asctime,
265 (TIME_MINYEAR - 1,) + (0,) * 8)
Fred Drakebc561982001-05-22 17:02:02 +0000266 self.assertRaises(TypeError, time.asctime, 0)
Alexander Belopolskye2dc0822011-01-02 20:48:22 +0000267 self.assertRaises(TypeError, time.asctime, ())
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000268 self.assertRaises(TypeError, time.asctime, (0,) * 10)
Fred Drakebc561982001-05-22 17:02:02 +0000269
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000270 def test_asctime_bounding_check(self):
271 self._bounds_checking(time.asctime)
272
Georg Brandle10608c2011-01-02 22:33:43 +0000273 def test_ctime(self):
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000274 t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
275 self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
276 t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
277 self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000')
Victor Stinner1ac42612014-02-21 09:27:17 +0100278 for year in [-100, 100, 1000, 2000, 2050, 10000]:
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000279 try:
280 testval = time.mktime((year, 1, 10) + (0,)*6)
281 except (ValueError, OverflowError):
282 # If mktime fails, ctime will fail too. This may happen
283 # on some platforms.
284 pass
285 else:
286 self.assertEqual(time.ctime(testval)[20:], str(year))
Georg Brandle10608c2011-01-02 22:33:43 +0000287
Florent Xiclunae54371e2011-11-11 18:59:30 +0100288 @unittest.skipUnless(hasattr(time, "tzset"),
289 "time module has no attribute tzset")
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000290 def test_tzset(self):
Guido van Rossumd2b738e2003-03-15 12:01:52 +0000291
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000292 from os import environ
293
Tim Peters0eadaac2003-04-24 16:02:54 +0000294 # Epoch time of midnight Dec 25th 2002. Never DST in northern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000295 # hemisphere.
Tim Peters0eadaac2003-04-24 16:02:54 +0000296 xmas2002 = 1040774400.0
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000297
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000298 # These formats are correct for 2002, and possibly future years
299 # This format is the 'standard' as documented at:
300 # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
301 # They are also documented in the tzset(3) man page on most Unix
302 # systems.
Tim Peters0eadaac2003-04-24 16:02:54 +0000303 eastern = 'EST+05EDT,M4.1.0,M10.5.0'
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000304 victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
305 utc='UTC+0'
306
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000307 org_TZ = environ.get('TZ',None)
308 try:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000309 # Make sure we can switch to UTC time and results are correct
310 # Note that unknown timezones default to UTC.
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000311 # Note that altzone is undefined in UTC, as there is no DST
312 environ['TZ'] = eastern
313 time.tzset()
314 environ['TZ'] = utc
315 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000316 self.assertEqual(
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000317 time.gmtime(xmas2002), time.localtime(xmas2002)
318 )
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000319 self.assertEqual(time.daylight, 0)
320 self.assertEqual(time.timezone, 0)
321 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000322
323 # Make sure we can switch to US/Eastern
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000324 environ['TZ'] = eastern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000325 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000326 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
327 self.assertEqual(time.tzname, ('EST', 'EDT'))
328 self.assertEqual(len(time.tzname), 2)
329 self.assertEqual(time.daylight, 1)
330 self.assertEqual(time.timezone, 18000)
331 self.assertEqual(time.altzone, 14400)
332 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
333 self.assertEqual(len(time.tzname), 2)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000334
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000335 # Now go to the southern hemisphere.
336 environ['TZ'] = victoria
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000337 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000338 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
Victor Stinner0cd47902011-12-08 00:32:51 +0100339
340 # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100341 # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
342 # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
343 # on some operating systems (e.g. FreeBSD), which is wrong. See for
344 # example this bug:
345 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
Victor Stinner0cd47902011-12-08 00:32:51 +0100346 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100347 self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000348 self.assertEqual(len(time.tzname), 2)
349 self.assertEqual(time.daylight, 1)
350 self.assertEqual(time.timezone, -36000)
351 self.assertEqual(time.altzone, -39600)
352 self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000353
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000354 finally:
355 # Repair TZ environment variable in case any other tests
356 # rely on it.
357 if org_TZ is not None:
358 environ['TZ'] = org_TZ
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000359 elif 'TZ' in environ:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000360 del environ['TZ']
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000361 time.tzset()
Tim Peters0eadaac2003-04-24 16:02:54 +0000362
Tim Peters1b6f7a92004-06-20 02:50:16 +0000363 def test_insane_timestamps(self):
364 # It's possible that some platform maps time_t to double,
365 # and that this test will fail there. This test should
366 # exempt such platforms (provided they return reasonable
367 # results!).
368 for func in time.ctime, time.gmtime, time.localtime:
369 for unreasonable in -1e200, 1e200:
Victor Stinner5d272cc2012-03-13 13:35:55 +0100370 self.assertRaises(OverflowError, func, unreasonable)
Fred Drakebc561982001-05-22 17:02:02 +0000371
Fred Drakef901abd2004-08-03 17:58:55 +0000372 def test_ctime_without_arg(self):
373 # Not sure how to check the values, since the clock could tick
374 # at any time. Make sure these are at least accepted and
375 # don't raise errors.
376 time.ctime()
377 time.ctime(None)
378
379 def test_gmtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000380 gt0 = time.gmtime()
381 gt1 = time.gmtime(None)
382 t0 = time.mktime(gt0)
383 t1 = time.mktime(gt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000384 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000385
386 def test_localtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000387 lt0 = time.localtime()
388 lt1 = time.localtime(None)
389 t0 = time.mktime(lt0)
390 t1 = time.mktime(lt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000391 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000392
Florent Xiclunae54371e2011-11-11 18:59:30 +0100393 def test_mktime(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100394 # Issue #1726687
395 for t in (-2, -1, 0, 1):
Victor Stinner8c8b4e02014-02-21 23:54:32 +0100396 if sys.platform.startswith('aix') and t == -1:
397 # Issue #11188, #19748: mktime() returns -1 on error. On Linux,
398 # the tm_wday field is used as a sentinel () to detect if -1 is
399 # really an error or a valid timestamp. On AIX, tm_wday is
400 # unchanged even on success and so cannot be used as a
401 # sentinel.
402 continue
Florent Xiclunabceb5282011-11-01 14:11:34 +0100403 try:
404 tt = time.localtime(t)
Victor Stinner2cbae982012-01-27 00:50:33 +0100405 except (OverflowError, OSError):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100406 pass
407 else:
408 self.assertEqual(time.mktime(tt), t)
Florent Xiclunae54371e2011-11-11 18:59:30 +0100409
410 # Issue #13309: passing extreme values to mktime() or localtime()
411 # borks the glibc's internal timezone data.
412 @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
413 "disabled because of a bug in glibc. Issue #13309")
414 def test_mktime_error(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100415 # It may not be possible to reliably make mktime return error
416 # on all platfom. This will make sure that no other exception
417 # than OverflowError is raised for an extreme value.
Florent Xiclunae54371e2011-11-11 18:59:30 +0100418 tt = time.gmtime(self.t)
419 tzname = time.strftime('%Z', tt)
420 self.assertNotEqual(tzname, 'LMT')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100421 try:
422 time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
423 except OverflowError:
424 pass
Florent Xiclunae54371e2011-11-11 18:59:30 +0100425 self.assertEqual(time.strftime('%Z', tt), tzname)
Florent Xiclunabceb5282011-11-01 14:11:34 +0100426
Victor Stinnerec895392012-04-29 02:41:27 +0200427 @unittest.skipUnless(hasattr(time, 'monotonic'),
428 'need time.monotonic')
429 def test_monotonic(self):
Victor Stinner6c861812013-11-23 00:15:27 +0100430 # monotonic() should not go backward
431 times = [time.monotonic() for n in range(100)]
432 t1 = times[0]
433 for t2 in times[1:]:
434 self.assertGreaterEqual(t2, t1, "times=%s" % times)
435 t1 = t2
436
437 # monotonic() includes time elapsed during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200438 t1 = time.monotonic()
Victor Stinnera9c99a62013-07-03 23:07:37 +0200439 time.sleep(0.5)
Victor Stinnerec895392012-04-29 02:41:27 +0200440 t2 = time.monotonic()
Victor Stinner2dd254d2012-01-20 02:24:18 +0100441 dt = t2 - t1
Victor Stinner8b302012012-02-07 23:29:46 +0100442 self.assertGreater(t2, t1)
Zachary Ware487aedb2014-01-02 09:41:10 -0600443 # Issue #20101: On some Windows machines, dt may be slightly low
444 self.assertTrue(0.45 <= dt <= 1.0, dt)
Antoine Pitrou391166f2012-01-18 22:35:21 +0100445
Victor Stinner6c861812013-11-23 00:15:27 +0100446 # monotonic() is a monotonic but non adjustable clock
Victor Stinnerec895392012-04-29 02:41:27 +0200447 info = time.get_clock_info('monotonic')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400448 self.assertTrue(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +0200449 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200450
451 def test_perf_counter(self):
452 time.perf_counter()
453
454 def test_process_time(self):
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200455 # process_time() should not include time spend during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200456 start = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200457 time.sleep(0.100)
Victor Stinnerec895392012-04-29 02:41:27 +0200458 stop = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200459 # use 20 ms because process_time() has usually a resolution of 15 ms
460 # on Windows
461 self.assertLess(stop - start, 0.020)
Victor Stinnerec895392012-04-29 02:41:27 +0200462
463 info = time.get_clock_info('process_time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400464 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200465 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200466
Victor Stinnerec895392012-04-29 02:41:27 +0200467 @unittest.skipUnless(hasattr(time, 'monotonic'),
468 'need time.monotonic')
469 @unittest.skipUnless(hasattr(time, 'clock_settime'),
470 'need time.clock_settime')
471 def test_monotonic_settime(self):
472 t1 = time.monotonic()
473 realtime = time.clock_gettime(time.CLOCK_REALTIME)
474 # jump backward with an offset of 1 hour
Victor Stinner071eca32012-03-15 01:17:09 +0100475 try:
Victor Stinnerec895392012-04-29 02:41:27 +0200476 time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
477 except PermissionError as err:
478 self.skipTest(err)
479 t2 = time.monotonic()
480 time.clock_settime(time.CLOCK_REALTIME, realtime)
481 # monotonic must not be affected by system clock updates
Victor Stinner071eca32012-03-15 01:17:09 +0100482 self.assertGreaterEqual(t2, t1)
483
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100484 def test_localtime_failure(self):
485 # Issue #13847: check for localtime() failure
Victor Stinner53d36452012-01-27 01:03:25 +0100486 invalid_time_t = None
487 for time_t in (-1, 2**30, 2**33, 2**60):
488 try:
489 time.localtime(time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100490 except OverflowError:
491 self.skipTest("need 64-bit time_t")
Victor Stinner53d36452012-01-27 01:03:25 +0100492 except OSError:
493 invalid_time_t = time_t
494 break
495 if invalid_time_t is None:
496 self.skipTest("unable to find an invalid time_t value")
497
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100498 self.assertRaises(OSError, time.localtime, invalid_time_t)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100499 self.assertRaises(OSError, time.ctime, invalid_time_t)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100500
Han Lee829dacc2017-09-09 08:05:05 +0900501 # Issue #26669: check for localtime() failure
502 self.assertRaises(ValueError, time.localtime, float("nan"))
503 self.assertRaises(ValueError, time.ctime, float("nan"))
504
Victor Stinnerec895392012-04-29 02:41:27 +0200505 def test_get_clock_info(self):
506 clocks = ['clock', 'perf_counter', 'process_time', 'time']
507 if hasattr(time, 'monotonic'):
508 clocks.append('monotonic')
509
510 for name in clocks:
511 info = time.get_clock_info(name)
512 #self.assertIsInstance(info, dict)
513 self.assertIsInstance(info.implementation, str)
514 self.assertNotEqual(info.implementation, '')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400515 self.assertIsInstance(info.monotonic, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200516 self.assertIsInstance(info.resolution, float)
517 # 0.0 < resolution <= 1.0
518 self.assertGreater(info.resolution, 0.0)
519 self.assertLessEqual(info.resolution, 1.0)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200520 self.assertIsInstance(info.adjustable, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200521
522 self.assertRaises(ValueError, time.get_clock_info, 'xxx')
523
524
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000525class TestLocale(unittest.TestCase):
526 def setUp(self):
527 self.oldloc = locale.setlocale(locale.LC_ALL)
Fred Drake2e2be372001-09-20 21:33:42 +0000528
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000529 def tearDown(self):
530 locale.setlocale(locale.LC_ALL, self.oldloc)
531
Martin v. Löwisa6a9c4d2009-05-30 06:15:30 +0000532 def test_bug_3061(self):
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000533 try:
534 tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
535 except locale.Error:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600536 self.skipTest('could not set locale.LC_ALL to fr_FR')
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000537 # This should not cause an exception
538 time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
539
Victor Stinner73ea29c2011-01-08 01:56:31 +0000540
Victor Stinner73ea29c2011-01-08 01:56:31 +0000541class _TestAsctimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100542 _format = '%d'
543
Victor Stinner73ea29c2011-01-08 01:56:31 +0000544 def yearstr(self, y):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000545 return time.asctime((y,) + (0,) * 8).split()[-1]
Alexander Belopolskya6867252011-01-05 23:00:47 +0000546
Victor Stinner73ea29c2011-01-08 01:56:31 +0000547 def test_large_year(self):
Victor Stinner73691322011-01-08 02:00:24 +0000548 # Check that it doesn't crash for year > 9999
Victor Stinner73ea29c2011-01-08 01:56:31 +0000549 self.assertEqual(self.yearstr(12345), '12345')
550 self.assertEqual(self.yearstr(123456789), '123456789')
551
552class _TestStrftimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100553
554 # Issue 13305: For years < 1000, the value is not always
555 # padded to 4 digits across platforms. The C standard
556 # assumes year >= 1900, so it does not specify the number
557 # of digits.
558
559 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
560 _format = '%04d'
561 else:
562 _format = '%d'
563
Victor Stinner73ea29c2011-01-08 01:56:31 +0000564 def yearstr(self, y):
Florent Xicluna49ce0682011-11-01 12:56:14 +0100565 return time.strftime('%Y', (y,) + (0,) * 8)
566
567 def test_4dyear(self):
568 # Check that we can return the zero padded value.
569 if self._format == '%04d':
570 self.test_year('%04d')
571 else:
572 def year4d(y):
573 return time.strftime('%4Y', (y,) + (0,) * 8)
574 self.test_year('%04d', func=year4d)
575
Florent Xiclunabceb5282011-11-01 14:11:34 +0100576 def skip_if_not_supported(y):
577 msg = "strftime() is limited to [1; 9999] with Visual Studio"
578 # Check that it doesn't crash for year > 9999
579 try:
580 time.strftime('%Y', (y,) + (0,) * 8)
581 except ValueError:
582 cond = False
583 else:
584 cond = True
585 return unittest.skipUnless(cond, msg)
586
587 @skip_if_not_supported(10000)
588 def test_large_year(self):
589 return super().test_large_year()
590
591 @skip_if_not_supported(0)
592 def test_negative(self):
593 return super().test_negative()
594
595 del skip_if_not_supported
596
597
Ezio Melotti3836d702013-04-11 20:29:42 +0300598class _Test4dYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100599 _format = '%d'
600
601 def test_year(self, fmt=None, func=None):
602 fmt = fmt or self._format
603 func = func or self.yearstr
604 self.assertEqual(func(1), fmt % 1)
605 self.assertEqual(func(68), fmt % 68)
606 self.assertEqual(func(69), fmt % 69)
607 self.assertEqual(func(99), fmt % 99)
608 self.assertEqual(func(999), fmt % 999)
609 self.assertEqual(func(9999), fmt % 9999)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000610
611 def test_large_year(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100612 self.assertEqual(self.yearstr(12345), '12345')
Victor Stinner13ed2ea2011-03-21 02:11:01 +0100613 self.assertEqual(self.yearstr(123456789), '123456789')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100614 self.assertEqual(self.yearstr(TIME_MAXYEAR), str(TIME_MAXYEAR))
615 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000616
Victor Stinner301f1212011-01-08 03:06:52 +0000617 def test_negative(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100618 self.assertEqual(self.yearstr(-1), self._format % -1)
Victor Stinner301f1212011-01-08 03:06:52 +0000619 self.assertEqual(self.yearstr(-1234), '-1234')
620 self.assertEqual(self.yearstr(-123456), '-123456')
Florent Xiclunad1bd7f72011-11-01 23:42:05 +0100621 self.assertEqual(self.yearstr(-123456789), str(-123456789))
622 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
Florent Xicluna2fbc1852011-11-02 08:13:43 +0100623 self.assertEqual(self.yearstr(TIME_MINYEAR + 1900), str(TIME_MINYEAR + 1900))
624 # Issue #13312: it may return wrong value for year < TIME_MINYEAR + 1900
625 # Skip the value test, but check that no error is raised
626 self.yearstr(TIME_MINYEAR)
Florent Xiclunae2a732e2011-11-02 01:28:17 +0100627 # self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
Florent Xiclunabceb5282011-11-01 14:11:34 +0100628 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
Victor Stinner301f1212011-01-08 03:06:52 +0000629
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000630
Ezio Melotti3836d702013-04-11 20:29:42 +0300631class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner73ea29c2011-01-08 01:56:31 +0000632 pass
633
Ezio Melotti3836d702013-04-11 20:29:42 +0300634class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner301f1212011-01-08 03:06:52 +0000635 pass
Victor Stinner73ea29c2011-01-08 01:56:31 +0000636
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000637
Victor Stinner643cd682012-03-02 22:54:03 +0100638class TestPytime(unittest.TestCase):
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400639 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
640 def test_localtime_timezone(self):
Victor Stinner643cd682012-03-02 22:54:03 +0100641
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400642 # Get the localtime and examine it for the offset and zone.
643 lt = time.localtime()
644 self.assertTrue(hasattr(lt, "tm_gmtoff"))
645 self.assertTrue(hasattr(lt, "tm_zone"))
646
647 # See if the offset and zone are similar to the module
648 # attributes.
649 if lt.tm_gmtoff is None:
650 self.assertTrue(not hasattr(time, "timezone"))
651 else:
652 self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
653 if lt.tm_zone is None:
654 self.assertTrue(not hasattr(time, "tzname"))
655 else:
656 self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
657
658 # Try and make UNIX times from the localtime and a 9-tuple
659 # created from the localtime. Test to see that the times are
660 # the same.
661 t = time.mktime(lt); t9 = time.mktime(lt[:9])
662 self.assertEqual(t, t9)
663
664 # Make localtimes from the UNIX times and compare them to
665 # the original localtime, thus making a round trip.
666 new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
667 self.assertEqual(new_lt, lt)
668 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
669 self.assertEqual(new_lt.tm_zone, lt.tm_zone)
670 self.assertEqual(new_lt9, lt)
671 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
672 self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
673
674 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
675 def test_strptime_timezone(self):
676 t = time.strptime("UTC", "%Z")
677 self.assertEqual(t.tm_zone, 'UTC')
678 t = time.strptime("+0500", "%z")
679 self.assertEqual(t.tm_gmtoff, 5 * 3600)
680
681 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
682 def test_short_times(self):
683
684 import pickle
685
686 # Load a short time structure using pickle.
687 st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
688 lt = pickle.loads(st)
689 self.assertIs(lt.tm_gmtoff, None)
690 self.assertIs(lt.tm_zone, None)
Victor Stinner643cd682012-03-02 22:54:03 +0100691
Fred Drake2e2be372001-09-20 21:33:42 +0000692
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200693@unittest.skipIf(_testcapi is None, 'need the _testcapi module')
694class CPyTimeTestCase:
Victor Stinneracea9f62015-09-02 10:39:40 +0200695 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200696 Base class to test the C _PyTime_t API.
Victor Stinneracea9f62015-09-02 10:39:40 +0200697 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200698 OVERFLOW_SECONDS = None
699
Victor Stinner4237d342015-09-10 10:10:39 +0200700 def setUp(self):
701 from _testcapi import SIZEOF_TIME_T
702 bits = SIZEOF_TIME_T * 8 - 1
703 self.time_t_min = -2 ** bits
704 self.time_t_max = 2 ** bits - 1
705
706 def time_t_filter(self, seconds):
707 return (self.time_t_min <= seconds <= self.time_t_max)
708
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200709 def _rounding_values(self, use_float):
710 "Build timestamps used to test rounding."
711
712 units = [1, US_TO_NS, MS_TO_NS, SEC_TO_NS]
713 if use_float:
714 # picoseconds are only tested to pytime_converter accepting floats
715 units.append(1e-3)
716
717 values = (
718 # small values
719 1, 2, 5, 7, 123, 456, 1234,
720 # 10^k - 1
721 9,
722 99,
723 999,
724 9999,
725 99999,
726 999999,
727 # test half even rounding near 0.5, 1.5, 2.5, 3.5, 4.5
728 499, 500, 501,
729 1499, 1500, 1501,
730 2500,
731 3500,
732 4500,
733 )
734
735 ns_timestamps = [0]
736 for unit in units:
737 for value in values:
738 ns = value * unit
739 ns_timestamps.extend((-ns, ns))
740 for pow2 in (0, 5, 10, 15, 22, 23, 24, 30, 33):
741 ns = (2 ** pow2) * SEC_TO_NS
742 ns_timestamps.extend((
743 -ns-1, -ns, -ns+1,
744 ns-1, ns, ns+1
745 ))
746 for seconds in (_testcapi.INT_MIN, _testcapi.INT_MAX):
747 ns_timestamps.append(seconds * SEC_TO_NS)
748 if use_float:
Victor Stinner717a32b2016-08-17 11:07:21 +0200749 # numbers with an exact representation in IEEE 754 (base 2)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200750 for pow2 in (3, 7, 10, 15):
751 ns = 2.0 ** (-pow2)
752 ns_timestamps.extend((-ns, ns))
753
754 # seconds close to _PyTime_t type limit
755 ns = (2 ** 63 // SEC_TO_NS) * SEC_TO_NS
756 ns_timestamps.extend((-ns, ns))
757
758 return ns_timestamps
759
760 def _check_rounding(self, pytime_converter, expected_func,
761 use_float, unit_to_sec, value_filter=None):
762
763 def convert_values(ns_timestamps):
764 if use_float:
765 unit_to_ns = SEC_TO_NS / float(unit_to_sec)
766 values = [ns / unit_to_ns for ns in ns_timestamps]
767 else:
768 unit_to_ns = SEC_TO_NS // unit_to_sec
769 values = [ns // unit_to_ns for ns in ns_timestamps]
770
771 if value_filter:
772 values = filter(value_filter, values)
773
774 # remove duplicates and sort
775 return sorted(set(values))
776
777 # test rounding
778 ns_timestamps = self._rounding_values(use_float)
779 valid_values = convert_values(ns_timestamps)
780 for time_rnd, decimal_rnd in ROUNDING_MODES :
781 context = decimal.getcontext()
782 context.rounding = decimal_rnd
783
784 for value in valid_values:
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200785 debug_info = {'value': value, 'rounding': decimal_rnd}
786 try:
787 result = pytime_converter(value, time_rnd)
788 expected = expected_func(value)
789 except Exception as exc:
790 self.fail("Error on timestamp conversion: %s" % debug_info)
791 self.assertEqual(result,
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200792 expected,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200793 debug_info)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200794
795 # test overflow
796 ns = self.OVERFLOW_SECONDS * SEC_TO_NS
797 ns_timestamps = (-ns, ns)
798 overflow_values = convert_values(ns_timestamps)
799 for time_rnd, _ in ROUNDING_MODES :
800 for value in overflow_values:
Victor Stinnerc60542b2015-09-10 15:55:07 +0200801 debug_info = {'value': value, 'rounding': time_rnd}
802 with self.assertRaises(OverflowError, msg=debug_info):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200803 pytime_converter(value, time_rnd)
804
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200805 def check_int_rounding(self, pytime_converter, expected_func,
806 unit_to_sec=1, value_filter=None):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200807 self._check_rounding(pytime_converter, expected_func,
808 False, unit_to_sec, value_filter)
809
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200810 def check_float_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,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200813 True, unit_to_sec, value_filter)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200814
815 def decimal_round(self, x):
816 d = decimal.Decimal(x)
817 d = d.quantize(1)
818 return int(d)
819
820
821class TestCPyTime(CPyTimeTestCase, unittest.TestCase):
822 """
823 Test the C _PyTime_t API.
824 """
825 # _PyTime_t is a 64-bit signed integer
826 OVERFLOW_SECONDS = math.ceil((2**63 + 1) / SEC_TO_NS)
827
Victor Stinner13019fd2015-04-03 13:10:54 +0200828 def test_FromSeconds(self):
829 from _testcapi import PyTime_FromSeconds
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200830
831 # PyTime_FromSeconds() expects a C int, reject values out of range
832 def c_int_filter(secs):
833 return (_testcapi.INT_MIN <= secs <= _testcapi.INT_MAX)
834
835 self.check_int_rounding(lambda secs, rnd: PyTime_FromSeconds(secs),
836 lambda secs: secs * SEC_TO_NS,
837 value_filter=c_int_filter)
Victor Stinner13019fd2015-04-03 13:10:54 +0200838
Han Lee829dacc2017-09-09 08:05:05 +0900839 # test nan
840 for time_rnd, _ in ROUNDING_MODES:
841 with self.assertRaises(TypeError):
842 PyTime_FromSeconds(float('nan'))
843
Victor Stinner992c43f2015-03-27 17:12:45 +0100844 def test_FromSecondsObject(self):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100845 from _testcapi import PyTime_FromSecondsObject
Victor Stinner992c43f2015-03-27 17:12:45 +0100846
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200847 self.check_int_rounding(
848 PyTime_FromSecondsObject,
849 lambda secs: secs * SEC_TO_NS)
Victor Stinner992c43f2015-03-27 17:12:45 +0100850
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200851 self.check_float_rounding(
852 PyTime_FromSecondsObject,
853 lambda ns: self.decimal_round(ns * SEC_TO_NS))
Victor Stinner4bfb4602015-03-27 22:27:24 +0100854
Han Lee829dacc2017-09-09 08:05:05 +0900855 # test nan
856 for time_rnd, _ in ROUNDING_MODES:
857 with self.assertRaises(ValueError):
858 PyTime_FromSecondsObject(float('nan'), time_rnd)
859
Victor Stinner4bfb4602015-03-27 22:27:24 +0100860 def test_AsSecondsDouble(self):
861 from _testcapi import PyTime_AsSecondsDouble
862
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200863 def float_converter(ns):
864 if abs(ns) % SEC_TO_NS == 0:
865 return float(ns // SEC_TO_NS)
866 else:
867 return float(ns) / SEC_TO_NS
Victor Stinner4bfb4602015-03-27 22:27:24 +0100868
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200869 self.check_int_rounding(lambda ns, rnd: PyTime_AsSecondsDouble(ns),
870 float_converter,
871 NS_TO_SEC)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100872
Han Lee829dacc2017-09-09 08:05:05 +0900873 # test nan
874 for time_rnd, _ in ROUNDING_MODES:
875 with self.assertRaises(TypeError):
876 PyTime_AsSecondsDouble(float('nan'))
877
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200878 def create_decimal_converter(self, denominator):
879 denom = decimal.Decimal(denominator)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100880
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200881 def converter(value):
882 d = decimal.Decimal(value) / denom
883 return self.decimal_round(d)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100884
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200885 return converter
Victor Stinner4bfb4602015-03-27 22:27:24 +0100886
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200887 def test_AsTimeval(self):
Victor Stinner95e9cef2015-03-28 01:26:47 +0100888 from _testcapi import PyTime_AsTimeval
Victor Stinner95e9cef2015-03-28 01:26:47 +0100889
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200890 us_converter = self.create_decimal_converter(US_TO_NS)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100891
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200892 def timeval_converter(ns):
893 us = us_converter(ns)
894 return divmod(us, SEC_TO_US)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100895
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200896 if sys.platform == 'win32':
897 from _testcapi import LONG_MIN, LONG_MAX
898
899 # On Windows, timeval.tv_sec type is a C long
900 def seconds_filter(secs):
901 return LONG_MIN <= secs <= LONG_MAX
902 else:
Victor Stinner4237d342015-09-10 10:10:39 +0200903 seconds_filter = self.time_t_filter
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200904
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200905 self.check_int_rounding(PyTime_AsTimeval,
906 timeval_converter,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200907 NS_TO_SEC,
908 value_filter=seconds_filter)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100909
Victor Stinner34dc0f42015-03-27 18:19:03 +0100910 @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec'),
911 'need _testcapi.PyTime_AsTimespec')
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200912 def test_AsTimespec(self):
Victor Stinner34dc0f42015-03-27 18:19:03 +0100913 from _testcapi import PyTime_AsTimespec
Victor Stinner34dc0f42015-03-27 18:19:03 +0100914
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200915 def timespec_converter(ns):
916 return divmod(ns, SEC_TO_NS)
Victor Stinner34dc0f42015-03-27 18:19:03 +0100917
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200918 self.check_int_rounding(lambda ns, rnd: PyTime_AsTimespec(ns),
919 timespec_converter,
Victor Stinner4237d342015-09-10 10:10:39 +0200920 NS_TO_SEC,
921 value_filter=self.time_t_filter)
Victor Stinner34dc0f42015-03-27 18:19:03 +0100922
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200923 def test_AsMilliseconds(self):
Victor Stinner62d1c702015-04-01 17:47:07 +0200924 from _testcapi import PyTime_AsMilliseconds
Victor Stinner62d1c702015-04-01 17:47:07 +0200925
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200926 self.check_int_rounding(PyTime_AsMilliseconds,
927 self.create_decimal_converter(MS_TO_NS),
928 NS_TO_SEC)
Victor Stinner62d1c702015-04-01 17:47:07 +0200929
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200930 def test_AsMicroseconds(self):
Victor Stinner62d1c702015-04-01 17:47:07 +0200931 from _testcapi import PyTime_AsMicroseconds
Victor Stinner62d1c702015-04-01 17:47:07 +0200932
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200933 self.check_int_rounding(PyTime_AsMicroseconds,
934 self.create_decimal_converter(US_TO_NS),
935 NS_TO_SEC)
Victor Stinner62d1c702015-04-01 17:47:07 +0200936
Victor Stinner992c43f2015-03-27 17:12:45 +0100937
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200938class TestOldPyTime(CPyTimeTestCase, unittest.TestCase):
Victor Stinneracea9f62015-09-02 10:39:40 +0200939 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200940 Test the old C _PyTime_t API: _PyTime_ObjectToXXX() functions.
Victor Stinneracea9f62015-09-02 10:39:40 +0200941 """
Victor Stinneracea9f62015-09-02 10:39:40 +0200942
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200943 # time_t is a 32-bit or 64-bit signed integer
944 OVERFLOW_SECONDS = 2 ** 64
945
946 def test_object_to_time_t(self):
Victor Stinneracea9f62015-09-02 10:39:40 +0200947 from _testcapi import pytime_object_to_time_t
948
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200949 self.check_int_rounding(pytime_object_to_time_t,
Victor Stinner4237d342015-09-10 10:10:39 +0200950 lambda secs: secs,
951 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200952
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200953 self.check_float_rounding(pytime_object_to_time_t,
Victor Stinner350b5182015-09-10 11:45:06 +0200954 self.decimal_round,
955 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200956
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200957 def create_converter(self, sec_to_unit):
958 def converter(secs):
959 floatpart, intpart = math.modf(secs)
960 intpart = int(intpart)
961 floatpart *= sec_to_unit
962 floatpart = self.decimal_round(floatpart)
963 if floatpart < 0:
964 floatpart += sec_to_unit
965 intpart -= 1
966 elif floatpart >= sec_to_unit:
967 floatpart -= sec_to_unit
968 intpart += 1
969 return (intpart, floatpart)
970 return converter
Victor Stinneracea9f62015-09-02 10:39:40 +0200971
Victor Stinneradfefa52015-09-04 23:57:25 +0200972 def test_object_to_timeval(self):
Victor Stinneracea9f62015-09-02 10:39:40 +0200973 from _testcapi import pytime_object_to_timeval
974
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200975 self.check_int_rounding(pytime_object_to_timeval,
Victor Stinner4237d342015-09-10 10:10:39 +0200976 lambda secs: (secs, 0),
977 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200978
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200979 self.check_float_rounding(pytime_object_to_timeval,
Victor Stinner350b5182015-09-10 11:45:06 +0200980 self.create_converter(SEC_TO_US),
981 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200982
Han Lee829dacc2017-09-09 08:05:05 +0900983 # test nan
984 for time_rnd, _ in ROUNDING_MODES:
985 with self.assertRaises(ValueError):
986 pytime_object_to_timeval(float('nan'), time_rnd)
987
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200988 def test_object_to_timespec(self):
Victor Stinneracea9f62015-09-02 10:39:40 +0200989 from _testcapi import pytime_object_to_timespec
990
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200991 self.check_int_rounding(pytime_object_to_timespec,
Victor Stinner4237d342015-09-10 10:10:39 +0200992 lambda secs: (secs, 0),
993 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200994
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200995 self.check_float_rounding(pytime_object_to_timespec,
Victor Stinner350b5182015-09-10 11:45:06 +0200996 self.create_converter(SEC_TO_NS),
997 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200998
Han Lee829dacc2017-09-09 08:05:05 +0900999 # test nan
1000 for time_rnd, _ in ROUNDING_MODES:
1001 with self.assertRaises(ValueError):
1002 pytime_object_to_timespec(float('nan'), time_rnd)
1003
Victor Stinneracea9f62015-09-02 10:39:40 +02001004
Fred Drake2e2be372001-09-20 21:33:42 +00001005if __name__ == "__main__":
Ezio Melotti3836d702013-04-11 20:29:42 +03001006 unittest.main()