blob: 61dda09c184d3fa9f7ea924dfdd61ed56cd1ba53 [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
Pablo Galindo2c15b292017-10-17 15:14:41 +010036 # Round away from zero
37 ROUND_UP = 3
Victor Stinner992c43f2015-03-27 17:12:45 +010038
Victor Stinner3e2c8d82015-09-09 22:32:48 +020039# Rounding modes supported by PyTime
40ROUNDING_MODES = (
41 # (PyTime rounding method, decimal rounding method)
42 (_PyTime.ROUND_FLOOR, decimal.ROUND_FLOOR),
43 (_PyTime.ROUND_CEILING, decimal.ROUND_CEILING),
44 (_PyTime.ROUND_HALF_EVEN, decimal.ROUND_HALF_EVEN),
Pablo Galindo2c15b292017-10-17 15:14:41 +010045 (_PyTime.ROUND_UP, decimal.ROUND_UP),
Victor Stinner3e2c8d82015-09-09 22:32:48 +020046)
Florent Xiclunabceb5282011-11-01 14:11:34 +010047
48
Fred Drakebc561982001-05-22 17:02:02 +000049class TimeTestCase(unittest.TestCase):
Barry Warsawb0c22321996-12-06 23:30:07 +000050
Fred Drakebc561982001-05-22 17:02:02 +000051 def setUp(self):
52 self.t = time.time()
Barry Warsawb0c22321996-12-06 23:30:07 +000053
Fred Drakebc561982001-05-22 17:02:02 +000054 def test_data_attributes(self):
55 time.altzone
56 time.daylight
57 time.timezone
58 time.tzname
Barry Warsawb0c22321996-12-06 23:30:07 +000059
Victor Stinnerec895392012-04-29 02:41:27 +020060 def test_time(self):
61 time.time()
62 info = time.get_clock_info('time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040063 self.assertFalse(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +020064 self.assertTrue(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020065
Fred Drakebc561982001-05-22 17:02:02 +000066 def test_clock(self):
67 time.clock()
Barry Warsawb0c22321996-12-06 23:30:07 +000068
Victor Stinnerec895392012-04-29 02:41:27 +020069 info = time.get_clock_info('clock')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040070 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +020071 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020072
Victor Stinnere0be4232011-10-25 13:06:09 +020073 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
74 'need time.clock_gettime()')
75 def test_clock_realtime(self):
76 time.clock_gettime(time.CLOCK_REALTIME)
77
78 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
79 'need time.clock_gettime()')
80 @unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'),
81 'need time.CLOCK_MONOTONIC')
82 def test_clock_monotonic(self):
83 a = time.clock_gettime(time.CLOCK_MONOTONIC)
84 b = time.clock_gettime(time.CLOCK_MONOTONIC)
85 self.assertLessEqual(a, b)
86
pdoxe14679c2017-10-05 00:01:56 -070087 @unittest.skipUnless(hasattr(time, 'pthread_getcpuclockid'),
88 'need time.pthread_getcpuclockid()')
89 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
90 'need time.clock_gettime()')
pdoxe14679c2017-10-05 00:01:56 -070091 def test_pthread_getcpuclockid(self):
92 clk_id = time.pthread_getcpuclockid(threading.get_ident())
93 self.assertTrue(type(clk_id) is int)
94 self.assertNotEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
pdoxe14679c2017-10-05 00:01:56 -070095 t1 = time.clock_gettime(clk_id)
Benjamin Peterson86566702017-10-05 22:50:42 -070096 t2 = time.clock_gettime(clk_id)
pdoxe14679c2017-10-05 00:01:56 -070097 self.assertLessEqual(t1, t2)
pdoxe14679c2017-10-05 00:01:56 -070098
Victor Stinnere0be4232011-10-25 13:06:09 +020099 @unittest.skipUnless(hasattr(time, 'clock_getres'),
100 'need time.clock_getres()')
101 def test_clock_getres(self):
102 res = time.clock_getres(time.CLOCK_REALTIME)
103 self.assertGreater(res, 0.0)
104 self.assertLessEqual(res, 1.0)
105
Victor Stinner30d79472012-04-03 00:45:07 +0200106 @unittest.skipUnless(hasattr(time, 'clock_settime'),
107 'need time.clock_settime()')
108 def test_clock_settime(self):
109 t = time.clock_gettime(time.CLOCK_REALTIME)
110 try:
111 time.clock_settime(time.CLOCK_REALTIME, t)
112 except PermissionError:
113 pass
114
Victor Stinnerec895392012-04-29 02:41:27 +0200115 if hasattr(time, 'CLOCK_MONOTONIC'):
116 self.assertRaises(OSError,
117 time.clock_settime, time.CLOCK_MONOTONIC, 0)
Victor Stinner30d79472012-04-03 00:45:07 +0200118
Fred Drakebc561982001-05-22 17:02:02 +0000119 def test_conversions(self):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000120 self.assertEqual(time.ctime(self.t),
121 time.asctime(time.localtime(self.t)))
122 self.assertEqual(int(time.mktime(time.localtime(self.t))),
123 int(self.t))
Fred Drakebc561982001-05-22 17:02:02 +0000124
125 def test_sleep(self):
Victor Stinner7f53a502011-07-05 22:00:25 +0200126 self.assertRaises(ValueError, time.sleep, -2)
127 self.assertRaises(ValueError, time.sleep, -1)
Fred Drakebc561982001-05-22 17:02:02 +0000128 time.sleep(1.2)
129
130 def test_strftime(self):
131 tt = time.gmtime(self.t)
132 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
133 'j', 'm', 'M', 'p', 'S',
134 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
135 format = ' %' + directive
136 try:
137 time.strftime(format, tt)
138 except ValueError:
139 self.fail('conversion specifier: %r failed.' % format)
140
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +0300141 self.assertRaises(TypeError, time.strftime, b'%S', tt)
142 # embedded null character
143 self.assertRaises(ValueError, time.strftime, '%S\0', tt)
144
Florent Xicluna49ce0682011-11-01 12:56:14 +0100145 def _bounds_checking(self, func):
Brett Cannond1080a32004-03-02 04:38:10 +0000146 # Make sure that strftime() checks the bounds of the various parts
Florent Xicluna49ce0682011-11-01 12:56:14 +0100147 # of the time tuple (0 is valid for *all* values).
Brett Cannond1080a32004-03-02 04:38:10 +0000148
Victor Stinner73ea29c2011-01-08 01:56:31 +0000149 # The year field is tested by other test cases above
150
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000151 # Check month [1, 12] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100152 func((1900, 0, 1, 0, 0, 0, 0, 1, -1))
153 func((1900, 12, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000154 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000155 (1900, -1, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000156 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000157 (1900, 13, 1, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000158 # Check day of month [1, 31] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100159 func((1900, 1, 0, 0, 0, 0, 0, 1, -1))
160 func((1900, 1, 31, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000161 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000162 (1900, 1, -1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000163 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000164 (1900, 1, 32, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000165 # Check hour [0, 23]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100166 func((1900, 1, 1, 23, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000167 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000168 (1900, 1, 1, -1, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000169 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000170 (1900, 1, 1, 24, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000171 # Check minute [0, 59]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100172 func((1900, 1, 1, 0, 59, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000173 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000174 (1900, 1, 1, 0, -1, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000175 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000176 (1900, 1, 1, 0, 60, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000177 # Check second [0, 61]
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000178 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000179 (1900, 1, 1, 0, 0, -1, 0, 1, -1))
180 # C99 only requires allowing for one leap second, but Python's docs say
181 # allow two leap seconds (0..61)
Florent Xicluna49ce0682011-11-01 12:56:14 +0100182 func((1900, 1, 1, 0, 0, 60, 0, 1, -1))
183 func((1900, 1, 1, 0, 0, 61, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000184 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000185 (1900, 1, 1, 0, 0, 62, 0, 1, -1))
186 # No check for upper-bound day of week;
187 # value forced into range by a ``% 7`` calculation.
188 # Start check at -2 since gettmarg() increments value before taking
189 # modulo.
Florent Xicluna49ce0682011-11-01 12:56:14 +0100190 self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)),
191 func((1900, 1, 1, 0, 0, 0, +6, 1, -1)))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000192 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000193 (1900, 1, 1, 0, 0, 0, -2, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000194 # Check day of the year [1, 366] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100195 func((1900, 1, 1, 0, 0, 0, 0, 0, -1))
196 func((1900, 1, 1, 0, 0, 0, 0, 366, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000197 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000198 (1900, 1, 1, 0, 0, 0, 0, -1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000199 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000200 (1900, 1, 1, 0, 0, 0, 0, 367, -1))
Brett Cannond1080a32004-03-02 04:38:10 +0000201
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000202 def test_strftime_bounding_check(self):
203 self._bounds_checking(lambda tup: time.strftime('', tup))
204
Steve Dowere5b58952015-09-06 19:20:51 -0700205 def test_strftime_format_check(self):
206 # Test that strftime does not crash on invalid format strings
207 # that may trigger a buffer overread. When not triggered,
208 # strftime may succeed or raise ValueError depending on
209 # the platform.
210 for x in [ '', 'A', '%A', '%AA' ]:
211 for y in range(0x0, 0x10):
212 for z in [ '%', 'A%', 'AA%', '%A%', 'A%A%', '%#' ]:
213 try:
214 time.strftime(x * y + z)
215 except ValueError:
216 pass
217
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000218 def test_default_values_for_zero(self):
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400219 # Make sure that using all zeros uses the proper default
220 # values. No test for daylight savings since strftime() does
221 # not change output based on its value and no test for year
222 # because systems vary in their support for year 0.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000223 expected = "2000 01 01 00 00 00 1 001"
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000224 with support.check_warnings():
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400225 result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000226 self.assertEqual(expected, result)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000227
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000228 def test_strptime(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000229 # Should be able to go round-trip from strftime to strptime without
Andrew Svetlov737fb892012-12-18 21:14:22 +0200230 # raising an exception.
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000231 tt = time.gmtime(self.t)
232 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
233 'j', 'm', 'M', 'p', 'S',
234 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000235 format = '%' + directive
236 strf_output = time.strftime(format, tt)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000237 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000238 time.strptime(strf_output, format)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000239 except ValueError:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000240 self.fail("conversion specifier %r failed with '%s' input." %
241 (format, strf_output))
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000242
Brett Cannon7f6b4f82009-03-30 21:30:26 +0000243 def test_strptime_bytes(self):
244 # Make sure only strings are accepted as arguments to strptime.
245 self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
246 self.assertRaises(TypeError, time.strptime, '2009', b'%Y')
247
Ezio Melotti0f389082013-04-04 02:09:20 +0300248 def test_strptime_exception_context(self):
249 # check that this doesn't chain exceptions needlessly (see #17572)
250 with self.assertRaises(ValueError) as e:
251 time.strptime('', '%D')
252 self.assertIs(e.exception.__suppress_context__, True)
Serhiy Storchakacdac3022013-11-24 18:15:37 +0200253 # additional check for IndexError branch (issue #19545)
254 with self.assertRaises(ValueError) as e:
255 time.strptime('19', '%Y %')
256 self.assertIs(e.exception.__suppress_context__, True)
Ezio Melotti0f389082013-04-04 02:09:20 +0300257
Fred Drakebc561982001-05-22 17:02:02 +0000258 def test_asctime(self):
259 time.asctime(time.gmtime(self.t))
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000260
261 # Max year is only limited by the size of C int.
Florent Xiclunabceb5282011-11-01 14:11:34 +0100262 for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
263 asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
264 self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
265 self.assertRaises(OverflowError, time.asctime,
266 (TIME_MAXYEAR + 1,) + (0,) * 8)
267 self.assertRaises(OverflowError, time.asctime,
268 (TIME_MINYEAR - 1,) + (0,) * 8)
Fred Drakebc561982001-05-22 17:02:02 +0000269 self.assertRaises(TypeError, time.asctime, 0)
Alexander Belopolskye2dc0822011-01-02 20:48:22 +0000270 self.assertRaises(TypeError, time.asctime, ())
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000271 self.assertRaises(TypeError, time.asctime, (0,) * 10)
Fred Drakebc561982001-05-22 17:02:02 +0000272
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000273 def test_asctime_bounding_check(self):
274 self._bounds_checking(time.asctime)
275
Georg Brandle10608c2011-01-02 22:33:43 +0000276 def test_ctime(self):
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000277 t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
278 self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
279 t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
280 self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000')
Victor Stinner1ac42612014-02-21 09:27:17 +0100281 for year in [-100, 100, 1000, 2000, 2050, 10000]:
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000282 try:
283 testval = time.mktime((year, 1, 10) + (0,)*6)
284 except (ValueError, OverflowError):
285 # If mktime fails, ctime will fail too. This may happen
286 # on some platforms.
287 pass
288 else:
289 self.assertEqual(time.ctime(testval)[20:], str(year))
Georg Brandle10608c2011-01-02 22:33:43 +0000290
Florent Xiclunae54371e2011-11-11 18:59:30 +0100291 @unittest.skipUnless(hasattr(time, "tzset"),
292 "time module has no attribute tzset")
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000293 def test_tzset(self):
Guido van Rossumd2b738e2003-03-15 12:01:52 +0000294
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000295 from os import environ
296
Tim Peters0eadaac2003-04-24 16:02:54 +0000297 # Epoch time of midnight Dec 25th 2002. Never DST in northern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000298 # hemisphere.
Tim Peters0eadaac2003-04-24 16:02:54 +0000299 xmas2002 = 1040774400.0
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000300
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000301 # These formats are correct for 2002, and possibly future years
302 # This format is the 'standard' as documented at:
303 # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
304 # They are also documented in the tzset(3) man page on most Unix
305 # systems.
Tim Peters0eadaac2003-04-24 16:02:54 +0000306 eastern = 'EST+05EDT,M4.1.0,M10.5.0'
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000307 victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
308 utc='UTC+0'
309
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000310 org_TZ = environ.get('TZ',None)
311 try:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000312 # Make sure we can switch to UTC time and results are correct
313 # Note that unknown timezones default to UTC.
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000314 # Note that altzone is undefined in UTC, as there is no DST
315 environ['TZ'] = eastern
316 time.tzset()
317 environ['TZ'] = utc
318 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000319 self.assertEqual(
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000320 time.gmtime(xmas2002), time.localtime(xmas2002)
321 )
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000322 self.assertEqual(time.daylight, 0)
323 self.assertEqual(time.timezone, 0)
324 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000325
326 # Make sure we can switch to US/Eastern
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000327 environ['TZ'] = eastern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000328 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000329 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
330 self.assertEqual(time.tzname, ('EST', 'EDT'))
331 self.assertEqual(len(time.tzname), 2)
332 self.assertEqual(time.daylight, 1)
333 self.assertEqual(time.timezone, 18000)
334 self.assertEqual(time.altzone, 14400)
335 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
336 self.assertEqual(len(time.tzname), 2)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000337
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000338 # Now go to the southern hemisphere.
339 environ['TZ'] = victoria
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000340 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000341 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
Victor Stinner0cd47902011-12-08 00:32:51 +0100342
343 # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100344 # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
345 # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
346 # on some operating systems (e.g. FreeBSD), which is wrong. See for
347 # example this bug:
348 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
Victor Stinner0cd47902011-12-08 00:32:51 +0100349 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100350 self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000351 self.assertEqual(len(time.tzname), 2)
352 self.assertEqual(time.daylight, 1)
353 self.assertEqual(time.timezone, -36000)
354 self.assertEqual(time.altzone, -39600)
355 self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000356
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000357 finally:
358 # Repair TZ environment variable in case any other tests
359 # rely on it.
360 if org_TZ is not None:
361 environ['TZ'] = org_TZ
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000362 elif 'TZ' in environ:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000363 del environ['TZ']
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000364 time.tzset()
Tim Peters0eadaac2003-04-24 16:02:54 +0000365
Tim Peters1b6f7a92004-06-20 02:50:16 +0000366 def test_insane_timestamps(self):
367 # It's possible that some platform maps time_t to double,
368 # and that this test will fail there. This test should
369 # exempt such platforms (provided they return reasonable
370 # results!).
371 for func in time.ctime, time.gmtime, time.localtime:
372 for unreasonable in -1e200, 1e200:
Victor Stinner5d272cc2012-03-13 13:35:55 +0100373 self.assertRaises(OverflowError, func, unreasonable)
Fred Drakebc561982001-05-22 17:02:02 +0000374
Fred Drakef901abd2004-08-03 17:58:55 +0000375 def test_ctime_without_arg(self):
376 # Not sure how to check the values, since the clock could tick
377 # at any time. Make sure these are at least accepted and
378 # don't raise errors.
379 time.ctime()
380 time.ctime(None)
381
382 def test_gmtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000383 gt0 = time.gmtime()
384 gt1 = time.gmtime(None)
385 t0 = time.mktime(gt0)
386 t1 = time.mktime(gt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000387 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000388
389 def test_localtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000390 lt0 = time.localtime()
391 lt1 = time.localtime(None)
392 t0 = time.mktime(lt0)
393 t1 = time.mktime(lt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000394 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000395
Florent Xiclunae54371e2011-11-11 18:59:30 +0100396 def test_mktime(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100397 # Issue #1726687
398 for t in (-2, -1, 0, 1):
Victor Stinner8c8b4e02014-02-21 23:54:32 +0100399 if sys.platform.startswith('aix') and t == -1:
400 # Issue #11188, #19748: mktime() returns -1 on error. On Linux,
401 # the tm_wday field is used as a sentinel () to detect if -1 is
402 # really an error or a valid timestamp. On AIX, tm_wday is
403 # unchanged even on success and so cannot be used as a
404 # sentinel.
405 continue
Florent Xiclunabceb5282011-11-01 14:11:34 +0100406 try:
407 tt = time.localtime(t)
Victor Stinner2cbae982012-01-27 00:50:33 +0100408 except (OverflowError, OSError):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100409 pass
410 else:
411 self.assertEqual(time.mktime(tt), t)
Florent Xiclunae54371e2011-11-11 18:59:30 +0100412
413 # Issue #13309: passing extreme values to mktime() or localtime()
414 # borks the glibc's internal timezone data.
415 @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
416 "disabled because of a bug in glibc. Issue #13309")
417 def test_mktime_error(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100418 # It may not be possible to reliably make mktime return error
419 # on all platfom. This will make sure that no other exception
420 # than OverflowError is raised for an extreme value.
Florent Xiclunae54371e2011-11-11 18:59:30 +0100421 tt = time.gmtime(self.t)
422 tzname = time.strftime('%Z', tt)
423 self.assertNotEqual(tzname, 'LMT')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100424 try:
425 time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
426 except OverflowError:
427 pass
Florent Xiclunae54371e2011-11-11 18:59:30 +0100428 self.assertEqual(time.strftime('%Z', tt), tzname)
Florent Xiclunabceb5282011-11-01 14:11:34 +0100429
Victor Stinnerec895392012-04-29 02:41:27 +0200430 @unittest.skipUnless(hasattr(time, 'monotonic'),
431 'need time.monotonic')
432 def test_monotonic(self):
Victor Stinner6c861812013-11-23 00:15:27 +0100433 # monotonic() should not go backward
434 times = [time.monotonic() for n in range(100)]
435 t1 = times[0]
436 for t2 in times[1:]:
437 self.assertGreaterEqual(t2, t1, "times=%s" % times)
438 t1 = t2
439
440 # monotonic() includes time elapsed during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200441 t1 = time.monotonic()
Victor Stinnera9c99a62013-07-03 23:07:37 +0200442 time.sleep(0.5)
Victor Stinnerec895392012-04-29 02:41:27 +0200443 t2 = time.monotonic()
Victor Stinner2dd254d2012-01-20 02:24:18 +0100444 dt = t2 - t1
Victor Stinner8b302012012-02-07 23:29:46 +0100445 self.assertGreater(t2, t1)
Zachary Ware487aedb2014-01-02 09:41:10 -0600446 # Issue #20101: On some Windows machines, dt may be slightly low
447 self.assertTrue(0.45 <= dt <= 1.0, dt)
Antoine Pitrou391166f2012-01-18 22:35:21 +0100448
Victor Stinner6c861812013-11-23 00:15:27 +0100449 # monotonic() is a monotonic but non adjustable clock
Victor Stinnerec895392012-04-29 02:41:27 +0200450 info = time.get_clock_info('monotonic')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400451 self.assertTrue(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +0200452 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200453
454 def test_perf_counter(self):
455 time.perf_counter()
456
457 def test_process_time(self):
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200458 # process_time() should not include time spend during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200459 start = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200460 time.sleep(0.100)
Victor Stinnerec895392012-04-29 02:41:27 +0200461 stop = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200462 # use 20 ms because process_time() has usually a resolution of 15 ms
463 # on Windows
464 self.assertLess(stop - start, 0.020)
Victor Stinnerec895392012-04-29 02:41:27 +0200465
466 info = time.get_clock_info('process_time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400467 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200468 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200469
Victor Stinnerec895392012-04-29 02:41:27 +0200470 @unittest.skipUnless(hasattr(time, 'monotonic'),
471 'need time.monotonic')
472 @unittest.skipUnless(hasattr(time, 'clock_settime'),
473 'need time.clock_settime')
474 def test_monotonic_settime(self):
475 t1 = time.monotonic()
476 realtime = time.clock_gettime(time.CLOCK_REALTIME)
477 # jump backward with an offset of 1 hour
Victor Stinner071eca32012-03-15 01:17:09 +0100478 try:
Victor Stinnerec895392012-04-29 02:41:27 +0200479 time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
480 except PermissionError as err:
481 self.skipTest(err)
482 t2 = time.monotonic()
483 time.clock_settime(time.CLOCK_REALTIME, realtime)
484 # monotonic must not be affected by system clock updates
Victor Stinner071eca32012-03-15 01:17:09 +0100485 self.assertGreaterEqual(t2, t1)
486
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100487 def test_localtime_failure(self):
488 # Issue #13847: check for localtime() failure
Victor Stinner53d36452012-01-27 01:03:25 +0100489 invalid_time_t = None
490 for time_t in (-1, 2**30, 2**33, 2**60):
491 try:
492 time.localtime(time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100493 except OverflowError:
494 self.skipTest("need 64-bit time_t")
Victor Stinner53d36452012-01-27 01:03:25 +0100495 except OSError:
496 invalid_time_t = time_t
497 break
498 if invalid_time_t is None:
499 self.skipTest("unable to find an invalid time_t value")
500
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100501 self.assertRaises(OSError, time.localtime, invalid_time_t)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100502 self.assertRaises(OSError, time.ctime, invalid_time_t)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100503
Han Lee829dacc2017-09-09 08:05:05 +0900504 # Issue #26669: check for localtime() failure
505 self.assertRaises(ValueError, time.localtime, float("nan"))
506 self.assertRaises(ValueError, time.ctime, float("nan"))
507
Victor Stinnerec895392012-04-29 02:41:27 +0200508 def test_get_clock_info(self):
509 clocks = ['clock', 'perf_counter', 'process_time', 'time']
510 if hasattr(time, 'monotonic'):
511 clocks.append('monotonic')
512
513 for name in clocks:
514 info = time.get_clock_info(name)
515 #self.assertIsInstance(info, dict)
516 self.assertIsInstance(info.implementation, str)
517 self.assertNotEqual(info.implementation, '')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400518 self.assertIsInstance(info.monotonic, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200519 self.assertIsInstance(info.resolution, float)
520 # 0.0 < resolution <= 1.0
521 self.assertGreater(info.resolution, 0.0)
522 self.assertLessEqual(info.resolution, 1.0)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200523 self.assertIsInstance(info.adjustable, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200524
525 self.assertRaises(ValueError, time.get_clock_info, 'xxx')
526
527
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000528class TestLocale(unittest.TestCase):
529 def setUp(self):
530 self.oldloc = locale.setlocale(locale.LC_ALL)
Fred Drake2e2be372001-09-20 21:33:42 +0000531
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000532 def tearDown(self):
533 locale.setlocale(locale.LC_ALL, self.oldloc)
534
Martin v. Löwisa6a9c4d2009-05-30 06:15:30 +0000535 def test_bug_3061(self):
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000536 try:
537 tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
538 except locale.Error:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600539 self.skipTest('could not set locale.LC_ALL to fr_FR')
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000540 # This should not cause an exception
541 time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
542
Victor Stinner73ea29c2011-01-08 01:56:31 +0000543
Victor Stinner73ea29c2011-01-08 01:56:31 +0000544class _TestAsctimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100545 _format = '%d'
546
Victor Stinner73ea29c2011-01-08 01:56:31 +0000547 def yearstr(self, y):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000548 return time.asctime((y,) + (0,) * 8).split()[-1]
Alexander Belopolskya6867252011-01-05 23:00:47 +0000549
Victor Stinner73ea29c2011-01-08 01:56:31 +0000550 def test_large_year(self):
Victor Stinner73691322011-01-08 02:00:24 +0000551 # Check that it doesn't crash for year > 9999
Victor Stinner73ea29c2011-01-08 01:56:31 +0000552 self.assertEqual(self.yearstr(12345), '12345')
553 self.assertEqual(self.yearstr(123456789), '123456789')
554
555class _TestStrftimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100556
557 # Issue 13305: For years < 1000, the value is not always
558 # padded to 4 digits across platforms. The C standard
559 # assumes year >= 1900, so it does not specify the number
560 # of digits.
561
562 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
563 _format = '%04d'
564 else:
565 _format = '%d'
566
Victor Stinner73ea29c2011-01-08 01:56:31 +0000567 def yearstr(self, y):
Florent Xicluna49ce0682011-11-01 12:56:14 +0100568 return time.strftime('%Y', (y,) + (0,) * 8)
569
570 def test_4dyear(self):
571 # Check that we can return the zero padded value.
572 if self._format == '%04d':
573 self.test_year('%04d')
574 else:
575 def year4d(y):
576 return time.strftime('%4Y', (y,) + (0,) * 8)
577 self.test_year('%04d', func=year4d)
578
Florent Xiclunabceb5282011-11-01 14:11:34 +0100579 def skip_if_not_supported(y):
580 msg = "strftime() is limited to [1; 9999] with Visual Studio"
581 # Check that it doesn't crash for year > 9999
582 try:
583 time.strftime('%Y', (y,) + (0,) * 8)
584 except ValueError:
585 cond = False
586 else:
587 cond = True
588 return unittest.skipUnless(cond, msg)
589
590 @skip_if_not_supported(10000)
591 def test_large_year(self):
592 return super().test_large_year()
593
594 @skip_if_not_supported(0)
595 def test_negative(self):
596 return super().test_negative()
597
598 del skip_if_not_supported
599
600
Ezio Melotti3836d702013-04-11 20:29:42 +0300601class _Test4dYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100602 _format = '%d'
603
604 def test_year(self, fmt=None, func=None):
605 fmt = fmt or self._format
606 func = func or self.yearstr
607 self.assertEqual(func(1), fmt % 1)
608 self.assertEqual(func(68), fmt % 68)
609 self.assertEqual(func(69), fmt % 69)
610 self.assertEqual(func(99), fmt % 99)
611 self.assertEqual(func(999), fmt % 999)
612 self.assertEqual(func(9999), fmt % 9999)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000613
614 def test_large_year(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100615 self.assertEqual(self.yearstr(12345), '12345')
Victor Stinner13ed2ea2011-03-21 02:11:01 +0100616 self.assertEqual(self.yearstr(123456789), '123456789')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100617 self.assertEqual(self.yearstr(TIME_MAXYEAR), str(TIME_MAXYEAR))
618 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000619
Victor Stinner301f1212011-01-08 03:06:52 +0000620 def test_negative(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100621 self.assertEqual(self.yearstr(-1), self._format % -1)
Victor Stinner301f1212011-01-08 03:06:52 +0000622 self.assertEqual(self.yearstr(-1234), '-1234')
623 self.assertEqual(self.yearstr(-123456), '-123456')
Florent Xiclunad1bd7f72011-11-01 23:42:05 +0100624 self.assertEqual(self.yearstr(-123456789), str(-123456789))
625 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
Florent Xicluna2fbc1852011-11-02 08:13:43 +0100626 self.assertEqual(self.yearstr(TIME_MINYEAR + 1900), str(TIME_MINYEAR + 1900))
627 # Issue #13312: it may return wrong value for year < TIME_MINYEAR + 1900
628 # Skip the value test, but check that no error is raised
629 self.yearstr(TIME_MINYEAR)
Florent Xiclunae2a732e2011-11-02 01:28:17 +0100630 # self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
Florent Xiclunabceb5282011-11-01 14:11:34 +0100631 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
Victor Stinner301f1212011-01-08 03:06:52 +0000632
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000633
Ezio Melotti3836d702013-04-11 20:29:42 +0300634class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner73ea29c2011-01-08 01:56:31 +0000635 pass
636
Ezio Melotti3836d702013-04-11 20:29:42 +0300637class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner301f1212011-01-08 03:06:52 +0000638 pass
Victor Stinner73ea29c2011-01-08 01:56:31 +0000639
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000640
Victor Stinner643cd682012-03-02 22:54:03 +0100641class TestPytime(unittest.TestCase):
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400642 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
643 def test_localtime_timezone(self):
Victor Stinner643cd682012-03-02 22:54:03 +0100644
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400645 # Get the localtime and examine it for the offset and zone.
646 lt = time.localtime()
647 self.assertTrue(hasattr(lt, "tm_gmtoff"))
648 self.assertTrue(hasattr(lt, "tm_zone"))
649
650 # See if the offset and zone are similar to the module
651 # attributes.
652 if lt.tm_gmtoff is None:
653 self.assertTrue(not hasattr(time, "timezone"))
654 else:
655 self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
656 if lt.tm_zone is None:
657 self.assertTrue(not hasattr(time, "tzname"))
658 else:
659 self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
660
661 # Try and make UNIX times from the localtime and a 9-tuple
662 # created from the localtime. Test to see that the times are
663 # the same.
664 t = time.mktime(lt); t9 = time.mktime(lt[:9])
665 self.assertEqual(t, t9)
666
667 # Make localtimes from the UNIX times and compare them to
668 # the original localtime, thus making a round trip.
669 new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
670 self.assertEqual(new_lt, lt)
671 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
672 self.assertEqual(new_lt.tm_zone, lt.tm_zone)
673 self.assertEqual(new_lt9, lt)
674 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
675 self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
676
677 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
678 def test_strptime_timezone(self):
679 t = time.strptime("UTC", "%Z")
680 self.assertEqual(t.tm_zone, 'UTC')
681 t = time.strptime("+0500", "%z")
682 self.assertEqual(t.tm_gmtoff, 5 * 3600)
683
684 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
685 def test_short_times(self):
686
687 import pickle
688
689 # Load a short time structure using pickle.
690 st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
691 lt = pickle.loads(st)
692 self.assertIs(lt.tm_gmtoff, None)
693 self.assertIs(lt.tm_zone, None)
Victor Stinner643cd682012-03-02 22:54:03 +0100694
Fred Drake2e2be372001-09-20 21:33:42 +0000695
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200696@unittest.skipIf(_testcapi is None, 'need the _testcapi module')
697class CPyTimeTestCase:
Victor Stinneracea9f62015-09-02 10:39:40 +0200698 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200699 Base class to test the C _PyTime_t API.
Victor Stinneracea9f62015-09-02 10:39:40 +0200700 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200701 OVERFLOW_SECONDS = None
702
Victor Stinner4237d342015-09-10 10:10:39 +0200703 def setUp(self):
704 from _testcapi import SIZEOF_TIME_T
705 bits = SIZEOF_TIME_T * 8 - 1
706 self.time_t_min = -2 ** bits
707 self.time_t_max = 2 ** bits - 1
708
709 def time_t_filter(self, seconds):
710 return (self.time_t_min <= seconds <= self.time_t_max)
711
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200712 def _rounding_values(self, use_float):
713 "Build timestamps used to test rounding."
714
715 units = [1, US_TO_NS, MS_TO_NS, SEC_TO_NS]
716 if use_float:
717 # picoseconds are only tested to pytime_converter accepting floats
718 units.append(1e-3)
719
720 values = (
721 # small values
722 1, 2, 5, 7, 123, 456, 1234,
723 # 10^k - 1
724 9,
725 99,
726 999,
727 9999,
728 99999,
729 999999,
730 # test half even rounding near 0.5, 1.5, 2.5, 3.5, 4.5
731 499, 500, 501,
732 1499, 1500, 1501,
733 2500,
734 3500,
735 4500,
736 )
737
738 ns_timestamps = [0]
739 for unit in units:
740 for value in values:
741 ns = value * unit
742 ns_timestamps.extend((-ns, ns))
743 for pow2 in (0, 5, 10, 15, 22, 23, 24, 30, 33):
744 ns = (2 ** pow2) * SEC_TO_NS
745 ns_timestamps.extend((
746 -ns-1, -ns, -ns+1,
747 ns-1, ns, ns+1
748 ))
749 for seconds in (_testcapi.INT_MIN, _testcapi.INT_MAX):
750 ns_timestamps.append(seconds * SEC_TO_NS)
751 if use_float:
Victor Stinner717a32b2016-08-17 11:07:21 +0200752 # numbers with an exact representation in IEEE 754 (base 2)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200753 for pow2 in (3, 7, 10, 15):
754 ns = 2.0 ** (-pow2)
755 ns_timestamps.extend((-ns, ns))
756
757 # seconds close to _PyTime_t type limit
758 ns = (2 ** 63 // SEC_TO_NS) * SEC_TO_NS
759 ns_timestamps.extend((-ns, ns))
760
761 return ns_timestamps
762
763 def _check_rounding(self, pytime_converter, expected_func,
764 use_float, unit_to_sec, value_filter=None):
765
766 def convert_values(ns_timestamps):
767 if use_float:
768 unit_to_ns = SEC_TO_NS / float(unit_to_sec)
769 values = [ns / unit_to_ns for ns in ns_timestamps]
770 else:
771 unit_to_ns = SEC_TO_NS // unit_to_sec
772 values = [ns // unit_to_ns for ns in ns_timestamps]
773
774 if value_filter:
775 values = filter(value_filter, values)
776
777 # remove duplicates and sort
778 return sorted(set(values))
779
780 # test rounding
781 ns_timestamps = self._rounding_values(use_float)
782 valid_values = convert_values(ns_timestamps)
783 for time_rnd, decimal_rnd in ROUNDING_MODES :
784 context = decimal.getcontext()
785 context.rounding = decimal_rnd
786
787 for value in valid_values:
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200788 debug_info = {'value': value, 'rounding': decimal_rnd}
789 try:
790 result = pytime_converter(value, time_rnd)
791 expected = expected_func(value)
792 except Exception as exc:
793 self.fail("Error on timestamp conversion: %s" % debug_info)
794 self.assertEqual(result,
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200795 expected,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200796 debug_info)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200797
798 # test overflow
799 ns = self.OVERFLOW_SECONDS * SEC_TO_NS
800 ns_timestamps = (-ns, ns)
801 overflow_values = convert_values(ns_timestamps)
802 for time_rnd, _ in ROUNDING_MODES :
803 for value in overflow_values:
Victor Stinnerc60542b2015-09-10 15:55:07 +0200804 debug_info = {'value': value, 'rounding': time_rnd}
805 with self.assertRaises(OverflowError, msg=debug_info):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200806 pytime_converter(value, time_rnd)
807
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200808 def check_int_rounding(self, pytime_converter, expected_func,
809 unit_to_sec=1, value_filter=None):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200810 self._check_rounding(pytime_converter, expected_func,
811 False, unit_to_sec, value_filter)
812
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200813 def check_float_rounding(self, pytime_converter, expected_func,
814 unit_to_sec=1, value_filter=None):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200815 self._check_rounding(pytime_converter, expected_func,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200816 True, unit_to_sec, value_filter)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200817
818 def decimal_round(self, x):
819 d = decimal.Decimal(x)
820 d = d.quantize(1)
821 return int(d)
822
823
824class TestCPyTime(CPyTimeTestCase, unittest.TestCase):
825 """
826 Test the C _PyTime_t API.
827 """
828 # _PyTime_t is a 64-bit signed integer
829 OVERFLOW_SECONDS = math.ceil((2**63 + 1) / SEC_TO_NS)
830
Victor Stinner13019fd2015-04-03 13:10:54 +0200831 def test_FromSeconds(self):
832 from _testcapi import PyTime_FromSeconds
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200833
834 # PyTime_FromSeconds() expects a C int, reject values out of range
835 def c_int_filter(secs):
836 return (_testcapi.INT_MIN <= secs <= _testcapi.INT_MAX)
837
838 self.check_int_rounding(lambda secs, rnd: PyTime_FromSeconds(secs),
839 lambda secs: secs * SEC_TO_NS,
840 value_filter=c_int_filter)
Victor Stinner13019fd2015-04-03 13:10:54 +0200841
Han Lee829dacc2017-09-09 08:05:05 +0900842 # test nan
843 for time_rnd, _ in ROUNDING_MODES:
844 with self.assertRaises(TypeError):
845 PyTime_FromSeconds(float('nan'))
846
Victor Stinner992c43f2015-03-27 17:12:45 +0100847 def test_FromSecondsObject(self):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100848 from _testcapi import PyTime_FromSecondsObject
Victor Stinner992c43f2015-03-27 17:12:45 +0100849
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200850 self.check_int_rounding(
851 PyTime_FromSecondsObject,
852 lambda secs: secs * SEC_TO_NS)
Victor Stinner992c43f2015-03-27 17:12:45 +0100853
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200854 self.check_float_rounding(
855 PyTime_FromSecondsObject,
856 lambda ns: self.decimal_round(ns * SEC_TO_NS))
Victor Stinner4bfb4602015-03-27 22:27:24 +0100857
Han Lee829dacc2017-09-09 08:05:05 +0900858 # test nan
859 for time_rnd, _ in ROUNDING_MODES:
860 with self.assertRaises(ValueError):
861 PyTime_FromSecondsObject(float('nan'), time_rnd)
862
Victor Stinner4bfb4602015-03-27 22:27:24 +0100863 def test_AsSecondsDouble(self):
864 from _testcapi import PyTime_AsSecondsDouble
865
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200866 def float_converter(ns):
867 if abs(ns) % SEC_TO_NS == 0:
868 return float(ns // SEC_TO_NS)
869 else:
870 return float(ns) / SEC_TO_NS
Victor Stinner4bfb4602015-03-27 22:27:24 +0100871
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200872 self.check_int_rounding(lambda ns, rnd: PyTime_AsSecondsDouble(ns),
873 float_converter,
874 NS_TO_SEC)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100875
Han Lee829dacc2017-09-09 08:05:05 +0900876 # test nan
877 for time_rnd, _ in ROUNDING_MODES:
878 with self.assertRaises(TypeError):
879 PyTime_AsSecondsDouble(float('nan'))
880
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200881 def create_decimal_converter(self, denominator):
882 denom = decimal.Decimal(denominator)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100883
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200884 def converter(value):
885 d = decimal.Decimal(value) / denom
886 return self.decimal_round(d)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100887
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200888 return converter
Victor Stinner4bfb4602015-03-27 22:27:24 +0100889
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200890 def test_AsTimeval(self):
Victor Stinner95e9cef2015-03-28 01:26:47 +0100891 from _testcapi import PyTime_AsTimeval
Victor Stinner95e9cef2015-03-28 01:26:47 +0100892
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200893 us_converter = self.create_decimal_converter(US_TO_NS)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100894
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200895 def timeval_converter(ns):
896 us = us_converter(ns)
897 return divmod(us, SEC_TO_US)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100898
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200899 if sys.platform == 'win32':
900 from _testcapi import LONG_MIN, LONG_MAX
901
902 # On Windows, timeval.tv_sec type is a C long
903 def seconds_filter(secs):
904 return LONG_MIN <= secs <= LONG_MAX
905 else:
Victor Stinner4237d342015-09-10 10:10:39 +0200906 seconds_filter = self.time_t_filter
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200907
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200908 self.check_int_rounding(PyTime_AsTimeval,
909 timeval_converter,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200910 NS_TO_SEC,
911 value_filter=seconds_filter)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100912
Victor Stinner34dc0f42015-03-27 18:19:03 +0100913 @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec'),
914 'need _testcapi.PyTime_AsTimespec')
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200915 def test_AsTimespec(self):
Victor Stinner34dc0f42015-03-27 18:19:03 +0100916 from _testcapi import PyTime_AsTimespec
Victor Stinner34dc0f42015-03-27 18:19:03 +0100917
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200918 def timespec_converter(ns):
919 return divmod(ns, SEC_TO_NS)
Victor Stinner34dc0f42015-03-27 18:19:03 +0100920
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200921 self.check_int_rounding(lambda ns, rnd: PyTime_AsTimespec(ns),
922 timespec_converter,
Victor Stinner4237d342015-09-10 10:10:39 +0200923 NS_TO_SEC,
924 value_filter=self.time_t_filter)
Victor Stinner34dc0f42015-03-27 18:19:03 +0100925
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200926 def test_AsMilliseconds(self):
Victor Stinner62d1c702015-04-01 17:47:07 +0200927 from _testcapi import PyTime_AsMilliseconds
Victor Stinner62d1c702015-04-01 17:47:07 +0200928
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200929 self.check_int_rounding(PyTime_AsMilliseconds,
930 self.create_decimal_converter(MS_TO_NS),
931 NS_TO_SEC)
Victor Stinner62d1c702015-04-01 17:47:07 +0200932
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200933 def test_AsMicroseconds(self):
Victor Stinner62d1c702015-04-01 17:47:07 +0200934 from _testcapi import PyTime_AsMicroseconds
Victor Stinner62d1c702015-04-01 17:47:07 +0200935
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200936 self.check_int_rounding(PyTime_AsMicroseconds,
937 self.create_decimal_converter(US_TO_NS),
938 NS_TO_SEC)
Victor Stinner62d1c702015-04-01 17:47:07 +0200939
Victor Stinner992c43f2015-03-27 17:12:45 +0100940
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200941class TestOldPyTime(CPyTimeTestCase, unittest.TestCase):
Victor Stinneracea9f62015-09-02 10:39:40 +0200942 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200943 Test the old C _PyTime_t API: _PyTime_ObjectToXXX() functions.
Victor Stinneracea9f62015-09-02 10:39:40 +0200944 """
Victor Stinneracea9f62015-09-02 10:39:40 +0200945
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200946 # time_t is a 32-bit or 64-bit signed integer
947 OVERFLOW_SECONDS = 2 ** 64
948
949 def test_object_to_time_t(self):
Victor Stinneracea9f62015-09-02 10:39:40 +0200950 from _testcapi import pytime_object_to_time_t
951
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200952 self.check_int_rounding(pytime_object_to_time_t,
Victor Stinner4237d342015-09-10 10:10:39 +0200953 lambda secs: secs,
954 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200955
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200956 self.check_float_rounding(pytime_object_to_time_t,
Victor Stinner350b5182015-09-10 11:45:06 +0200957 self.decimal_round,
958 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200959
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200960 def create_converter(self, sec_to_unit):
961 def converter(secs):
962 floatpart, intpart = math.modf(secs)
963 intpart = int(intpart)
964 floatpart *= sec_to_unit
965 floatpart = self.decimal_round(floatpart)
966 if floatpart < 0:
967 floatpart += sec_to_unit
968 intpart -= 1
969 elif floatpart >= sec_to_unit:
970 floatpart -= sec_to_unit
971 intpart += 1
972 return (intpart, floatpart)
973 return converter
Victor Stinneracea9f62015-09-02 10:39:40 +0200974
Victor Stinneradfefa52015-09-04 23:57:25 +0200975 def test_object_to_timeval(self):
Victor Stinneracea9f62015-09-02 10:39:40 +0200976 from _testcapi import pytime_object_to_timeval
977
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200978 self.check_int_rounding(pytime_object_to_timeval,
Victor Stinner4237d342015-09-10 10:10:39 +0200979 lambda secs: (secs, 0),
980 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200981
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200982 self.check_float_rounding(pytime_object_to_timeval,
Victor Stinner350b5182015-09-10 11:45:06 +0200983 self.create_converter(SEC_TO_US),
984 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200985
Han Lee829dacc2017-09-09 08:05:05 +0900986 # test nan
987 for time_rnd, _ in ROUNDING_MODES:
988 with self.assertRaises(ValueError):
989 pytime_object_to_timeval(float('nan'), time_rnd)
990
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200991 def test_object_to_timespec(self):
Victor Stinneracea9f62015-09-02 10:39:40 +0200992 from _testcapi import pytime_object_to_timespec
993
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200994 self.check_int_rounding(pytime_object_to_timespec,
Victor Stinner4237d342015-09-10 10:10:39 +0200995 lambda secs: (secs, 0),
996 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200997
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200998 self.check_float_rounding(pytime_object_to_timespec,
Victor Stinner350b5182015-09-10 11:45:06 +0200999 self.create_converter(SEC_TO_NS),
1000 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +02001001
Han Lee829dacc2017-09-09 08:05:05 +09001002 # test nan
1003 for time_rnd, _ in ROUNDING_MODES:
1004 with self.assertRaises(ValueError):
1005 pytime_object_to_timespec(float('nan'), time_rnd)
1006
Victor Stinneracea9f62015-09-02 10:39:40 +02001007
Fred Drake2e2be372001-09-20 21:33:42 +00001008if __name__ == "__main__":
Ezio Melotti3836d702013-04-11 20:29:42 +03001009 unittest.main()