blob: 810ec37b1113f9faddfda2e2cb286f6c1622c913 [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
Fred Drakebc561982001-05-22 17:02:02 +000010import unittest
Victor Stinnerec895392012-04-29 02:41:27 +020011try:
12 import threading
13except ImportError:
14 threading = None
Victor Stinner34dc0f42015-03-27 18:19:03 +010015try:
16 import _testcapi
17except ImportError:
18 _testcapi = None
19
Barry Warsawb0c22321996-12-06 23:30:07 +000020
Florent Xiclunabceb5282011-11-01 14:11:34 +010021# Max year is only limited by the size of C int.
22SIZEOF_INT = sysconfig.get_config_var('SIZEOF_INT') or 4
23TIME_MAXYEAR = (1 << 8 * SIZEOF_INT - 1) - 1
24TIME_MINYEAR = -TIME_MAXYEAR - 1
Victor Stinner992c43f2015-03-27 17:12:45 +010025
Victor Stinner3e2c8d82015-09-09 22:32:48 +020026SEC_TO_US = 10 ** 6
Victor Stinner62d1c702015-04-01 17:47:07 +020027US_TO_NS = 10 ** 3
28MS_TO_NS = 10 ** 6
Victor Stinner4bfb4602015-03-27 22:27:24 +010029SEC_TO_NS = 10 ** 9
Victor Stinner3e2c8d82015-09-09 22:32:48 +020030NS_TO_SEC = 10 ** 9
Victor Stinner992c43f2015-03-27 17:12:45 +010031
32class _PyTime(enum.IntEnum):
Victor Stinnerbcdd7772015-03-30 03:52:49 +020033 # Round towards minus infinity (-inf)
Victor Stinnera695f832015-03-30 03:57:14 +020034 ROUND_FLOOR = 0
Victor Stinnerbcdd7772015-03-30 03:52:49 +020035 # Round towards infinity (+inf)
Victor Stinnera695f832015-03-30 03:57:14 +020036 ROUND_CEILING = 1
Victor Stinner7667f582015-09-09 01:02:23 +020037 # Round to nearest with ties going to nearest even integer
38 ROUND_HALF_EVEN = 2
Victor Stinner992c43f2015-03-27 17:12:45 +010039
Victor Stinner3e2c8d82015-09-09 22:32:48 +020040# Rounding modes supported by PyTime
41ROUNDING_MODES = (
42 # (PyTime rounding method, decimal rounding method)
43 (_PyTime.ROUND_FLOOR, decimal.ROUND_FLOOR),
44 (_PyTime.ROUND_CEILING, decimal.ROUND_CEILING),
45 (_PyTime.ROUND_HALF_EVEN, decimal.ROUND_HALF_EVEN),
46)
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
87 @unittest.skipUnless(hasattr(time, 'clock_getres'),
88 'need time.clock_getres()')
89 def test_clock_getres(self):
90 res = time.clock_getres(time.CLOCK_REALTIME)
91 self.assertGreater(res, 0.0)
92 self.assertLessEqual(res, 1.0)
93
Victor Stinner30d79472012-04-03 00:45:07 +020094 @unittest.skipUnless(hasattr(time, 'clock_settime'),
95 'need time.clock_settime()')
96 def test_clock_settime(self):
97 t = time.clock_gettime(time.CLOCK_REALTIME)
98 try:
99 time.clock_settime(time.CLOCK_REALTIME, t)
100 except PermissionError:
101 pass
102
Victor Stinnerec895392012-04-29 02:41:27 +0200103 if hasattr(time, 'CLOCK_MONOTONIC'):
104 self.assertRaises(OSError,
105 time.clock_settime, time.CLOCK_MONOTONIC, 0)
Victor Stinner30d79472012-04-03 00:45:07 +0200106
Fred Drakebc561982001-05-22 17:02:02 +0000107 def test_conversions(self):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000108 self.assertEqual(time.ctime(self.t),
109 time.asctime(time.localtime(self.t)))
110 self.assertEqual(int(time.mktime(time.localtime(self.t))),
111 int(self.t))
Fred Drakebc561982001-05-22 17:02:02 +0000112
113 def test_sleep(self):
Victor Stinner7f53a502011-07-05 22:00:25 +0200114 self.assertRaises(ValueError, time.sleep, -2)
115 self.assertRaises(ValueError, time.sleep, -1)
Fred Drakebc561982001-05-22 17:02:02 +0000116 time.sleep(1.2)
117
118 def test_strftime(self):
119 tt = time.gmtime(self.t)
120 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
121 'j', 'm', 'M', 'p', 'S',
122 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
123 format = ' %' + directive
124 try:
125 time.strftime(format, tt)
126 except ValueError:
127 self.fail('conversion specifier: %r failed.' % format)
128
Serhiy Storchaka08349052017-06-28 09:27:35 +0300129 self.assertRaises(TypeError, time.strftime, b'%S', tt)
130 # embedded null character
131 self.assertRaises(ValueError, time.strftime, '%S\0', tt)
132
Florent Xicluna49ce0682011-11-01 12:56:14 +0100133 def _bounds_checking(self, func):
Brett Cannond1080a32004-03-02 04:38:10 +0000134 # Make sure that strftime() checks the bounds of the various parts
Florent Xicluna49ce0682011-11-01 12:56:14 +0100135 # of the time tuple (0 is valid for *all* values).
Brett Cannond1080a32004-03-02 04:38:10 +0000136
Victor Stinner73ea29c2011-01-08 01:56:31 +0000137 # The year field is tested by other test cases above
138
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000139 # Check month [1, 12] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100140 func((1900, 0, 1, 0, 0, 0, 0, 1, -1))
141 func((1900, 12, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000142 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000143 (1900, -1, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000144 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000145 (1900, 13, 1, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000146 # Check day of month [1, 31] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100147 func((1900, 1, 0, 0, 0, 0, 0, 1, -1))
148 func((1900, 1, 31, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000149 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000150 (1900, 1, -1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000151 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000152 (1900, 1, 32, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000153 # Check hour [0, 23]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100154 func((1900, 1, 1, 23, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000155 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000156 (1900, 1, 1, -1, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000157 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000158 (1900, 1, 1, 24, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000159 # Check minute [0, 59]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100160 func((1900, 1, 1, 0, 59, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000161 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000162 (1900, 1, 1, 0, -1, 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, 1, 0, 60, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000165 # Check second [0, 61]
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000166 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000167 (1900, 1, 1, 0, 0, -1, 0, 1, -1))
168 # C99 only requires allowing for one leap second, but Python's docs say
169 # allow two leap seconds (0..61)
Florent Xicluna49ce0682011-11-01 12:56:14 +0100170 func((1900, 1, 1, 0, 0, 60, 0, 1, -1))
171 func((1900, 1, 1, 0, 0, 61, 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, 0, 62, 0, 1, -1))
174 # No check for upper-bound day of week;
175 # value forced into range by a ``% 7`` calculation.
176 # Start check at -2 since gettmarg() increments value before taking
177 # modulo.
Florent Xicluna49ce0682011-11-01 12:56:14 +0100178 self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)),
179 func((1900, 1, 1, 0, 0, 0, +6, 1, -1)))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000180 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000181 (1900, 1, 1, 0, 0, 0, -2, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000182 # Check day of the year [1, 366] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100183 func((1900, 1, 1, 0, 0, 0, 0, 0, -1))
184 func((1900, 1, 1, 0, 0, 0, 0, 366, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000185 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000186 (1900, 1, 1, 0, 0, 0, 0, -1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000187 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000188 (1900, 1, 1, 0, 0, 0, 0, 367, -1))
Brett Cannond1080a32004-03-02 04:38:10 +0000189
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000190 def test_strftime_bounding_check(self):
191 self._bounds_checking(lambda tup: time.strftime('', tup))
192
Steve Dowere5b58952015-09-06 19:20:51 -0700193 def test_strftime_format_check(self):
194 # Test that strftime does not crash on invalid format strings
195 # that may trigger a buffer overread. When not triggered,
196 # strftime may succeed or raise ValueError depending on
197 # the platform.
198 for x in [ '', 'A', '%A', '%AA' ]:
199 for y in range(0x0, 0x10):
200 for z in [ '%', 'A%', 'AA%', '%A%', 'A%A%', '%#' ]:
201 try:
202 time.strftime(x * y + z)
203 except ValueError:
204 pass
205
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000206 def test_default_values_for_zero(self):
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400207 # Make sure that using all zeros uses the proper default
208 # values. No test for daylight savings since strftime() does
209 # not change output based on its value and no test for year
210 # because systems vary in their support for year 0.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000211 expected = "2000 01 01 00 00 00 1 001"
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000212 with support.check_warnings():
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400213 result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000214 self.assertEqual(expected, result)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000215
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000216 def test_strptime(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000217 # Should be able to go round-trip from strftime to strptime without
Andrew Svetlov737fb892012-12-18 21:14:22 +0200218 # raising an exception.
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000219 tt = time.gmtime(self.t)
220 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
221 'j', 'm', 'M', 'p', 'S',
222 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000223 format = '%' + directive
224 strf_output = time.strftime(format, tt)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000225 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000226 time.strptime(strf_output, format)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000227 except ValueError:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000228 self.fail("conversion specifier %r failed with '%s' input." %
229 (format, strf_output))
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000230
Brett Cannon7f6b4f82009-03-30 21:30:26 +0000231 def test_strptime_bytes(self):
232 # Make sure only strings are accepted as arguments to strptime.
233 self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
234 self.assertRaises(TypeError, time.strptime, '2009', b'%Y')
235
Ezio Melotti0f389082013-04-04 02:09:20 +0300236 def test_strptime_exception_context(self):
237 # check that this doesn't chain exceptions needlessly (see #17572)
238 with self.assertRaises(ValueError) as e:
239 time.strptime('', '%D')
240 self.assertIs(e.exception.__suppress_context__, True)
Serhiy Storchakacdac3022013-11-24 18:15:37 +0200241 # additional check for IndexError branch (issue #19545)
242 with self.assertRaises(ValueError) as e:
243 time.strptime('19', '%Y %')
244 self.assertIs(e.exception.__suppress_context__, True)
Ezio Melotti0f389082013-04-04 02:09:20 +0300245
Fred Drakebc561982001-05-22 17:02:02 +0000246 def test_asctime(self):
247 time.asctime(time.gmtime(self.t))
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000248
249 # Max year is only limited by the size of C int.
Florent Xiclunabceb5282011-11-01 14:11:34 +0100250 for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
251 asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
252 self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
253 self.assertRaises(OverflowError, time.asctime,
254 (TIME_MAXYEAR + 1,) + (0,) * 8)
255 self.assertRaises(OverflowError, time.asctime,
256 (TIME_MINYEAR - 1,) + (0,) * 8)
Fred Drakebc561982001-05-22 17:02:02 +0000257 self.assertRaises(TypeError, time.asctime, 0)
Alexander Belopolskye2dc0822011-01-02 20:48:22 +0000258 self.assertRaises(TypeError, time.asctime, ())
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000259 self.assertRaises(TypeError, time.asctime, (0,) * 10)
Fred Drakebc561982001-05-22 17:02:02 +0000260
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000261 def test_asctime_bounding_check(self):
262 self._bounds_checking(time.asctime)
263
Georg Brandle10608c2011-01-02 22:33:43 +0000264 def test_ctime(self):
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000265 t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
266 self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
267 t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
268 self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000')
Victor Stinner1ac42612014-02-21 09:27:17 +0100269 for year in [-100, 100, 1000, 2000, 2050, 10000]:
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000270 try:
271 testval = time.mktime((year, 1, 10) + (0,)*6)
272 except (ValueError, OverflowError):
273 # If mktime fails, ctime will fail too. This may happen
274 # on some platforms.
275 pass
276 else:
277 self.assertEqual(time.ctime(testval)[20:], str(year))
Georg Brandle10608c2011-01-02 22:33:43 +0000278
Florent Xiclunae54371e2011-11-11 18:59:30 +0100279 @unittest.skipUnless(hasattr(time, "tzset"),
280 "time module has no attribute tzset")
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000281 def test_tzset(self):
Guido van Rossumd2b738e2003-03-15 12:01:52 +0000282
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000283 from os import environ
284
Tim Peters0eadaac2003-04-24 16:02:54 +0000285 # Epoch time of midnight Dec 25th 2002. Never DST in northern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000286 # hemisphere.
Tim Peters0eadaac2003-04-24 16:02:54 +0000287 xmas2002 = 1040774400.0
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000288
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000289 # These formats are correct for 2002, and possibly future years
290 # This format is the 'standard' as documented at:
291 # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
292 # They are also documented in the tzset(3) man page on most Unix
293 # systems.
Tim Peters0eadaac2003-04-24 16:02:54 +0000294 eastern = 'EST+05EDT,M4.1.0,M10.5.0'
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000295 victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
296 utc='UTC+0'
297
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000298 org_TZ = environ.get('TZ',None)
299 try:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000300 # Make sure we can switch to UTC time and results are correct
301 # Note that unknown timezones default to UTC.
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000302 # Note that altzone is undefined in UTC, as there is no DST
303 environ['TZ'] = eastern
304 time.tzset()
305 environ['TZ'] = utc
306 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000307 self.assertEqual(
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000308 time.gmtime(xmas2002), time.localtime(xmas2002)
309 )
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000310 self.assertEqual(time.daylight, 0)
311 self.assertEqual(time.timezone, 0)
312 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000313
314 # Make sure we can switch to US/Eastern
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000315 environ['TZ'] = eastern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000316 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000317 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
318 self.assertEqual(time.tzname, ('EST', 'EDT'))
319 self.assertEqual(len(time.tzname), 2)
320 self.assertEqual(time.daylight, 1)
321 self.assertEqual(time.timezone, 18000)
322 self.assertEqual(time.altzone, 14400)
323 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
324 self.assertEqual(len(time.tzname), 2)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000325
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000326 # Now go to the southern hemisphere.
327 environ['TZ'] = victoria
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))
Victor Stinner0cd47902011-12-08 00:32:51 +0100330
331 # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100332 # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
333 # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
334 # on some operating systems (e.g. FreeBSD), which is wrong. See for
335 # example this bug:
336 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
Victor Stinner0cd47902011-12-08 00:32:51 +0100337 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100338 self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000339 self.assertEqual(len(time.tzname), 2)
340 self.assertEqual(time.daylight, 1)
341 self.assertEqual(time.timezone, -36000)
342 self.assertEqual(time.altzone, -39600)
343 self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000344
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000345 finally:
346 # Repair TZ environment variable in case any other tests
347 # rely on it.
348 if org_TZ is not None:
349 environ['TZ'] = org_TZ
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000350 elif 'TZ' in environ:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000351 del environ['TZ']
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000352 time.tzset()
Tim Peters0eadaac2003-04-24 16:02:54 +0000353
Tim Peters1b6f7a92004-06-20 02:50:16 +0000354 def test_insane_timestamps(self):
355 # It's possible that some platform maps time_t to double,
356 # and that this test will fail there. This test should
357 # exempt such platforms (provided they return reasonable
358 # results!).
359 for func in time.ctime, time.gmtime, time.localtime:
360 for unreasonable in -1e200, 1e200:
Victor Stinner5d272cc2012-03-13 13:35:55 +0100361 self.assertRaises(OverflowError, func, unreasonable)
Fred Drakebc561982001-05-22 17:02:02 +0000362
Fred Drakef901abd2004-08-03 17:58:55 +0000363 def test_ctime_without_arg(self):
364 # Not sure how to check the values, since the clock could tick
365 # at any time. Make sure these are at least accepted and
366 # don't raise errors.
367 time.ctime()
368 time.ctime(None)
369
370 def test_gmtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000371 gt0 = time.gmtime()
372 gt1 = time.gmtime(None)
373 t0 = time.mktime(gt0)
374 t1 = time.mktime(gt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000375 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000376
377 def test_localtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000378 lt0 = time.localtime()
379 lt1 = time.localtime(None)
380 t0 = time.mktime(lt0)
381 t1 = time.mktime(lt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000382 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000383
Florent Xiclunae54371e2011-11-11 18:59:30 +0100384 def test_mktime(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100385 # Issue #1726687
386 for t in (-2, -1, 0, 1):
Victor Stinner8c8b4e02014-02-21 23:54:32 +0100387 if sys.platform.startswith('aix') and t == -1:
388 # Issue #11188, #19748: mktime() returns -1 on error. On Linux,
389 # the tm_wday field is used as a sentinel () to detect if -1 is
390 # really an error or a valid timestamp. On AIX, tm_wday is
391 # unchanged even on success and so cannot be used as a
392 # sentinel.
393 continue
Florent Xiclunabceb5282011-11-01 14:11:34 +0100394 try:
395 tt = time.localtime(t)
Victor Stinner2cbae982012-01-27 00:50:33 +0100396 except (OverflowError, OSError):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100397 pass
398 else:
399 self.assertEqual(time.mktime(tt), t)
Florent Xiclunae54371e2011-11-11 18:59:30 +0100400
401 # Issue #13309: passing extreme values to mktime() or localtime()
402 # borks the glibc's internal timezone data.
403 @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
404 "disabled because of a bug in glibc. Issue #13309")
405 def test_mktime_error(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100406 # It may not be possible to reliably make mktime return error
407 # on all platfom. This will make sure that no other exception
408 # than OverflowError is raised for an extreme value.
Florent Xiclunae54371e2011-11-11 18:59:30 +0100409 tt = time.gmtime(self.t)
410 tzname = time.strftime('%Z', tt)
411 self.assertNotEqual(tzname, 'LMT')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100412 try:
413 time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
414 except OverflowError:
415 pass
Florent Xiclunae54371e2011-11-11 18:59:30 +0100416 self.assertEqual(time.strftime('%Z', tt), tzname)
Florent Xiclunabceb5282011-11-01 14:11:34 +0100417
Victor Stinnerec895392012-04-29 02:41:27 +0200418 @unittest.skipUnless(hasattr(time, 'monotonic'),
419 'need time.monotonic')
420 def test_monotonic(self):
Victor Stinner6c861812013-11-23 00:15:27 +0100421 # monotonic() should not go backward
422 times = [time.monotonic() for n in range(100)]
423 t1 = times[0]
424 for t2 in times[1:]:
425 self.assertGreaterEqual(t2, t1, "times=%s" % times)
426 t1 = t2
427
428 # monotonic() includes time elapsed during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200429 t1 = time.monotonic()
Victor Stinnera9c99a62013-07-03 23:07:37 +0200430 time.sleep(0.5)
Victor Stinnerec895392012-04-29 02:41:27 +0200431 t2 = time.monotonic()
Victor Stinner2dd254d2012-01-20 02:24:18 +0100432 dt = t2 - t1
Victor Stinner8b302012012-02-07 23:29:46 +0100433 self.assertGreater(t2, t1)
Zachary Ware487aedb2014-01-02 09:41:10 -0600434 # Issue #20101: On some Windows machines, dt may be slightly low
435 self.assertTrue(0.45 <= dt <= 1.0, dt)
Antoine Pitrou391166f2012-01-18 22:35:21 +0100436
Victor Stinner6c861812013-11-23 00:15:27 +0100437 # monotonic() is a monotonic but non adjustable clock
Victor Stinnerec895392012-04-29 02:41:27 +0200438 info = time.get_clock_info('monotonic')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400439 self.assertTrue(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +0200440 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200441
442 def test_perf_counter(self):
443 time.perf_counter()
444
445 def test_process_time(self):
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200446 # process_time() should not include time spend during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200447 start = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200448 time.sleep(0.100)
Victor Stinnerec895392012-04-29 02:41:27 +0200449 stop = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200450 # use 20 ms because process_time() has usually a resolution of 15 ms
451 # on Windows
452 self.assertLess(stop - start, 0.020)
Victor Stinnerec895392012-04-29 02:41:27 +0200453
454 info = time.get_clock_info('process_time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400455 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200456 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200457
Victor Stinnerec895392012-04-29 02:41:27 +0200458 @unittest.skipUnless(hasattr(time, 'monotonic'),
459 'need time.monotonic')
460 @unittest.skipUnless(hasattr(time, 'clock_settime'),
461 'need time.clock_settime')
462 def test_monotonic_settime(self):
463 t1 = time.monotonic()
464 realtime = time.clock_gettime(time.CLOCK_REALTIME)
465 # jump backward with an offset of 1 hour
Victor Stinner071eca32012-03-15 01:17:09 +0100466 try:
Victor Stinnerec895392012-04-29 02:41:27 +0200467 time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
468 except PermissionError as err:
469 self.skipTest(err)
470 t2 = time.monotonic()
471 time.clock_settime(time.CLOCK_REALTIME, realtime)
472 # monotonic must not be affected by system clock updates
Victor Stinner071eca32012-03-15 01:17:09 +0100473 self.assertGreaterEqual(t2, t1)
474
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100475 def test_localtime_failure(self):
476 # Issue #13847: check for localtime() failure
Victor Stinner53d36452012-01-27 01:03:25 +0100477 invalid_time_t = None
478 for time_t in (-1, 2**30, 2**33, 2**60):
479 try:
480 time.localtime(time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100481 except OverflowError:
482 self.skipTest("need 64-bit time_t")
Victor Stinner53d36452012-01-27 01:03:25 +0100483 except OSError:
484 invalid_time_t = time_t
485 break
486 if invalid_time_t is None:
487 self.skipTest("unable to find an invalid time_t value")
488
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100489 self.assertRaises(OSError, time.localtime, invalid_time_t)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100490 self.assertRaises(OSError, time.ctime, invalid_time_t)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100491
Victor Stinnerec895392012-04-29 02:41:27 +0200492 def test_get_clock_info(self):
493 clocks = ['clock', 'perf_counter', 'process_time', 'time']
494 if hasattr(time, 'monotonic'):
495 clocks.append('monotonic')
496
497 for name in clocks:
498 info = time.get_clock_info(name)
499 #self.assertIsInstance(info, dict)
500 self.assertIsInstance(info.implementation, str)
501 self.assertNotEqual(info.implementation, '')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400502 self.assertIsInstance(info.monotonic, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200503 self.assertIsInstance(info.resolution, float)
504 # 0.0 < resolution <= 1.0
505 self.assertGreater(info.resolution, 0.0)
506 self.assertLessEqual(info.resolution, 1.0)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200507 self.assertIsInstance(info.adjustable, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200508
509 self.assertRaises(ValueError, time.get_clock_info, 'xxx')
510
511
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000512class TestLocale(unittest.TestCase):
513 def setUp(self):
514 self.oldloc = locale.setlocale(locale.LC_ALL)
Fred Drake2e2be372001-09-20 21:33:42 +0000515
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000516 def tearDown(self):
517 locale.setlocale(locale.LC_ALL, self.oldloc)
518
Martin v. Löwisa6a9c4d2009-05-30 06:15:30 +0000519 def test_bug_3061(self):
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000520 try:
521 tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
522 except locale.Error:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600523 self.skipTest('could not set locale.LC_ALL to fr_FR')
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000524 # This should not cause an exception
525 time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
526
Victor Stinner73ea29c2011-01-08 01:56:31 +0000527
Victor Stinner73ea29c2011-01-08 01:56:31 +0000528class _TestAsctimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100529 _format = '%d'
530
Victor Stinner73ea29c2011-01-08 01:56:31 +0000531 def yearstr(self, y):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000532 return time.asctime((y,) + (0,) * 8).split()[-1]
Alexander Belopolskya6867252011-01-05 23:00:47 +0000533
Victor Stinner73ea29c2011-01-08 01:56:31 +0000534 def test_large_year(self):
Victor Stinner73691322011-01-08 02:00:24 +0000535 # Check that it doesn't crash for year > 9999
Victor Stinner73ea29c2011-01-08 01:56:31 +0000536 self.assertEqual(self.yearstr(12345), '12345')
537 self.assertEqual(self.yearstr(123456789), '123456789')
538
539class _TestStrftimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100540
541 # Issue 13305: For years < 1000, the value is not always
542 # padded to 4 digits across platforms. The C standard
543 # assumes year >= 1900, so it does not specify the number
544 # of digits.
545
546 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
547 _format = '%04d'
548 else:
549 _format = '%d'
550
Victor Stinner73ea29c2011-01-08 01:56:31 +0000551 def yearstr(self, y):
Florent Xicluna49ce0682011-11-01 12:56:14 +0100552 return time.strftime('%Y', (y,) + (0,) * 8)
553
554 def test_4dyear(self):
555 # Check that we can return the zero padded value.
556 if self._format == '%04d':
557 self.test_year('%04d')
558 else:
559 def year4d(y):
560 return time.strftime('%4Y', (y,) + (0,) * 8)
561 self.test_year('%04d', func=year4d)
562
Florent Xiclunabceb5282011-11-01 14:11:34 +0100563 def skip_if_not_supported(y):
564 msg = "strftime() is limited to [1; 9999] with Visual Studio"
565 # Check that it doesn't crash for year > 9999
566 try:
567 time.strftime('%Y', (y,) + (0,) * 8)
568 except ValueError:
569 cond = False
570 else:
571 cond = True
572 return unittest.skipUnless(cond, msg)
573
574 @skip_if_not_supported(10000)
575 def test_large_year(self):
576 return super().test_large_year()
577
578 @skip_if_not_supported(0)
579 def test_negative(self):
580 return super().test_negative()
581
582 del skip_if_not_supported
583
584
Ezio Melotti3836d702013-04-11 20:29:42 +0300585class _Test4dYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100586 _format = '%d'
587
588 def test_year(self, fmt=None, func=None):
589 fmt = fmt or self._format
590 func = func or self.yearstr
591 self.assertEqual(func(1), fmt % 1)
592 self.assertEqual(func(68), fmt % 68)
593 self.assertEqual(func(69), fmt % 69)
594 self.assertEqual(func(99), fmt % 99)
595 self.assertEqual(func(999), fmt % 999)
596 self.assertEqual(func(9999), fmt % 9999)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000597
598 def test_large_year(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100599 self.assertEqual(self.yearstr(12345), '12345')
Victor Stinner13ed2ea2011-03-21 02:11:01 +0100600 self.assertEqual(self.yearstr(123456789), '123456789')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100601 self.assertEqual(self.yearstr(TIME_MAXYEAR), str(TIME_MAXYEAR))
602 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000603
Victor Stinner301f1212011-01-08 03:06:52 +0000604 def test_negative(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100605 self.assertEqual(self.yearstr(-1), self._format % -1)
Victor Stinner301f1212011-01-08 03:06:52 +0000606 self.assertEqual(self.yearstr(-1234), '-1234')
607 self.assertEqual(self.yearstr(-123456), '-123456')
Florent Xiclunad1bd7f72011-11-01 23:42:05 +0100608 self.assertEqual(self.yearstr(-123456789), str(-123456789))
609 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
Florent Xicluna2fbc1852011-11-02 08:13:43 +0100610 self.assertEqual(self.yearstr(TIME_MINYEAR + 1900), str(TIME_MINYEAR + 1900))
611 # Issue #13312: it may return wrong value for year < TIME_MINYEAR + 1900
612 # Skip the value test, but check that no error is raised
613 self.yearstr(TIME_MINYEAR)
Florent Xiclunae2a732e2011-11-02 01:28:17 +0100614 # self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
Florent Xiclunabceb5282011-11-01 14:11:34 +0100615 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
Victor Stinner301f1212011-01-08 03:06:52 +0000616
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000617
Ezio Melotti3836d702013-04-11 20:29:42 +0300618class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner73ea29c2011-01-08 01:56:31 +0000619 pass
620
Ezio Melotti3836d702013-04-11 20:29:42 +0300621class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner301f1212011-01-08 03:06:52 +0000622 pass
Victor Stinner73ea29c2011-01-08 01:56:31 +0000623
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000624
Victor Stinner643cd682012-03-02 22:54:03 +0100625class TestPytime(unittest.TestCase):
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400626 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
627 def test_localtime_timezone(self):
Victor Stinner643cd682012-03-02 22:54:03 +0100628
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400629 # Get the localtime and examine it for the offset and zone.
630 lt = time.localtime()
631 self.assertTrue(hasattr(lt, "tm_gmtoff"))
632 self.assertTrue(hasattr(lt, "tm_zone"))
633
634 # See if the offset and zone are similar to the module
635 # attributes.
636 if lt.tm_gmtoff is None:
637 self.assertTrue(not hasattr(time, "timezone"))
638 else:
639 self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
640 if lt.tm_zone is None:
641 self.assertTrue(not hasattr(time, "tzname"))
642 else:
643 self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
644
645 # Try and make UNIX times from the localtime and a 9-tuple
646 # created from the localtime. Test to see that the times are
647 # the same.
648 t = time.mktime(lt); t9 = time.mktime(lt[:9])
649 self.assertEqual(t, t9)
650
651 # Make localtimes from the UNIX times and compare them to
652 # the original localtime, thus making a round trip.
653 new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
654 self.assertEqual(new_lt, lt)
655 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
656 self.assertEqual(new_lt.tm_zone, lt.tm_zone)
657 self.assertEqual(new_lt9, lt)
658 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
659 self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
660
661 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
662 def test_strptime_timezone(self):
663 t = time.strptime("UTC", "%Z")
664 self.assertEqual(t.tm_zone, 'UTC')
665 t = time.strptime("+0500", "%z")
666 self.assertEqual(t.tm_gmtoff, 5 * 3600)
667
668 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
669 def test_short_times(self):
670
671 import pickle
672
673 # Load a short time structure using pickle.
674 st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
675 lt = pickle.loads(st)
676 self.assertIs(lt.tm_gmtoff, None)
677 self.assertIs(lt.tm_zone, None)
Victor Stinner643cd682012-03-02 22:54:03 +0100678
Fred Drake2e2be372001-09-20 21:33:42 +0000679
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200680@unittest.skipIf(_testcapi is None, 'need the _testcapi module')
681class CPyTimeTestCase:
Victor Stinneracea9f62015-09-02 10:39:40 +0200682 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200683 Base class to test the C _PyTime_t API.
Victor Stinneracea9f62015-09-02 10:39:40 +0200684 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200685 OVERFLOW_SECONDS = None
686
Victor Stinner4237d342015-09-10 10:10:39 +0200687 def setUp(self):
688 from _testcapi import SIZEOF_TIME_T
689 bits = SIZEOF_TIME_T * 8 - 1
690 self.time_t_min = -2 ** bits
691 self.time_t_max = 2 ** bits - 1
692
693 def time_t_filter(self, seconds):
694 return (self.time_t_min <= seconds <= self.time_t_max)
695
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200696 def _rounding_values(self, use_float):
697 "Build timestamps used to test rounding."
698
699 units = [1, US_TO_NS, MS_TO_NS, SEC_TO_NS]
700 if use_float:
701 # picoseconds are only tested to pytime_converter accepting floats
702 units.append(1e-3)
703
704 values = (
705 # small values
706 1, 2, 5, 7, 123, 456, 1234,
707 # 10^k - 1
708 9,
709 99,
710 999,
711 9999,
712 99999,
713 999999,
714 # test half even rounding near 0.5, 1.5, 2.5, 3.5, 4.5
715 499, 500, 501,
716 1499, 1500, 1501,
717 2500,
718 3500,
719 4500,
720 )
721
722 ns_timestamps = [0]
723 for unit in units:
724 for value in values:
725 ns = value * unit
726 ns_timestamps.extend((-ns, ns))
727 for pow2 in (0, 5, 10, 15, 22, 23, 24, 30, 33):
728 ns = (2 ** pow2) * SEC_TO_NS
729 ns_timestamps.extend((
730 -ns-1, -ns, -ns+1,
731 ns-1, ns, ns+1
732 ))
733 for seconds in (_testcapi.INT_MIN, _testcapi.INT_MAX):
734 ns_timestamps.append(seconds * SEC_TO_NS)
735 if use_float:
Victor Stinner717a32b2016-08-17 11:07:21 +0200736 # numbers with an exact representation in IEEE 754 (base 2)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200737 for pow2 in (3, 7, 10, 15):
738 ns = 2.0 ** (-pow2)
739 ns_timestamps.extend((-ns, ns))
740
741 # seconds close to _PyTime_t type limit
742 ns = (2 ** 63 // SEC_TO_NS) * SEC_TO_NS
743 ns_timestamps.extend((-ns, ns))
744
745 return ns_timestamps
746
747 def _check_rounding(self, pytime_converter, expected_func,
748 use_float, unit_to_sec, value_filter=None):
749
750 def convert_values(ns_timestamps):
751 if use_float:
752 unit_to_ns = SEC_TO_NS / float(unit_to_sec)
753 values = [ns / unit_to_ns for ns in ns_timestamps]
754 else:
755 unit_to_ns = SEC_TO_NS // unit_to_sec
756 values = [ns // unit_to_ns for ns in ns_timestamps]
757
758 if value_filter:
759 values = filter(value_filter, values)
760
761 # remove duplicates and sort
762 return sorted(set(values))
763
764 # test rounding
765 ns_timestamps = self._rounding_values(use_float)
766 valid_values = convert_values(ns_timestamps)
767 for time_rnd, decimal_rnd in ROUNDING_MODES :
768 context = decimal.getcontext()
769 context.rounding = decimal_rnd
770
771 for value in valid_values:
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200772 debug_info = {'value': value, 'rounding': decimal_rnd}
773 try:
774 result = pytime_converter(value, time_rnd)
775 expected = expected_func(value)
776 except Exception as exc:
777 self.fail("Error on timestamp conversion: %s" % debug_info)
778 self.assertEqual(result,
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200779 expected,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200780 debug_info)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200781
782 # test overflow
783 ns = self.OVERFLOW_SECONDS * SEC_TO_NS
784 ns_timestamps = (-ns, ns)
785 overflow_values = convert_values(ns_timestamps)
786 for time_rnd, _ in ROUNDING_MODES :
787 for value in overflow_values:
Victor Stinnerc60542b2015-09-10 15:55:07 +0200788 debug_info = {'value': value, 'rounding': time_rnd}
789 with self.assertRaises(OverflowError, msg=debug_info):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200790 pytime_converter(value, time_rnd)
791
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200792 def check_int_rounding(self, pytime_converter, expected_func,
793 unit_to_sec=1, value_filter=None):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200794 self._check_rounding(pytime_converter, expected_func,
795 False, unit_to_sec, value_filter)
796
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200797 def check_float_rounding(self, pytime_converter, expected_func,
798 unit_to_sec=1, value_filter=None):
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200799 self._check_rounding(pytime_converter, expected_func,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200800 True, unit_to_sec, value_filter)
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200801
802 def decimal_round(self, x):
803 d = decimal.Decimal(x)
804 d = d.quantize(1)
805 return int(d)
806
807
808class TestCPyTime(CPyTimeTestCase, unittest.TestCase):
809 """
810 Test the C _PyTime_t API.
811 """
812 # _PyTime_t is a 64-bit signed integer
813 OVERFLOW_SECONDS = math.ceil((2**63 + 1) / SEC_TO_NS)
814
Victor Stinner13019fd2015-04-03 13:10:54 +0200815 def test_FromSeconds(self):
816 from _testcapi import PyTime_FromSeconds
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200817
818 # PyTime_FromSeconds() expects a C int, reject values out of range
819 def c_int_filter(secs):
820 return (_testcapi.INT_MIN <= secs <= _testcapi.INT_MAX)
821
822 self.check_int_rounding(lambda secs, rnd: PyTime_FromSeconds(secs),
823 lambda secs: secs * SEC_TO_NS,
824 value_filter=c_int_filter)
Victor Stinner13019fd2015-04-03 13:10:54 +0200825
Victor Stinner992c43f2015-03-27 17:12:45 +0100826 def test_FromSecondsObject(self):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100827 from _testcapi import PyTime_FromSecondsObject
Victor Stinner992c43f2015-03-27 17:12:45 +0100828
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200829 self.check_int_rounding(
830 PyTime_FromSecondsObject,
831 lambda secs: secs * SEC_TO_NS)
Victor Stinner992c43f2015-03-27 17:12:45 +0100832
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200833 self.check_float_rounding(
834 PyTime_FromSecondsObject,
835 lambda ns: self.decimal_round(ns * SEC_TO_NS))
Victor Stinner4bfb4602015-03-27 22:27:24 +0100836
837 def test_AsSecondsDouble(self):
838 from _testcapi import PyTime_AsSecondsDouble
839
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200840 def float_converter(ns):
841 if abs(ns) % SEC_TO_NS == 0:
842 return float(ns // SEC_TO_NS)
843 else:
844 return float(ns) / SEC_TO_NS
Victor Stinner4bfb4602015-03-27 22:27:24 +0100845
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200846 self.check_int_rounding(lambda ns, rnd: PyTime_AsSecondsDouble(ns),
847 float_converter,
848 NS_TO_SEC)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100849
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200850 def create_decimal_converter(self, denominator):
851 denom = decimal.Decimal(denominator)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100852
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200853 def converter(value):
854 d = decimal.Decimal(value) / denom
855 return self.decimal_round(d)
Victor Stinner4bfb4602015-03-27 22:27:24 +0100856
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200857 return converter
Victor Stinner4bfb4602015-03-27 22:27:24 +0100858
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200859 def test_AsTimeval(self):
Victor Stinner95e9cef2015-03-28 01:26:47 +0100860 from _testcapi import PyTime_AsTimeval
Victor Stinner95e9cef2015-03-28 01:26:47 +0100861
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200862 us_converter = self.create_decimal_converter(US_TO_NS)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100863
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200864 def timeval_converter(ns):
865 us = us_converter(ns)
866 return divmod(us, SEC_TO_US)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100867
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200868 if sys.platform == 'win32':
869 from _testcapi import LONG_MIN, LONG_MAX
870
871 # On Windows, timeval.tv_sec type is a C long
872 def seconds_filter(secs):
873 return LONG_MIN <= secs <= LONG_MAX
874 else:
Victor Stinner4237d342015-09-10 10:10:39 +0200875 seconds_filter = self.time_t_filter
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200876
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200877 self.check_int_rounding(PyTime_AsTimeval,
878 timeval_converter,
Victor Stinner9c72f9b2015-09-10 09:10:14 +0200879 NS_TO_SEC,
880 value_filter=seconds_filter)
Victor Stinner95e9cef2015-03-28 01:26:47 +0100881
Victor Stinner34dc0f42015-03-27 18:19:03 +0100882 @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec'),
883 'need _testcapi.PyTime_AsTimespec')
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200884 def test_AsTimespec(self):
Victor Stinner34dc0f42015-03-27 18:19:03 +0100885 from _testcapi import PyTime_AsTimespec
Victor Stinner34dc0f42015-03-27 18:19:03 +0100886
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200887 def timespec_converter(ns):
888 return divmod(ns, SEC_TO_NS)
Victor Stinner34dc0f42015-03-27 18:19:03 +0100889
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200890 self.check_int_rounding(lambda ns, rnd: PyTime_AsTimespec(ns),
891 timespec_converter,
Victor Stinner4237d342015-09-10 10:10:39 +0200892 NS_TO_SEC,
893 value_filter=self.time_t_filter)
Victor Stinner34dc0f42015-03-27 18:19:03 +0100894
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200895 def test_AsMilliseconds(self):
Victor Stinner62d1c702015-04-01 17:47:07 +0200896 from _testcapi import PyTime_AsMilliseconds
Victor Stinner62d1c702015-04-01 17:47:07 +0200897
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200898 self.check_int_rounding(PyTime_AsMilliseconds,
899 self.create_decimal_converter(MS_TO_NS),
900 NS_TO_SEC)
Victor Stinner62d1c702015-04-01 17:47:07 +0200901
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200902 def test_AsMicroseconds(self):
Victor Stinner62d1c702015-04-01 17:47:07 +0200903 from _testcapi import PyTime_AsMicroseconds
Victor Stinner62d1c702015-04-01 17:47:07 +0200904
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200905 self.check_int_rounding(PyTime_AsMicroseconds,
906 self.create_decimal_converter(US_TO_NS),
907 NS_TO_SEC)
Victor Stinner62d1c702015-04-01 17:47:07 +0200908
Victor Stinner992c43f2015-03-27 17:12:45 +0100909
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200910class TestOldPyTime(CPyTimeTestCase, unittest.TestCase):
Victor Stinneracea9f62015-09-02 10:39:40 +0200911 """
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200912 Test the old C _PyTime_t API: _PyTime_ObjectToXXX() functions.
Victor Stinneracea9f62015-09-02 10:39:40 +0200913 """
Victor Stinneracea9f62015-09-02 10:39:40 +0200914
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200915 # time_t is a 32-bit or 64-bit signed integer
916 OVERFLOW_SECONDS = 2 ** 64
917
918 def test_object_to_time_t(self):
Victor Stinneracea9f62015-09-02 10:39:40 +0200919 from _testcapi import pytime_object_to_time_t
920
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200921 self.check_int_rounding(pytime_object_to_time_t,
Victor Stinner4237d342015-09-10 10:10:39 +0200922 lambda secs: secs,
923 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200924
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200925 self.check_float_rounding(pytime_object_to_time_t,
Victor Stinner350b5182015-09-10 11:45:06 +0200926 self.decimal_round,
927 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200928
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200929 def create_converter(self, sec_to_unit):
930 def converter(secs):
931 floatpart, intpart = math.modf(secs)
932 intpart = int(intpart)
933 floatpart *= sec_to_unit
934 floatpart = self.decimal_round(floatpart)
935 if floatpart < 0:
936 floatpart += sec_to_unit
937 intpart -= 1
938 elif floatpart >= sec_to_unit:
939 floatpart -= sec_to_unit
940 intpart += 1
941 return (intpart, floatpart)
942 return converter
Victor Stinneracea9f62015-09-02 10:39:40 +0200943
Victor Stinneradfefa52015-09-04 23:57:25 +0200944 def test_object_to_timeval(self):
Victor Stinneracea9f62015-09-02 10:39:40 +0200945 from _testcapi import pytime_object_to_timeval
946
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200947 self.check_int_rounding(pytime_object_to_timeval,
Victor Stinner4237d342015-09-10 10:10:39 +0200948 lambda secs: (secs, 0),
949 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200950
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200951 self.check_float_rounding(pytime_object_to_timeval,
Victor Stinner350b5182015-09-10 11:45:06 +0200952 self.create_converter(SEC_TO_US),
953 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200954
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200955 def test_object_to_timespec(self):
Victor Stinneracea9f62015-09-02 10:39:40 +0200956 from _testcapi import pytime_object_to_timespec
957
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200958 self.check_int_rounding(pytime_object_to_timespec,
Victor Stinner4237d342015-09-10 10:10:39 +0200959 lambda secs: (secs, 0),
960 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200961
Victor Stinner3e2c8d82015-09-09 22:32:48 +0200962 self.check_float_rounding(pytime_object_to_timespec,
Victor Stinner350b5182015-09-10 11:45:06 +0200963 self.create_converter(SEC_TO_NS),
964 value_filter=self.time_t_filter)
Victor Stinneracea9f62015-09-02 10:39:40 +0200965
Victor Stinneracea9f62015-09-02 10:39:40 +0200966
Fred Drake2e2be372001-09-20 21:33:42 +0000967if __name__ == "__main__":
Ezio Melotti3836d702013-04-11 20:29:42 +0300968 unittest.main()