blob: de0cbc4020f614478cad3f3d5aeaa4d4232d1231 [file] [log] [blame]
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001from test import support
Victor Stinner992c43f2015-03-27 17:12:45 +01002import enum
3import locale
4import platform
5import sys
6import sysconfig
Barry Warsawb0c22321996-12-06 23:30:07 +00007import time
Fred Drakebc561982001-05-22 17:02:02 +00008import unittest
Victor Stinnerec895392012-04-29 02:41:27 +02009try:
10 import threading
11except ImportError:
12 threading = None
Victor Stinner34dc0f42015-03-27 18:19:03 +010013try:
14 import _testcapi
15except ImportError:
16 _testcapi = None
17
Barry Warsawb0c22321996-12-06 23:30:07 +000018
Florent Xiclunabceb5282011-11-01 14:11:34 +010019# Max year is only limited by the size of C int.
20SIZEOF_INT = sysconfig.get_config_var('SIZEOF_INT') or 4
21TIME_MAXYEAR = (1 << 8 * SIZEOF_INT - 1) - 1
22TIME_MINYEAR = -TIME_MAXYEAR - 1
Victor Stinner992c43f2015-03-27 17:12:45 +010023
Victor 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 Stinner992c43f2015-03-27 17:12:45 +010027
28class _PyTime(enum.IntEnum):
Victor Stinnerbcdd7772015-03-30 03:52:49 +020029 # Round towards minus infinity (-inf)
Victor Stinnera695f832015-03-30 03:57:14 +020030 ROUND_FLOOR = 0
Victor Stinnerbcdd7772015-03-30 03:52:49 +020031 # Round towards infinity (+inf)
Victor Stinnera695f832015-03-30 03:57:14 +020032 ROUND_CEILING = 1
Victor Stinner992c43f2015-03-27 17:12:45 +010033
Victor Stinnera695f832015-03-30 03:57:14 +020034ALL_ROUNDING_METHODS = (_PyTime.ROUND_FLOOR, _PyTime.ROUND_CEILING)
Florent Xiclunabceb5282011-11-01 14:11:34 +010035
36
Fred Drakebc561982001-05-22 17:02:02 +000037class TimeTestCase(unittest.TestCase):
Barry Warsawb0c22321996-12-06 23:30:07 +000038
Fred Drakebc561982001-05-22 17:02:02 +000039 def setUp(self):
40 self.t = time.time()
Barry Warsawb0c22321996-12-06 23:30:07 +000041
Fred Drakebc561982001-05-22 17:02:02 +000042 def test_data_attributes(self):
43 time.altzone
44 time.daylight
45 time.timezone
46 time.tzname
Barry Warsawb0c22321996-12-06 23:30:07 +000047
Victor Stinnerec895392012-04-29 02:41:27 +020048 def test_time(self):
49 time.time()
50 info = time.get_clock_info('time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040051 self.assertFalse(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +020052 self.assertTrue(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020053
Fred Drakebc561982001-05-22 17:02:02 +000054 def test_clock(self):
55 time.clock()
Barry Warsawb0c22321996-12-06 23:30:07 +000056
Victor Stinnerec895392012-04-29 02:41:27 +020057 info = time.get_clock_info('clock')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040058 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +020059 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020060
Victor Stinnere0be4232011-10-25 13:06:09 +020061 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
62 'need time.clock_gettime()')
63 def test_clock_realtime(self):
64 time.clock_gettime(time.CLOCK_REALTIME)
65
66 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
67 'need time.clock_gettime()')
68 @unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'),
69 'need time.CLOCK_MONOTONIC')
70 def test_clock_monotonic(self):
71 a = time.clock_gettime(time.CLOCK_MONOTONIC)
72 b = time.clock_gettime(time.CLOCK_MONOTONIC)
73 self.assertLessEqual(a, b)
74
75 @unittest.skipUnless(hasattr(time, 'clock_getres'),
76 'need time.clock_getres()')
77 def test_clock_getres(self):
78 res = time.clock_getres(time.CLOCK_REALTIME)
79 self.assertGreater(res, 0.0)
80 self.assertLessEqual(res, 1.0)
81
Victor Stinner30d79472012-04-03 00:45:07 +020082 @unittest.skipUnless(hasattr(time, 'clock_settime'),
83 'need time.clock_settime()')
84 def test_clock_settime(self):
85 t = time.clock_gettime(time.CLOCK_REALTIME)
86 try:
87 time.clock_settime(time.CLOCK_REALTIME, t)
88 except PermissionError:
89 pass
90
Victor Stinnerec895392012-04-29 02:41:27 +020091 if hasattr(time, 'CLOCK_MONOTONIC'):
92 self.assertRaises(OSError,
93 time.clock_settime, time.CLOCK_MONOTONIC, 0)
Victor Stinner30d79472012-04-03 00:45:07 +020094
Fred Drakebc561982001-05-22 17:02:02 +000095 def test_conversions(self):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +000096 self.assertEqual(time.ctime(self.t),
97 time.asctime(time.localtime(self.t)))
98 self.assertEqual(int(time.mktime(time.localtime(self.t))),
99 int(self.t))
Fred Drakebc561982001-05-22 17:02:02 +0000100
101 def test_sleep(self):
Victor Stinner7f53a502011-07-05 22:00:25 +0200102 self.assertRaises(ValueError, time.sleep, -2)
103 self.assertRaises(ValueError, time.sleep, -1)
Fred Drakebc561982001-05-22 17:02:02 +0000104 time.sleep(1.2)
105
106 def test_strftime(self):
107 tt = time.gmtime(self.t)
108 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
109 'j', 'm', 'M', 'p', 'S',
110 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
111 format = ' %' + directive
112 try:
113 time.strftime(format, tt)
114 except ValueError:
115 self.fail('conversion specifier: %r failed.' % format)
116
Florent Xicluna49ce0682011-11-01 12:56:14 +0100117 def _bounds_checking(self, func):
Brett Cannond1080a32004-03-02 04:38:10 +0000118 # Make sure that strftime() checks the bounds of the various parts
Florent Xicluna49ce0682011-11-01 12:56:14 +0100119 # of the time tuple (0 is valid for *all* values).
Brett Cannond1080a32004-03-02 04:38:10 +0000120
Victor Stinner73ea29c2011-01-08 01:56:31 +0000121 # The year field is tested by other test cases above
122
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000123 # Check month [1, 12] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100124 func((1900, 0, 1, 0, 0, 0, 0, 1, -1))
125 func((1900, 12, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000126 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000127 (1900, -1, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000128 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000129 (1900, 13, 1, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000130 # Check day of month [1, 31] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100131 func((1900, 1, 0, 0, 0, 0, 0, 1, -1))
132 func((1900, 1, 31, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000133 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000134 (1900, 1, -1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000135 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000136 (1900, 1, 32, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000137 # Check hour [0, 23]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100138 func((1900, 1, 1, 23, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000139 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000140 (1900, 1, 1, -1, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000141 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000142 (1900, 1, 1, 24, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000143 # Check minute [0, 59]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100144 func((1900, 1, 1, 0, 59, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000145 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000146 (1900, 1, 1, 0, -1, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000147 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000148 (1900, 1, 1, 0, 60, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000149 # Check second [0, 61]
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000150 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000151 (1900, 1, 1, 0, 0, -1, 0, 1, -1))
152 # C99 only requires allowing for one leap second, but Python's docs say
153 # allow two leap seconds (0..61)
Florent Xicluna49ce0682011-11-01 12:56:14 +0100154 func((1900, 1, 1, 0, 0, 60, 0, 1, -1))
155 func((1900, 1, 1, 0, 0, 61, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000156 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000157 (1900, 1, 1, 0, 0, 62, 0, 1, -1))
158 # No check for upper-bound day of week;
159 # value forced into range by a ``% 7`` calculation.
160 # Start check at -2 since gettmarg() increments value before taking
161 # modulo.
Florent Xicluna49ce0682011-11-01 12:56:14 +0100162 self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)),
163 func((1900, 1, 1, 0, 0, 0, +6, 1, -1)))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000164 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000165 (1900, 1, 1, 0, 0, 0, -2, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000166 # Check day of the year [1, 366] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100167 func((1900, 1, 1, 0, 0, 0, 0, 0, -1))
168 func((1900, 1, 1, 0, 0, 0, 0, 366, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000169 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000170 (1900, 1, 1, 0, 0, 0, 0, -1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000171 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000172 (1900, 1, 1, 0, 0, 0, 0, 367, -1))
Brett Cannond1080a32004-03-02 04:38:10 +0000173
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000174 def test_strftime_bounding_check(self):
175 self._bounds_checking(lambda tup: time.strftime('', tup))
176
Steve Dowere5b58952015-09-06 19:20:51 -0700177 def test_strftime_format_check(self):
178 # Test that strftime does not crash on invalid format strings
179 # that may trigger a buffer overread. When not triggered,
180 # strftime may succeed or raise ValueError depending on
181 # the platform.
182 for x in [ '', 'A', '%A', '%AA' ]:
183 for y in range(0x0, 0x10):
184 for z in [ '%', 'A%', 'AA%', '%A%', 'A%A%', '%#' ]:
185 try:
186 time.strftime(x * y + z)
187 except ValueError:
188 pass
189
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000190 def test_default_values_for_zero(self):
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400191 # Make sure that using all zeros uses the proper default
192 # values. No test for daylight savings since strftime() does
193 # not change output based on its value and no test for year
194 # because systems vary in their support for year 0.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000195 expected = "2000 01 01 00 00 00 1 001"
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000196 with support.check_warnings():
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400197 result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000198 self.assertEqual(expected, result)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000199
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000200 def test_strptime(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000201 # Should be able to go round-trip from strftime to strptime without
Andrew Svetlov737fb892012-12-18 21:14:22 +0200202 # raising an exception.
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000203 tt = time.gmtime(self.t)
204 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
205 'j', 'm', 'M', 'p', 'S',
206 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000207 format = '%' + directive
208 strf_output = time.strftime(format, tt)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000209 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000210 time.strptime(strf_output, format)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000211 except ValueError:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000212 self.fail("conversion specifier %r failed with '%s' input." %
213 (format, strf_output))
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000214
Brett Cannon7f6b4f82009-03-30 21:30:26 +0000215 def test_strptime_bytes(self):
216 # Make sure only strings are accepted as arguments to strptime.
217 self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
218 self.assertRaises(TypeError, time.strptime, '2009', b'%Y')
219
Ezio Melotti0f389082013-04-04 02:09:20 +0300220 def test_strptime_exception_context(self):
221 # check that this doesn't chain exceptions needlessly (see #17572)
222 with self.assertRaises(ValueError) as e:
223 time.strptime('', '%D')
224 self.assertIs(e.exception.__suppress_context__, True)
Serhiy Storchakacdac3022013-11-24 18:15:37 +0200225 # additional check for IndexError branch (issue #19545)
226 with self.assertRaises(ValueError) as e:
227 time.strptime('19', '%Y %')
228 self.assertIs(e.exception.__suppress_context__, True)
Ezio Melotti0f389082013-04-04 02:09:20 +0300229
Fred Drakebc561982001-05-22 17:02:02 +0000230 def test_asctime(self):
231 time.asctime(time.gmtime(self.t))
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000232
233 # Max year is only limited by the size of C int.
Florent Xiclunabceb5282011-11-01 14:11:34 +0100234 for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
235 asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
236 self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
237 self.assertRaises(OverflowError, time.asctime,
238 (TIME_MAXYEAR + 1,) + (0,) * 8)
239 self.assertRaises(OverflowError, time.asctime,
240 (TIME_MINYEAR - 1,) + (0,) * 8)
Fred Drakebc561982001-05-22 17:02:02 +0000241 self.assertRaises(TypeError, time.asctime, 0)
Alexander Belopolskye2dc0822011-01-02 20:48:22 +0000242 self.assertRaises(TypeError, time.asctime, ())
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000243 self.assertRaises(TypeError, time.asctime, (0,) * 10)
Fred Drakebc561982001-05-22 17:02:02 +0000244
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000245 def test_asctime_bounding_check(self):
246 self._bounds_checking(time.asctime)
247
Georg Brandle10608c2011-01-02 22:33:43 +0000248 def test_ctime(self):
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000249 t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
250 self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
251 t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
252 self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000')
Victor Stinner1ac42612014-02-21 09:27:17 +0100253 for year in [-100, 100, 1000, 2000, 2050, 10000]:
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000254 try:
255 testval = time.mktime((year, 1, 10) + (0,)*6)
256 except (ValueError, OverflowError):
257 # If mktime fails, ctime will fail too. This may happen
258 # on some platforms.
259 pass
260 else:
261 self.assertEqual(time.ctime(testval)[20:], str(year))
Georg Brandle10608c2011-01-02 22:33:43 +0000262
Florent Xiclunae54371e2011-11-11 18:59:30 +0100263 @unittest.skipUnless(hasattr(time, "tzset"),
264 "time module has no attribute tzset")
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000265 def test_tzset(self):
Guido van Rossumd2b738e2003-03-15 12:01:52 +0000266
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000267 from os import environ
268
Tim Peters0eadaac2003-04-24 16:02:54 +0000269 # Epoch time of midnight Dec 25th 2002. Never DST in northern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000270 # hemisphere.
Tim Peters0eadaac2003-04-24 16:02:54 +0000271 xmas2002 = 1040774400.0
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000272
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000273 # These formats are correct for 2002, and possibly future years
274 # This format is the 'standard' as documented at:
275 # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
276 # They are also documented in the tzset(3) man page on most Unix
277 # systems.
Tim Peters0eadaac2003-04-24 16:02:54 +0000278 eastern = 'EST+05EDT,M4.1.0,M10.5.0'
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000279 victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
280 utc='UTC+0'
281
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000282 org_TZ = environ.get('TZ',None)
283 try:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000284 # Make sure we can switch to UTC time and results are correct
285 # Note that unknown timezones default to UTC.
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000286 # Note that altzone is undefined in UTC, as there is no DST
287 environ['TZ'] = eastern
288 time.tzset()
289 environ['TZ'] = utc
290 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000291 self.assertEqual(
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000292 time.gmtime(xmas2002), time.localtime(xmas2002)
293 )
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000294 self.assertEqual(time.daylight, 0)
295 self.assertEqual(time.timezone, 0)
296 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000297
298 # Make sure we can switch to US/Eastern
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000299 environ['TZ'] = eastern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000300 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000301 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
302 self.assertEqual(time.tzname, ('EST', 'EDT'))
303 self.assertEqual(len(time.tzname), 2)
304 self.assertEqual(time.daylight, 1)
305 self.assertEqual(time.timezone, 18000)
306 self.assertEqual(time.altzone, 14400)
307 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
308 self.assertEqual(len(time.tzname), 2)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000309
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000310 # Now go to the southern hemisphere.
311 environ['TZ'] = victoria
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000312 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000313 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
Victor Stinner0cd47902011-12-08 00:32:51 +0100314
315 # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100316 # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
317 # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
318 # on some operating systems (e.g. FreeBSD), which is wrong. See for
319 # example this bug:
320 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
Victor Stinner0cd47902011-12-08 00:32:51 +0100321 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100322 self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000323 self.assertEqual(len(time.tzname), 2)
324 self.assertEqual(time.daylight, 1)
325 self.assertEqual(time.timezone, -36000)
326 self.assertEqual(time.altzone, -39600)
327 self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000328
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000329 finally:
330 # Repair TZ environment variable in case any other tests
331 # rely on it.
332 if org_TZ is not None:
333 environ['TZ'] = org_TZ
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000334 elif 'TZ' in environ:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000335 del environ['TZ']
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000336 time.tzset()
Tim Peters0eadaac2003-04-24 16:02:54 +0000337
Tim Peters1b6f7a92004-06-20 02:50:16 +0000338 def test_insane_timestamps(self):
339 # It's possible that some platform maps time_t to double,
340 # and that this test will fail there. This test should
341 # exempt such platforms (provided they return reasonable
342 # results!).
343 for func in time.ctime, time.gmtime, time.localtime:
344 for unreasonable in -1e200, 1e200:
Victor Stinner5d272cc2012-03-13 13:35:55 +0100345 self.assertRaises(OverflowError, func, unreasonable)
Fred Drakebc561982001-05-22 17:02:02 +0000346
Fred Drakef901abd2004-08-03 17:58:55 +0000347 def test_ctime_without_arg(self):
348 # Not sure how to check the values, since the clock could tick
349 # at any time. Make sure these are at least accepted and
350 # don't raise errors.
351 time.ctime()
352 time.ctime(None)
353
354 def test_gmtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000355 gt0 = time.gmtime()
356 gt1 = time.gmtime(None)
357 t0 = time.mktime(gt0)
358 t1 = time.mktime(gt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000359 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000360
361 def test_localtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000362 lt0 = time.localtime()
363 lt1 = time.localtime(None)
364 t0 = time.mktime(lt0)
365 t1 = time.mktime(lt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000366 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000367
Florent Xiclunae54371e2011-11-11 18:59:30 +0100368 def test_mktime(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100369 # Issue #1726687
370 for t in (-2, -1, 0, 1):
Victor Stinner8c8b4e02014-02-21 23:54:32 +0100371 if sys.platform.startswith('aix') and t == -1:
372 # Issue #11188, #19748: mktime() returns -1 on error. On Linux,
373 # the tm_wday field is used as a sentinel () to detect if -1 is
374 # really an error or a valid timestamp. On AIX, tm_wday is
375 # unchanged even on success and so cannot be used as a
376 # sentinel.
377 continue
Florent Xiclunabceb5282011-11-01 14:11:34 +0100378 try:
379 tt = time.localtime(t)
Victor Stinner2cbae982012-01-27 00:50:33 +0100380 except (OverflowError, OSError):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100381 pass
382 else:
383 self.assertEqual(time.mktime(tt), t)
Florent Xiclunae54371e2011-11-11 18:59:30 +0100384
385 # Issue #13309: passing extreme values to mktime() or localtime()
386 # borks the glibc's internal timezone data.
387 @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
388 "disabled because of a bug in glibc. Issue #13309")
389 def test_mktime_error(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100390 # It may not be possible to reliably make mktime return error
391 # on all platfom. This will make sure that no other exception
392 # than OverflowError is raised for an extreme value.
Florent Xiclunae54371e2011-11-11 18:59:30 +0100393 tt = time.gmtime(self.t)
394 tzname = time.strftime('%Z', tt)
395 self.assertNotEqual(tzname, 'LMT')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100396 try:
397 time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
398 except OverflowError:
399 pass
Florent Xiclunae54371e2011-11-11 18:59:30 +0100400 self.assertEqual(time.strftime('%Z', tt), tzname)
Florent Xiclunabceb5282011-11-01 14:11:34 +0100401
Victor Stinnerec895392012-04-29 02:41:27 +0200402 @unittest.skipUnless(hasattr(time, 'monotonic'),
403 'need time.monotonic')
404 def test_monotonic(self):
Victor Stinner6c861812013-11-23 00:15:27 +0100405 # monotonic() should not go backward
406 times = [time.monotonic() for n in range(100)]
407 t1 = times[0]
408 for t2 in times[1:]:
409 self.assertGreaterEqual(t2, t1, "times=%s" % times)
410 t1 = t2
411
412 # monotonic() includes time elapsed during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200413 t1 = time.monotonic()
Victor Stinnera9c99a62013-07-03 23:07:37 +0200414 time.sleep(0.5)
Victor Stinnerec895392012-04-29 02:41:27 +0200415 t2 = time.monotonic()
Victor Stinner2dd254d2012-01-20 02:24:18 +0100416 dt = t2 - t1
Victor Stinner8b302012012-02-07 23:29:46 +0100417 self.assertGreater(t2, t1)
Zachary Ware487aedb2014-01-02 09:41:10 -0600418 # Issue #20101: On some Windows machines, dt may be slightly low
419 self.assertTrue(0.45 <= dt <= 1.0, dt)
Antoine Pitrou391166f2012-01-18 22:35:21 +0100420
Victor Stinner6c861812013-11-23 00:15:27 +0100421 # monotonic() is a monotonic but non adjustable clock
Victor Stinnerec895392012-04-29 02:41:27 +0200422 info = time.get_clock_info('monotonic')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400423 self.assertTrue(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +0200424 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200425
426 def test_perf_counter(self):
427 time.perf_counter()
428
429 def test_process_time(self):
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200430 # process_time() should not include time spend during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200431 start = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200432 time.sleep(0.100)
Victor Stinnerec895392012-04-29 02:41:27 +0200433 stop = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200434 # use 20 ms because process_time() has usually a resolution of 15 ms
435 # on Windows
436 self.assertLess(stop - start, 0.020)
Victor Stinnerec895392012-04-29 02:41:27 +0200437
438 info = time.get_clock_info('process_time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400439 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200440 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200441
Victor Stinnerec895392012-04-29 02:41:27 +0200442 @unittest.skipUnless(hasattr(time, 'monotonic'),
443 'need time.monotonic')
444 @unittest.skipUnless(hasattr(time, 'clock_settime'),
445 'need time.clock_settime')
446 def test_monotonic_settime(self):
447 t1 = time.monotonic()
448 realtime = time.clock_gettime(time.CLOCK_REALTIME)
449 # jump backward with an offset of 1 hour
Victor Stinner071eca32012-03-15 01:17:09 +0100450 try:
Victor Stinnerec895392012-04-29 02:41:27 +0200451 time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
452 except PermissionError as err:
453 self.skipTest(err)
454 t2 = time.monotonic()
455 time.clock_settime(time.CLOCK_REALTIME, realtime)
456 # monotonic must not be affected by system clock updates
Victor Stinner071eca32012-03-15 01:17:09 +0100457 self.assertGreaterEqual(t2, t1)
458
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100459 def test_localtime_failure(self):
460 # Issue #13847: check for localtime() failure
Victor Stinner53d36452012-01-27 01:03:25 +0100461 invalid_time_t = None
462 for time_t in (-1, 2**30, 2**33, 2**60):
463 try:
464 time.localtime(time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100465 except OverflowError:
466 self.skipTest("need 64-bit time_t")
Victor Stinner53d36452012-01-27 01:03:25 +0100467 except OSError:
468 invalid_time_t = time_t
469 break
470 if invalid_time_t is None:
471 self.skipTest("unable to find an invalid time_t value")
472
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100473 self.assertRaises(OSError, time.localtime, invalid_time_t)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100474 self.assertRaises(OSError, time.ctime, invalid_time_t)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100475
Victor Stinnerec895392012-04-29 02:41:27 +0200476 def test_get_clock_info(self):
477 clocks = ['clock', 'perf_counter', 'process_time', 'time']
478 if hasattr(time, 'monotonic'):
479 clocks.append('monotonic')
480
481 for name in clocks:
482 info = time.get_clock_info(name)
483 #self.assertIsInstance(info, dict)
484 self.assertIsInstance(info.implementation, str)
485 self.assertNotEqual(info.implementation, '')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400486 self.assertIsInstance(info.monotonic, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200487 self.assertIsInstance(info.resolution, float)
488 # 0.0 < resolution <= 1.0
489 self.assertGreater(info.resolution, 0.0)
490 self.assertLessEqual(info.resolution, 1.0)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200491 self.assertIsInstance(info.adjustable, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200492
493 self.assertRaises(ValueError, time.get_clock_info, 'xxx')
494
495
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000496class TestLocale(unittest.TestCase):
497 def setUp(self):
498 self.oldloc = locale.setlocale(locale.LC_ALL)
Fred Drake2e2be372001-09-20 21:33:42 +0000499
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000500 def tearDown(self):
501 locale.setlocale(locale.LC_ALL, self.oldloc)
502
Martin v. Löwisa6a9c4d2009-05-30 06:15:30 +0000503 def test_bug_3061(self):
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000504 try:
505 tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
506 except locale.Error:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600507 self.skipTest('could not set locale.LC_ALL to fr_FR')
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000508 # This should not cause an exception
509 time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
510
Victor Stinner73ea29c2011-01-08 01:56:31 +0000511
Victor Stinner73ea29c2011-01-08 01:56:31 +0000512class _TestAsctimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100513 _format = '%d'
514
Victor Stinner73ea29c2011-01-08 01:56:31 +0000515 def yearstr(self, y):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000516 return time.asctime((y,) + (0,) * 8).split()[-1]
Alexander Belopolskya6867252011-01-05 23:00:47 +0000517
Victor Stinner73ea29c2011-01-08 01:56:31 +0000518 def test_large_year(self):
Victor Stinner73691322011-01-08 02:00:24 +0000519 # Check that it doesn't crash for year > 9999
Victor Stinner73ea29c2011-01-08 01:56:31 +0000520 self.assertEqual(self.yearstr(12345), '12345')
521 self.assertEqual(self.yearstr(123456789), '123456789')
522
523class _TestStrftimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100524
525 # Issue 13305: For years < 1000, the value is not always
526 # padded to 4 digits across platforms. The C standard
527 # assumes year >= 1900, so it does not specify the number
528 # of digits.
529
530 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
531 _format = '%04d'
532 else:
533 _format = '%d'
534
Victor Stinner73ea29c2011-01-08 01:56:31 +0000535 def yearstr(self, y):
Florent Xicluna49ce0682011-11-01 12:56:14 +0100536 return time.strftime('%Y', (y,) + (0,) * 8)
537
538 def test_4dyear(self):
539 # Check that we can return the zero padded value.
540 if self._format == '%04d':
541 self.test_year('%04d')
542 else:
543 def year4d(y):
544 return time.strftime('%4Y', (y,) + (0,) * 8)
545 self.test_year('%04d', func=year4d)
546
Florent Xiclunabceb5282011-11-01 14:11:34 +0100547 def skip_if_not_supported(y):
548 msg = "strftime() is limited to [1; 9999] with Visual Studio"
549 # Check that it doesn't crash for year > 9999
550 try:
551 time.strftime('%Y', (y,) + (0,) * 8)
552 except ValueError:
553 cond = False
554 else:
555 cond = True
556 return unittest.skipUnless(cond, msg)
557
558 @skip_if_not_supported(10000)
559 def test_large_year(self):
560 return super().test_large_year()
561
562 @skip_if_not_supported(0)
563 def test_negative(self):
564 return super().test_negative()
565
566 del skip_if_not_supported
567
568
Ezio Melotti3836d702013-04-11 20:29:42 +0300569class _Test4dYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100570 _format = '%d'
571
572 def test_year(self, fmt=None, func=None):
573 fmt = fmt or self._format
574 func = func or self.yearstr
575 self.assertEqual(func(1), fmt % 1)
576 self.assertEqual(func(68), fmt % 68)
577 self.assertEqual(func(69), fmt % 69)
578 self.assertEqual(func(99), fmt % 99)
579 self.assertEqual(func(999), fmt % 999)
580 self.assertEqual(func(9999), fmt % 9999)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000581
582 def test_large_year(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100583 self.assertEqual(self.yearstr(12345), '12345')
Victor Stinner13ed2ea2011-03-21 02:11:01 +0100584 self.assertEqual(self.yearstr(123456789), '123456789')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100585 self.assertEqual(self.yearstr(TIME_MAXYEAR), str(TIME_MAXYEAR))
586 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000587
Victor Stinner301f1212011-01-08 03:06:52 +0000588 def test_negative(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100589 self.assertEqual(self.yearstr(-1), self._format % -1)
Victor Stinner301f1212011-01-08 03:06:52 +0000590 self.assertEqual(self.yearstr(-1234), '-1234')
591 self.assertEqual(self.yearstr(-123456), '-123456')
Florent Xiclunad1bd7f72011-11-01 23:42:05 +0100592 self.assertEqual(self.yearstr(-123456789), str(-123456789))
593 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
Florent Xicluna2fbc1852011-11-02 08:13:43 +0100594 self.assertEqual(self.yearstr(TIME_MINYEAR + 1900), str(TIME_MINYEAR + 1900))
595 # Issue #13312: it may return wrong value for year < TIME_MINYEAR + 1900
596 # Skip the value test, but check that no error is raised
597 self.yearstr(TIME_MINYEAR)
Florent Xiclunae2a732e2011-11-02 01:28:17 +0100598 # self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
Florent Xiclunabceb5282011-11-01 14:11:34 +0100599 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
Victor Stinner301f1212011-01-08 03:06:52 +0000600
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000601
Ezio Melotti3836d702013-04-11 20:29:42 +0300602class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner73ea29c2011-01-08 01:56:31 +0000603 pass
604
Ezio Melotti3836d702013-04-11 20:29:42 +0300605class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner301f1212011-01-08 03:06:52 +0000606 pass
Victor Stinner73ea29c2011-01-08 01:56:31 +0000607
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000608
Victor Stinner643cd682012-03-02 22:54:03 +0100609class TestPytime(unittest.TestCase):
Victor Stinner5d272cc2012-03-13 13:35:55 +0100610 def setUp(self):
611 self.invalid_values = (
612 -(2 ** 100), 2 ** 100,
613 -(2.0 ** 100.0), 2.0 ** 100.0,
614 )
615
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200616 @support.cpython_only
Victor Stinner5d272cc2012-03-13 13:35:55 +0100617 def test_time_t(self):
618 from _testcapi import pytime_object_to_time_t
Victor Stinner3c1b3792014-02-17 00:02:43 +0100619 for obj, time_t, rnd in (
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200620 # Round towards minus infinity (-inf)
621 (0, 0, _PyTime.ROUND_FLOOR),
622 (-1, -1, _PyTime.ROUND_FLOOR),
623 (-1.0, -1, _PyTime.ROUND_FLOOR),
624 (-1.9, -2, _PyTime.ROUND_FLOOR),
625 (1.0, 1, _PyTime.ROUND_FLOOR),
626 (1.9, 1, _PyTime.ROUND_FLOOR),
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200627 # Round towards infinity (+inf)
628 (0, 0, _PyTime.ROUND_CEILING),
629 (-1, -1, _PyTime.ROUND_CEILING),
630 (-1.0, -1, _PyTime.ROUND_CEILING),
631 (-1.9, -1, _PyTime.ROUND_CEILING),
632 (1.0, 1, _PyTime.ROUND_CEILING),
633 (1.9, 2, _PyTime.ROUND_CEILING),
Victor Stinner5d272cc2012-03-13 13:35:55 +0100634 ):
Victor Stinner3c1b3792014-02-17 00:02:43 +0100635 self.assertEqual(pytime_object_to_time_t(obj, rnd), time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100636
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200637 rnd = _PyTime.ROUND_FLOOR
Victor Stinner5d272cc2012-03-13 13:35:55 +0100638 for invalid in self.invalid_values:
Victor Stinner3c1b3792014-02-17 00:02:43 +0100639 self.assertRaises(OverflowError,
640 pytime_object_to_time_t, invalid, rnd)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100641
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200642 @support.cpython_only
Victor Stinner643cd682012-03-02 22:54:03 +0100643 def test_timespec(self):
644 from _testcapi import pytime_object_to_timespec
Victor Stinner3c1b3792014-02-17 00:02:43 +0100645 for obj, timespec, rnd in (
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200646 # Round towards minus infinity (-inf)
647 (0, (0, 0), _PyTime.ROUND_FLOOR),
648 (-1, (-1, 0), _PyTime.ROUND_FLOOR),
649 (-1.0, (-1, 0), _PyTime.ROUND_FLOOR),
650 (1e-9, (0, 1), _PyTime.ROUND_FLOOR),
651 (1e-10, (0, 0), _PyTime.ROUND_FLOOR),
652 (-1e-9, (-1, 999999999), _PyTime.ROUND_FLOOR),
653 (-1e-10, (-1, 999999999), _PyTime.ROUND_FLOOR),
654 (-1.2, (-2, 800000000), _PyTime.ROUND_FLOOR),
655 (0.9999999999, (0, 999999999), _PyTime.ROUND_FLOOR),
656 (1.1234567890, (1, 123456789), _PyTime.ROUND_FLOOR),
657 (1.1234567899, (1, 123456789), _PyTime.ROUND_FLOOR),
658 (-1.1234567890, (-2, 876543211), _PyTime.ROUND_FLOOR),
659 (-1.1234567891, (-2, 876543210), _PyTime.ROUND_FLOOR),
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200660 # Round towards infinity (+inf)
661 (0, (0, 0), _PyTime.ROUND_CEILING),
662 (-1, (-1, 0), _PyTime.ROUND_CEILING),
663 (-1.0, (-1, 0), _PyTime.ROUND_CEILING),
664 (1e-9, (0, 1), _PyTime.ROUND_CEILING),
665 (1e-10, (0, 1), _PyTime.ROUND_CEILING),
666 (-1e-9, (-1, 999999999), _PyTime.ROUND_CEILING),
667 (-1e-10, (0, 0), _PyTime.ROUND_CEILING),
668 (-1.2, (-2, 800000000), _PyTime.ROUND_CEILING),
669 (0.9999999999, (1, 0), _PyTime.ROUND_CEILING),
670 (1.1234567890, (1, 123456790), _PyTime.ROUND_CEILING),
671 (1.1234567899, (1, 123456790), _PyTime.ROUND_CEILING),
672 (-1.1234567890, (-2, 876543211), _PyTime.ROUND_CEILING),
673 (-1.1234567891, (-2, 876543211), _PyTime.ROUND_CEILING),
Victor Stinner643cd682012-03-02 22:54:03 +0100674 ):
Victor Stinner3c1b3792014-02-17 00:02:43 +0100675 with self.subTest(obj=obj, round=rnd, timespec=timespec):
676 self.assertEqual(pytime_object_to_timespec(obj, rnd), timespec)
Victor Stinner643cd682012-03-02 22:54:03 +0100677
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200678 rnd = _PyTime.ROUND_FLOOR
Victor Stinner5d272cc2012-03-13 13:35:55 +0100679 for invalid in self.invalid_values:
Victor Stinner3c1b3792014-02-17 00:02:43 +0100680 self.assertRaises(OverflowError,
681 pytime_object_to_timespec, invalid, rnd)
Victor Stinner643cd682012-03-02 22:54:03 +0100682
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400683 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
684 def test_localtime_timezone(self):
Victor Stinner643cd682012-03-02 22:54:03 +0100685
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400686 # Get the localtime and examine it for the offset and zone.
687 lt = time.localtime()
688 self.assertTrue(hasattr(lt, "tm_gmtoff"))
689 self.assertTrue(hasattr(lt, "tm_zone"))
690
691 # See if the offset and zone are similar to the module
692 # attributes.
693 if lt.tm_gmtoff is None:
694 self.assertTrue(not hasattr(time, "timezone"))
695 else:
696 self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
697 if lt.tm_zone is None:
698 self.assertTrue(not hasattr(time, "tzname"))
699 else:
700 self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
701
702 # Try and make UNIX times from the localtime and a 9-tuple
703 # created from the localtime. Test to see that the times are
704 # the same.
705 t = time.mktime(lt); t9 = time.mktime(lt[:9])
706 self.assertEqual(t, t9)
707
708 # Make localtimes from the UNIX times and compare them to
709 # the original localtime, thus making a round trip.
710 new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
711 self.assertEqual(new_lt, lt)
712 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
713 self.assertEqual(new_lt.tm_zone, lt.tm_zone)
714 self.assertEqual(new_lt9, lt)
715 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
716 self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
717
718 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
719 def test_strptime_timezone(self):
720 t = time.strptime("UTC", "%Z")
721 self.assertEqual(t.tm_zone, 'UTC')
722 t = time.strptime("+0500", "%z")
723 self.assertEqual(t.tm_gmtoff, 5 * 3600)
724
725 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
726 def test_short_times(self):
727
728 import pickle
729
730 # Load a short time structure using pickle.
731 st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
732 lt = pickle.loads(st)
733 self.assertIs(lt.tm_gmtoff, None)
734 self.assertIs(lt.tm_zone, None)
Victor Stinner643cd682012-03-02 22:54:03 +0100735
Fred Drake2e2be372001-09-20 21:33:42 +0000736
Victor Stinner34dc0f42015-03-27 18:19:03 +0100737@unittest.skipUnless(_testcapi is not None,
738 'need the _testcapi module')
Victor Stinner992c43f2015-03-27 17:12:45 +0100739class TestPyTime_t(unittest.TestCase):
Victor Stinner13019fd2015-04-03 13:10:54 +0200740 def test_FromSeconds(self):
741 from _testcapi import PyTime_FromSeconds
742 for seconds in (0, 3, -456, _testcapi.INT_MAX, _testcapi.INT_MIN):
743 with self.subTest(seconds=seconds):
744 self.assertEqual(PyTime_FromSeconds(seconds),
745 seconds * SEC_TO_NS)
746
Victor Stinner992c43f2015-03-27 17:12:45 +0100747 def test_FromSecondsObject(self):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100748 from _testcapi import PyTime_FromSecondsObject
Victor Stinner992c43f2015-03-27 17:12:45 +0100749
750 # Conversion giving the same result for all rounding methods
751 for rnd in ALL_ROUNDING_METHODS:
752 for obj, ts in (
753 # integers
754 (0, 0),
755 (1, SEC_TO_NS),
756 (-3, -3 * SEC_TO_NS),
757
758 # float: subseconds
759 (0.0, 0),
760 (1e-9, 1),
761 (1e-6, 10 ** 3),
762 (1e-3, 10 ** 6),
763
764 # float: seconds
765 (2.0, 2 * SEC_TO_NS),
766 (123.0, 123 * SEC_TO_NS),
767 (-7.0, -7 * SEC_TO_NS),
768
769 # nanosecond are kept for value <= 2^23 seconds
770 (2**22 - 1e-9, 4194303999999999),
771 (2**22, 4194304000000000),
772 (2**22 + 1e-9, 4194304000000001),
773 (2**23 - 1e-9, 8388607999999999),
774 (2**23, 8388608000000000),
775
776 # start loosing precision for value > 2^23 seconds
777 (2**23 + 1e-9, 8388608000000002),
778
779 # nanoseconds are lost for value > 2^23 seconds
780 (2**24 - 1e-9, 16777215999999998),
781 (2**24, 16777216000000000),
782 (2**24 + 1e-9, 16777216000000000),
783 (2**25 - 1e-9, 33554432000000000),
784 (2**25 , 33554432000000000),
785 (2**25 + 1e-9, 33554432000000000),
786
Victor Stinner4bfb4602015-03-27 22:27:24 +0100787 # close to 2^63 nanoseconds (_PyTime_t limit)
Victor Stinner992c43f2015-03-27 17:12:45 +0100788 (9223372036, 9223372036 * SEC_TO_NS),
789 (9223372036.0, 9223372036 * SEC_TO_NS),
790 (-9223372036, -9223372036 * SEC_TO_NS),
791 (-9223372036.0, -9223372036 * SEC_TO_NS),
792 ):
793 with self.subTest(obj=obj, round=rnd, timestamp=ts):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100794 self.assertEqual(PyTime_FromSecondsObject(obj, rnd), ts)
Victor Stinner992c43f2015-03-27 17:12:45 +0100795
796 with self.subTest(round=rnd):
797 with self.assertRaises(OverflowError):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100798 PyTime_FromSecondsObject(9223372037, rnd)
799 PyTime_FromSecondsObject(9223372037.0, rnd)
800 PyTime_FromSecondsObject(-9223372037, rnd)
801 PyTime_FromSecondsObject(-9223372037.0, rnd)
Victor Stinner992c43f2015-03-27 17:12:45 +0100802
803 # Conversion giving different results depending on the rounding method
Victor Stinner02937aa2015-03-28 05:02:39 +0100804 FLOOR = _PyTime.ROUND_FLOOR
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200805 CEILING = _PyTime.ROUND_CEILING
Victor Stinner992c43f2015-03-27 17:12:45 +0100806 for obj, ts, rnd in (
807 # close to zero
Victor Stinner02937aa2015-03-28 05:02:39 +0100808 ( 1e-10, 0, FLOOR),
Victor Stinnera695f832015-03-30 03:57:14 +0200809 ( 1e-10, 1, CEILING),
Victor Stinner02937aa2015-03-28 05:02:39 +0100810 (-1e-10, -1, FLOOR),
Victor Stinnera695f832015-03-30 03:57:14 +0200811 (-1e-10, 0, CEILING),
Victor Stinner992c43f2015-03-27 17:12:45 +0100812
813 # test rounding of the last nanosecond
Victor Stinner02937aa2015-03-28 05:02:39 +0100814 ( 1.1234567899, 1123456789, FLOOR),
Victor Stinnera695f832015-03-30 03:57:14 +0200815 ( 1.1234567899, 1123456790, CEILING),
Victor Stinner02937aa2015-03-28 05:02:39 +0100816 (-1.1234567899, -1123456790, FLOOR),
Victor Stinnera695f832015-03-30 03:57:14 +0200817 (-1.1234567899, -1123456789, CEILING),
Victor Stinner992c43f2015-03-27 17:12:45 +0100818
819 # close to 1 second
Victor Stinner02937aa2015-03-28 05:02:39 +0100820 ( 0.9999999999, 999999999, FLOOR),
Victor Stinnera695f832015-03-30 03:57:14 +0200821 ( 0.9999999999, 1000000000, CEILING),
Victor Stinner02937aa2015-03-28 05:02:39 +0100822 (-0.9999999999, -1000000000, FLOOR),
Victor Stinnera695f832015-03-30 03:57:14 +0200823 (-0.9999999999, -999999999, CEILING),
Victor Stinner992c43f2015-03-27 17:12:45 +0100824 ):
825 with self.subTest(obj=obj, round=rnd, timestamp=ts):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100826 self.assertEqual(PyTime_FromSecondsObject(obj, rnd), ts)
827
828 def test_AsSecondsDouble(self):
829 from _testcapi import PyTime_AsSecondsDouble
830
831 for nanoseconds, seconds in (
832 # near 1 nanosecond
833 ( 0, 0.0),
834 ( 1, 1e-9),
835 (-1, -1e-9),
836
837 # near 1 second
838 (SEC_TO_NS + 1, 1.0 + 1e-9),
839 (SEC_TO_NS, 1.0),
840 (SEC_TO_NS - 1, 1.0 - 1e-9),
841
842 # a few seconds
843 (123 * SEC_TO_NS, 123.0),
844 (-567 * SEC_TO_NS, -567.0),
845
846 # nanosecond are kept for value <= 2^23 seconds
847 (4194303999999999, 2**22 - 1e-9),
848 (4194304000000000, 2**22),
849 (4194304000000001, 2**22 + 1e-9),
850
851 # start loosing precision for value > 2^23 seconds
852 (8388608000000002, 2**23 + 1e-9),
853
854 # nanoseconds are lost for value > 2^23 seconds
855 (16777215999999998, 2**24 - 1e-9),
856 (16777215999999999, 2**24 - 1e-9),
857 (16777216000000000, 2**24 ),
858 (16777216000000001, 2**24 ),
859 (16777216000000002, 2**24 + 2e-9),
860
861 (33554432000000000, 2**25 ),
862 (33554432000000002, 2**25 ),
863 (33554432000000004, 2**25 + 4e-9),
864
865 # close to 2^63 nanoseconds (_PyTime_t limit)
866 (9223372036 * SEC_TO_NS, 9223372036.0),
867 (-9223372036 * SEC_TO_NS, -9223372036.0),
868 ):
869 with self.subTest(nanoseconds=nanoseconds, seconds=seconds):
870 self.assertEqual(PyTime_AsSecondsDouble(nanoseconds),
871 seconds)
Victor Stinner992c43f2015-03-27 17:12:45 +0100872
Victor Stinner95e9cef2015-03-28 01:26:47 +0100873 def test_timeval(self):
874 from _testcapi import PyTime_AsTimeval
875 for rnd in ALL_ROUNDING_METHODS:
876 for ns, tv in (
877 # microseconds
878 (0, (0, 0)),
879 (1000, (0, 1)),
880 (-1000, (-1, 999999)),
881
882 # seconds
883 (2 * SEC_TO_NS, (2, 0)),
884 (-3 * SEC_TO_NS, (-3, 0)),
Victor Stinner95e9cef2015-03-28 01:26:47 +0100885 ):
886 with self.subTest(nanoseconds=ns, timeval=tv, round=rnd):
887 self.assertEqual(PyTime_AsTimeval(ns, rnd), tv)
888
Victor Stinner02937aa2015-03-28 05:02:39 +0100889 FLOOR = _PyTime.ROUND_FLOOR
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200890 CEILING = _PyTime.ROUND_CEILING
Victor Stinner95e9cef2015-03-28 01:26:47 +0100891 for ns, tv, rnd in (
892 # nanoseconds
Victor Stinner02937aa2015-03-28 05:02:39 +0100893 (1, (0, 0), FLOOR),
Victor Stinnera695f832015-03-30 03:57:14 +0200894 (1, (0, 1), CEILING),
Victor Stinner02937aa2015-03-28 05:02:39 +0100895 (-1, (-1, 999999), FLOOR),
Victor Stinnera695f832015-03-30 03:57:14 +0200896 (-1, (0, 0), CEILING),
Victor Stinner95e9cef2015-03-28 01:26:47 +0100897
898 # seconds + nanoseconds
Victor Stinner02937aa2015-03-28 05:02:39 +0100899 (1234567001, (1, 234567), FLOOR),
Victor Stinnera695f832015-03-30 03:57:14 +0200900 (1234567001, (1, 234568), CEILING),
Victor Stinner02937aa2015-03-28 05:02:39 +0100901 (-1234567001, (-2, 765432), FLOOR),
Victor Stinnera695f832015-03-30 03:57:14 +0200902 (-1234567001, (-2, 765433), CEILING),
Victor Stinner95e9cef2015-03-28 01:26:47 +0100903 ):
904 with self.subTest(nanoseconds=ns, timeval=tv, round=rnd):
905 self.assertEqual(PyTime_AsTimeval(ns, rnd), tv)
906
Victor Stinner34dc0f42015-03-27 18:19:03 +0100907 @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec'),
908 'need _testcapi.PyTime_AsTimespec')
909 def test_timespec(self):
910 from _testcapi import PyTime_AsTimespec
911 for ns, ts in (
912 # nanoseconds
913 (0, (0, 0)),
914 (1, (0, 1)),
915 (-1, (-1, 999999999)),
916
917 # seconds
918 (2 * SEC_TO_NS, (2, 0)),
919 (-3 * SEC_TO_NS, (-3, 0)),
920
921 # seconds + nanoseconds
922 (1234567890, (1, 234567890)),
923 (-1234567890, (-2, 765432110)),
924 ):
925 with self.subTest(nanoseconds=ns, timespec=ts):
926 self.assertEqual(PyTime_AsTimespec(ns), ts)
927
Victor Stinner62d1c702015-04-01 17:47:07 +0200928 def test_milliseconds(self):
929 from _testcapi import PyTime_AsMilliseconds
930 for rnd in ALL_ROUNDING_METHODS:
931 for ns, tv in (
932 # milliseconds
933 (1 * MS_TO_NS, 1),
934 (-2 * MS_TO_NS, -2),
935
936 # seconds
937 (2 * SEC_TO_NS, 2000),
938 (-3 * SEC_TO_NS, -3000),
939 ):
940 with self.subTest(nanoseconds=ns, timeval=tv, round=rnd):
941 self.assertEqual(PyTime_AsMilliseconds(ns, rnd), tv)
942
943 FLOOR = _PyTime.ROUND_FLOOR
944 CEILING = _PyTime.ROUND_CEILING
945 for ns, ms, rnd in (
946 # nanoseconds
947 (1, 0, FLOOR),
948 (1, 1, CEILING),
Victor Stinnerec26f832015-09-18 14:21:14 +0200949 (-1, -1, FLOOR),
950 (-1, 0, CEILING),
Victor Stinner62d1c702015-04-01 17:47:07 +0200951
952 # seconds + nanoseconds
953 (1234 * MS_TO_NS + 1, 1234, FLOOR),
954 (1234 * MS_TO_NS + 1, 1235, CEILING),
Victor Stinnerec26f832015-09-18 14:21:14 +0200955 (-1234 * MS_TO_NS - 1, -1235, FLOOR),
956 (-1234 * MS_TO_NS - 1, -1234, CEILING),
Victor Stinner62d1c702015-04-01 17:47:07 +0200957 ):
958 with self.subTest(nanoseconds=ns, milliseconds=ms, round=rnd):
959 self.assertEqual(PyTime_AsMilliseconds(ns, rnd), ms)
960
961 def test_microseconds(self):
962 from _testcapi import PyTime_AsMicroseconds
963 for rnd in ALL_ROUNDING_METHODS:
964 for ns, tv in (
965 # microseconds
966 (1 * US_TO_NS, 1),
967 (-2 * US_TO_NS, -2),
968
969 # milliseconds
970 (1 * MS_TO_NS, 1000),
971 (-2 * MS_TO_NS, -2000),
972
973 # seconds
974 (2 * SEC_TO_NS, 2000000),
975 (-3 * SEC_TO_NS, -3000000),
976 ):
977 with self.subTest(nanoseconds=ns, timeval=tv, round=rnd):
978 self.assertEqual(PyTime_AsMicroseconds(ns, rnd), tv)
979
980 FLOOR = _PyTime.ROUND_FLOOR
981 CEILING = _PyTime.ROUND_CEILING
982 for ns, ms, rnd in (
983 # nanoseconds
984 (1, 0, FLOOR),
985 (1, 1, CEILING),
Victor Stinnerec26f832015-09-18 14:21:14 +0200986 (-1, -1, FLOOR),
987 (-1, 0, CEILING),
Victor Stinner62d1c702015-04-01 17:47:07 +0200988
989 # seconds + nanoseconds
990 (1234 * US_TO_NS + 1, 1234, FLOOR),
991 (1234 * US_TO_NS + 1, 1235, CEILING),
Victor Stinnerec26f832015-09-18 14:21:14 +0200992 (-1234 * US_TO_NS - 1, -1235, FLOOR),
993 (-1234 * US_TO_NS - 1, -1234, CEILING),
Victor Stinner62d1c702015-04-01 17:47:07 +0200994 ):
995 with self.subTest(nanoseconds=ns, milliseconds=ms, round=rnd):
996 self.assertEqual(PyTime_AsMicroseconds(ns, rnd), ms)
997
Victor Stinner992c43f2015-03-27 17:12:45 +0100998
Fred Drake2e2be372001-09-20 21:33:42 +0000999if __name__ == "__main__":
Ezio Melotti3836d702013-04-11 20:29:42 +03001000 unittest.main()