blob: 6334e022e007c90d22689cee49672db34273c6a2 [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
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000177 def test_default_values_for_zero(self):
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400178 # Make sure that using all zeros uses the proper default
179 # values. No test for daylight savings since strftime() does
180 # not change output based on its value and no test for year
181 # because systems vary in their support for year 0.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000182 expected = "2000 01 01 00 00 00 1 001"
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000183 with support.check_warnings():
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400184 result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000185 self.assertEqual(expected, result)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000186
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000187 def test_strptime(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000188 # Should be able to go round-trip from strftime to strptime without
Andrew Svetlov737fb892012-12-18 21:14:22 +0200189 # raising an exception.
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000190 tt = time.gmtime(self.t)
191 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
192 'j', 'm', 'M', 'p', 'S',
193 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000194 format = '%' + directive
195 strf_output = time.strftime(format, tt)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000196 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000197 time.strptime(strf_output, format)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000198 except ValueError:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000199 self.fail("conversion specifier %r failed with '%s' input." %
200 (format, strf_output))
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000201
Brett Cannon7f6b4f82009-03-30 21:30:26 +0000202 def test_strptime_bytes(self):
203 # Make sure only strings are accepted as arguments to strptime.
204 self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
205 self.assertRaises(TypeError, time.strptime, '2009', b'%Y')
206
Ezio Melotti0f389082013-04-04 02:09:20 +0300207 def test_strptime_exception_context(self):
208 # check that this doesn't chain exceptions needlessly (see #17572)
209 with self.assertRaises(ValueError) as e:
210 time.strptime('', '%D')
211 self.assertIs(e.exception.__suppress_context__, True)
Serhiy Storchakacdac3022013-11-24 18:15:37 +0200212 # additional check for IndexError branch (issue #19545)
213 with self.assertRaises(ValueError) as e:
214 time.strptime('19', '%Y %')
215 self.assertIs(e.exception.__suppress_context__, True)
Ezio Melotti0f389082013-04-04 02:09:20 +0300216
Fred Drakebc561982001-05-22 17:02:02 +0000217 def test_asctime(self):
218 time.asctime(time.gmtime(self.t))
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000219
220 # Max year is only limited by the size of C int.
Florent Xiclunabceb5282011-11-01 14:11:34 +0100221 for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
222 asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
223 self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
224 self.assertRaises(OverflowError, time.asctime,
225 (TIME_MAXYEAR + 1,) + (0,) * 8)
226 self.assertRaises(OverflowError, time.asctime,
227 (TIME_MINYEAR - 1,) + (0,) * 8)
Fred Drakebc561982001-05-22 17:02:02 +0000228 self.assertRaises(TypeError, time.asctime, 0)
Alexander Belopolskye2dc0822011-01-02 20:48:22 +0000229 self.assertRaises(TypeError, time.asctime, ())
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000230 self.assertRaises(TypeError, time.asctime, (0,) * 10)
Fred Drakebc561982001-05-22 17:02:02 +0000231
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000232 def test_asctime_bounding_check(self):
233 self._bounds_checking(time.asctime)
234
Georg Brandle10608c2011-01-02 22:33:43 +0000235 def test_ctime(self):
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000236 t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
237 self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
238 t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
239 self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000')
Victor Stinner1ac42612014-02-21 09:27:17 +0100240 for year in [-100, 100, 1000, 2000, 2050, 10000]:
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000241 try:
242 testval = time.mktime((year, 1, 10) + (0,)*6)
243 except (ValueError, OverflowError):
244 # If mktime fails, ctime will fail too. This may happen
245 # on some platforms.
246 pass
247 else:
248 self.assertEqual(time.ctime(testval)[20:], str(year))
Georg Brandle10608c2011-01-02 22:33:43 +0000249
Florent Xiclunae54371e2011-11-11 18:59:30 +0100250 @unittest.skipUnless(hasattr(time, "tzset"),
251 "time module has no attribute tzset")
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000252 def test_tzset(self):
Guido van Rossumd2b738e2003-03-15 12:01:52 +0000253
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000254 from os import environ
255
Tim Peters0eadaac2003-04-24 16:02:54 +0000256 # Epoch time of midnight Dec 25th 2002. Never DST in northern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000257 # hemisphere.
Tim Peters0eadaac2003-04-24 16:02:54 +0000258 xmas2002 = 1040774400.0
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000259
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000260 # These formats are correct for 2002, and possibly future years
261 # This format is the 'standard' as documented at:
262 # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
263 # They are also documented in the tzset(3) man page on most Unix
264 # systems.
Tim Peters0eadaac2003-04-24 16:02:54 +0000265 eastern = 'EST+05EDT,M4.1.0,M10.5.0'
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000266 victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
267 utc='UTC+0'
268
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000269 org_TZ = environ.get('TZ',None)
270 try:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000271 # Make sure we can switch to UTC time and results are correct
272 # Note that unknown timezones default to UTC.
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000273 # Note that altzone is undefined in UTC, as there is no DST
274 environ['TZ'] = eastern
275 time.tzset()
276 environ['TZ'] = utc
277 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000278 self.assertEqual(
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000279 time.gmtime(xmas2002), time.localtime(xmas2002)
280 )
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000281 self.assertEqual(time.daylight, 0)
282 self.assertEqual(time.timezone, 0)
283 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000284
285 # Make sure we can switch to US/Eastern
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000286 environ['TZ'] = eastern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000287 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000288 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
289 self.assertEqual(time.tzname, ('EST', 'EDT'))
290 self.assertEqual(len(time.tzname), 2)
291 self.assertEqual(time.daylight, 1)
292 self.assertEqual(time.timezone, 18000)
293 self.assertEqual(time.altzone, 14400)
294 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
295 self.assertEqual(len(time.tzname), 2)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000296
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000297 # Now go to the southern hemisphere.
298 environ['TZ'] = victoria
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000299 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000300 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
Victor Stinner0cd47902011-12-08 00:32:51 +0100301
302 # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100303 # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
304 # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
305 # on some operating systems (e.g. FreeBSD), which is wrong. See for
306 # example this bug:
307 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
Victor Stinner0cd47902011-12-08 00:32:51 +0100308 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100309 self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000310 self.assertEqual(len(time.tzname), 2)
311 self.assertEqual(time.daylight, 1)
312 self.assertEqual(time.timezone, -36000)
313 self.assertEqual(time.altzone, -39600)
314 self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000315
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000316 finally:
317 # Repair TZ environment variable in case any other tests
318 # rely on it.
319 if org_TZ is not None:
320 environ['TZ'] = org_TZ
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000321 elif 'TZ' in environ:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000322 del environ['TZ']
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000323 time.tzset()
Tim Peters0eadaac2003-04-24 16:02:54 +0000324
Tim Peters1b6f7a92004-06-20 02:50:16 +0000325 def test_insane_timestamps(self):
326 # It's possible that some platform maps time_t to double,
327 # and that this test will fail there. This test should
328 # exempt such platforms (provided they return reasonable
329 # results!).
330 for func in time.ctime, time.gmtime, time.localtime:
331 for unreasonable in -1e200, 1e200:
Victor Stinner5d272cc2012-03-13 13:35:55 +0100332 self.assertRaises(OverflowError, func, unreasonable)
Fred Drakebc561982001-05-22 17:02:02 +0000333
Fred Drakef901abd2004-08-03 17:58:55 +0000334 def test_ctime_without_arg(self):
335 # Not sure how to check the values, since the clock could tick
336 # at any time. Make sure these are at least accepted and
337 # don't raise errors.
338 time.ctime()
339 time.ctime(None)
340
341 def test_gmtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000342 gt0 = time.gmtime()
343 gt1 = time.gmtime(None)
344 t0 = time.mktime(gt0)
345 t1 = time.mktime(gt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000346 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000347
348 def test_localtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000349 lt0 = time.localtime()
350 lt1 = time.localtime(None)
351 t0 = time.mktime(lt0)
352 t1 = time.mktime(lt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000353 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000354
Florent Xiclunae54371e2011-11-11 18:59:30 +0100355 def test_mktime(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100356 # Issue #1726687
357 for t in (-2, -1, 0, 1):
Victor Stinner8c8b4e02014-02-21 23:54:32 +0100358 if sys.platform.startswith('aix') and t == -1:
359 # Issue #11188, #19748: mktime() returns -1 on error. On Linux,
360 # the tm_wday field is used as a sentinel () to detect if -1 is
361 # really an error or a valid timestamp. On AIX, tm_wday is
362 # unchanged even on success and so cannot be used as a
363 # sentinel.
364 continue
Florent Xiclunabceb5282011-11-01 14:11:34 +0100365 try:
366 tt = time.localtime(t)
Victor Stinner2cbae982012-01-27 00:50:33 +0100367 except (OverflowError, OSError):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100368 pass
369 else:
370 self.assertEqual(time.mktime(tt), t)
Florent Xiclunae54371e2011-11-11 18:59:30 +0100371
372 # Issue #13309: passing extreme values to mktime() or localtime()
373 # borks the glibc's internal timezone data.
374 @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
375 "disabled because of a bug in glibc. Issue #13309")
376 def test_mktime_error(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100377 # It may not be possible to reliably make mktime return error
378 # on all platfom. This will make sure that no other exception
379 # than OverflowError is raised for an extreme value.
Florent Xiclunae54371e2011-11-11 18:59:30 +0100380 tt = time.gmtime(self.t)
381 tzname = time.strftime('%Z', tt)
382 self.assertNotEqual(tzname, 'LMT')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100383 try:
384 time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
385 except OverflowError:
386 pass
Florent Xiclunae54371e2011-11-11 18:59:30 +0100387 self.assertEqual(time.strftime('%Z', tt), tzname)
Florent Xiclunabceb5282011-11-01 14:11:34 +0100388
Victor Stinnerec895392012-04-29 02:41:27 +0200389 @unittest.skipUnless(hasattr(time, 'monotonic'),
390 'need time.monotonic')
391 def test_monotonic(self):
Victor Stinner6c861812013-11-23 00:15:27 +0100392 # monotonic() should not go backward
393 times = [time.monotonic() for n in range(100)]
394 t1 = times[0]
395 for t2 in times[1:]:
396 self.assertGreaterEqual(t2, t1, "times=%s" % times)
397 t1 = t2
398
399 # monotonic() includes time elapsed during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200400 t1 = time.monotonic()
Victor Stinnera9c99a62013-07-03 23:07:37 +0200401 time.sleep(0.5)
Victor Stinnerec895392012-04-29 02:41:27 +0200402 t2 = time.monotonic()
Victor Stinner2dd254d2012-01-20 02:24:18 +0100403 dt = t2 - t1
Victor Stinner8b302012012-02-07 23:29:46 +0100404 self.assertGreater(t2, t1)
Zachary Ware487aedb2014-01-02 09:41:10 -0600405 # Issue #20101: On some Windows machines, dt may be slightly low
406 self.assertTrue(0.45 <= dt <= 1.0, dt)
Antoine Pitrou391166f2012-01-18 22:35:21 +0100407
Victor Stinner6c861812013-11-23 00:15:27 +0100408 # monotonic() is a monotonic but non adjustable clock
Victor Stinnerec895392012-04-29 02:41:27 +0200409 info = time.get_clock_info('monotonic')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400410 self.assertTrue(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +0200411 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200412
413 def test_perf_counter(self):
414 time.perf_counter()
415
416 def test_process_time(self):
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200417 # process_time() should not include time spend during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200418 start = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200419 time.sleep(0.100)
Victor Stinnerec895392012-04-29 02:41:27 +0200420 stop = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200421 # use 20 ms because process_time() has usually a resolution of 15 ms
422 # on Windows
423 self.assertLess(stop - start, 0.020)
Victor Stinnerec895392012-04-29 02:41:27 +0200424
425 info = time.get_clock_info('process_time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400426 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200427 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200428
Victor Stinnerec895392012-04-29 02:41:27 +0200429 @unittest.skipUnless(hasattr(time, 'monotonic'),
430 'need time.monotonic')
431 @unittest.skipUnless(hasattr(time, 'clock_settime'),
432 'need time.clock_settime')
433 def test_monotonic_settime(self):
434 t1 = time.monotonic()
435 realtime = time.clock_gettime(time.CLOCK_REALTIME)
436 # jump backward with an offset of 1 hour
Victor Stinner071eca32012-03-15 01:17:09 +0100437 try:
Victor Stinnerec895392012-04-29 02:41:27 +0200438 time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
439 except PermissionError as err:
440 self.skipTest(err)
441 t2 = time.monotonic()
442 time.clock_settime(time.CLOCK_REALTIME, realtime)
443 # monotonic must not be affected by system clock updates
Victor Stinner071eca32012-03-15 01:17:09 +0100444 self.assertGreaterEqual(t2, t1)
445
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100446 def test_localtime_failure(self):
447 # Issue #13847: check for localtime() failure
Victor Stinner53d36452012-01-27 01:03:25 +0100448 invalid_time_t = None
449 for time_t in (-1, 2**30, 2**33, 2**60):
450 try:
451 time.localtime(time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100452 except OverflowError:
453 self.skipTest("need 64-bit time_t")
Victor Stinner53d36452012-01-27 01:03:25 +0100454 except OSError:
455 invalid_time_t = time_t
456 break
457 if invalid_time_t is None:
458 self.skipTest("unable to find an invalid time_t value")
459
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100460 self.assertRaises(OSError, time.localtime, invalid_time_t)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100461 self.assertRaises(OSError, time.ctime, invalid_time_t)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100462
Victor Stinnerec895392012-04-29 02:41:27 +0200463 def test_get_clock_info(self):
464 clocks = ['clock', 'perf_counter', 'process_time', 'time']
465 if hasattr(time, 'monotonic'):
466 clocks.append('monotonic')
467
468 for name in clocks:
469 info = time.get_clock_info(name)
470 #self.assertIsInstance(info, dict)
471 self.assertIsInstance(info.implementation, str)
472 self.assertNotEqual(info.implementation, '')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400473 self.assertIsInstance(info.monotonic, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200474 self.assertIsInstance(info.resolution, float)
475 # 0.0 < resolution <= 1.0
476 self.assertGreater(info.resolution, 0.0)
477 self.assertLessEqual(info.resolution, 1.0)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200478 self.assertIsInstance(info.adjustable, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200479
480 self.assertRaises(ValueError, time.get_clock_info, 'xxx')
481
482
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000483class TestLocale(unittest.TestCase):
484 def setUp(self):
485 self.oldloc = locale.setlocale(locale.LC_ALL)
Fred Drake2e2be372001-09-20 21:33:42 +0000486
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000487 def tearDown(self):
488 locale.setlocale(locale.LC_ALL, self.oldloc)
489
Martin v. Löwisa6a9c4d2009-05-30 06:15:30 +0000490 def test_bug_3061(self):
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000491 try:
492 tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
493 except locale.Error:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600494 self.skipTest('could not set locale.LC_ALL to fr_FR')
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000495 # This should not cause an exception
496 time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
497
Victor Stinner73ea29c2011-01-08 01:56:31 +0000498
Victor Stinner73ea29c2011-01-08 01:56:31 +0000499class _TestAsctimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100500 _format = '%d'
501
Victor Stinner73ea29c2011-01-08 01:56:31 +0000502 def yearstr(self, y):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000503 return time.asctime((y,) + (0,) * 8).split()[-1]
Alexander Belopolskya6867252011-01-05 23:00:47 +0000504
Victor Stinner73ea29c2011-01-08 01:56:31 +0000505 def test_large_year(self):
Victor Stinner73691322011-01-08 02:00:24 +0000506 # Check that it doesn't crash for year > 9999
Victor Stinner73ea29c2011-01-08 01:56:31 +0000507 self.assertEqual(self.yearstr(12345), '12345')
508 self.assertEqual(self.yearstr(123456789), '123456789')
509
510class _TestStrftimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100511
512 # Issue 13305: For years < 1000, the value is not always
513 # padded to 4 digits across platforms. The C standard
514 # assumes year >= 1900, so it does not specify the number
515 # of digits.
516
517 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
518 _format = '%04d'
519 else:
520 _format = '%d'
521
Victor Stinner73ea29c2011-01-08 01:56:31 +0000522 def yearstr(self, y):
Florent Xicluna49ce0682011-11-01 12:56:14 +0100523 return time.strftime('%Y', (y,) + (0,) * 8)
524
525 def test_4dyear(self):
526 # Check that we can return the zero padded value.
527 if self._format == '%04d':
528 self.test_year('%04d')
529 else:
530 def year4d(y):
531 return time.strftime('%4Y', (y,) + (0,) * 8)
532 self.test_year('%04d', func=year4d)
533
Florent Xiclunabceb5282011-11-01 14:11:34 +0100534 def skip_if_not_supported(y):
535 msg = "strftime() is limited to [1; 9999] with Visual Studio"
536 # Check that it doesn't crash for year > 9999
537 try:
538 time.strftime('%Y', (y,) + (0,) * 8)
539 except ValueError:
540 cond = False
541 else:
542 cond = True
543 return unittest.skipUnless(cond, msg)
544
545 @skip_if_not_supported(10000)
546 def test_large_year(self):
547 return super().test_large_year()
548
549 @skip_if_not_supported(0)
550 def test_negative(self):
551 return super().test_negative()
552
553 del skip_if_not_supported
554
555
Ezio Melotti3836d702013-04-11 20:29:42 +0300556class _Test4dYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100557 _format = '%d'
558
559 def test_year(self, fmt=None, func=None):
560 fmt = fmt or self._format
561 func = func or self.yearstr
562 self.assertEqual(func(1), fmt % 1)
563 self.assertEqual(func(68), fmt % 68)
564 self.assertEqual(func(69), fmt % 69)
565 self.assertEqual(func(99), fmt % 99)
566 self.assertEqual(func(999), fmt % 999)
567 self.assertEqual(func(9999), fmt % 9999)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000568
569 def test_large_year(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100570 self.assertEqual(self.yearstr(12345), '12345')
Victor Stinner13ed2ea2011-03-21 02:11:01 +0100571 self.assertEqual(self.yearstr(123456789), '123456789')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100572 self.assertEqual(self.yearstr(TIME_MAXYEAR), str(TIME_MAXYEAR))
573 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000574
Victor Stinner301f1212011-01-08 03:06:52 +0000575 def test_negative(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100576 self.assertEqual(self.yearstr(-1), self._format % -1)
Victor Stinner301f1212011-01-08 03:06:52 +0000577 self.assertEqual(self.yearstr(-1234), '-1234')
578 self.assertEqual(self.yearstr(-123456), '-123456')
Florent Xiclunad1bd7f72011-11-01 23:42:05 +0100579 self.assertEqual(self.yearstr(-123456789), str(-123456789))
580 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
Florent Xicluna2fbc1852011-11-02 08:13:43 +0100581 self.assertEqual(self.yearstr(TIME_MINYEAR + 1900), str(TIME_MINYEAR + 1900))
582 # Issue #13312: it may return wrong value for year < TIME_MINYEAR + 1900
583 # Skip the value test, but check that no error is raised
584 self.yearstr(TIME_MINYEAR)
Florent Xiclunae2a732e2011-11-02 01:28:17 +0100585 # self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
Florent Xiclunabceb5282011-11-01 14:11:34 +0100586 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
Victor Stinner301f1212011-01-08 03:06:52 +0000587
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000588
Ezio Melotti3836d702013-04-11 20:29:42 +0300589class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner73ea29c2011-01-08 01:56:31 +0000590 pass
591
Ezio Melotti3836d702013-04-11 20:29:42 +0300592class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner301f1212011-01-08 03:06:52 +0000593 pass
Victor Stinner73ea29c2011-01-08 01:56:31 +0000594
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000595
Victor Stinner643cd682012-03-02 22:54:03 +0100596class TestPytime(unittest.TestCase):
Victor Stinner5d272cc2012-03-13 13:35:55 +0100597 def setUp(self):
598 self.invalid_values = (
599 -(2 ** 100), 2 ** 100,
600 -(2.0 ** 100.0), 2.0 ** 100.0,
601 )
602
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200603 @support.cpython_only
Victor Stinner5d272cc2012-03-13 13:35:55 +0100604 def test_time_t(self):
605 from _testcapi import pytime_object_to_time_t
Victor Stinner3c1b3792014-02-17 00:02:43 +0100606 for obj, time_t, rnd in (
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200607 # Round towards minus infinity (-inf)
608 (0, 0, _PyTime.ROUND_FLOOR),
609 (-1, -1, _PyTime.ROUND_FLOOR),
610 (-1.0, -1, _PyTime.ROUND_FLOOR),
611 (-1.9, -2, _PyTime.ROUND_FLOOR),
612 (1.0, 1, _PyTime.ROUND_FLOOR),
613 (1.9, 1, _PyTime.ROUND_FLOOR),
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200614 # Round towards infinity (+inf)
615 (0, 0, _PyTime.ROUND_CEILING),
616 (-1, -1, _PyTime.ROUND_CEILING),
617 (-1.0, -1, _PyTime.ROUND_CEILING),
618 (-1.9, -1, _PyTime.ROUND_CEILING),
619 (1.0, 1, _PyTime.ROUND_CEILING),
620 (1.9, 2, _PyTime.ROUND_CEILING),
Victor Stinner5d272cc2012-03-13 13:35:55 +0100621 ):
Victor Stinner3c1b3792014-02-17 00:02:43 +0100622 self.assertEqual(pytime_object_to_time_t(obj, rnd), time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100623
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200624 rnd = _PyTime.ROUND_FLOOR
Victor Stinner5d272cc2012-03-13 13:35:55 +0100625 for invalid in self.invalid_values:
Victor Stinner3c1b3792014-02-17 00:02:43 +0100626 self.assertRaises(OverflowError,
627 pytime_object_to_time_t, invalid, rnd)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100628
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200629 @support.cpython_only
Victor Stinner643cd682012-03-02 22:54:03 +0100630 def test_timespec(self):
631 from _testcapi import pytime_object_to_timespec
Victor Stinner3c1b3792014-02-17 00:02:43 +0100632 for obj, timespec, rnd in (
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200633 # Round towards minus infinity (-inf)
634 (0, (0, 0), _PyTime.ROUND_FLOOR),
635 (-1, (-1, 0), _PyTime.ROUND_FLOOR),
636 (-1.0, (-1, 0), _PyTime.ROUND_FLOOR),
637 (1e-9, (0, 1), _PyTime.ROUND_FLOOR),
638 (1e-10, (0, 0), _PyTime.ROUND_FLOOR),
639 (-1e-9, (-1, 999999999), _PyTime.ROUND_FLOOR),
640 (-1e-10, (-1, 999999999), _PyTime.ROUND_FLOOR),
641 (-1.2, (-2, 800000000), _PyTime.ROUND_FLOOR),
642 (0.9999999999, (0, 999999999), _PyTime.ROUND_FLOOR),
643 (1.1234567890, (1, 123456789), _PyTime.ROUND_FLOOR),
644 (1.1234567899, (1, 123456789), _PyTime.ROUND_FLOOR),
645 (-1.1234567890, (-2, 876543211), _PyTime.ROUND_FLOOR),
646 (-1.1234567891, (-2, 876543210), _PyTime.ROUND_FLOOR),
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200647 # Round towards infinity (+inf)
648 (0, (0, 0), _PyTime.ROUND_CEILING),
649 (-1, (-1, 0), _PyTime.ROUND_CEILING),
650 (-1.0, (-1, 0), _PyTime.ROUND_CEILING),
651 (1e-9, (0, 1), _PyTime.ROUND_CEILING),
652 (1e-10, (0, 1), _PyTime.ROUND_CEILING),
653 (-1e-9, (-1, 999999999), _PyTime.ROUND_CEILING),
654 (-1e-10, (0, 0), _PyTime.ROUND_CEILING),
655 (-1.2, (-2, 800000000), _PyTime.ROUND_CEILING),
656 (0.9999999999, (1, 0), _PyTime.ROUND_CEILING),
657 (1.1234567890, (1, 123456790), _PyTime.ROUND_CEILING),
658 (1.1234567899, (1, 123456790), _PyTime.ROUND_CEILING),
659 (-1.1234567890, (-2, 876543211), _PyTime.ROUND_CEILING),
660 (-1.1234567891, (-2, 876543211), _PyTime.ROUND_CEILING),
Victor Stinner643cd682012-03-02 22:54:03 +0100661 ):
Victor Stinner3c1b3792014-02-17 00:02:43 +0100662 with self.subTest(obj=obj, round=rnd, timespec=timespec):
663 self.assertEqual(pytime_object_to_timespec(obj, rnd), timespec)
Victor Stinner643cd682012-03-02 22:54:03 +0100664
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200665 rnd = _PyTime.ROUND_FLOOR
Victor Stinner5d272cc2012-03-13 13:35:55 +0100666 for invalid in self.invalid_values:
Victor Stinner3c1b3792014-02-17 00:02:43 +0100667 self.assertRaises(OverflowError,
668 pytime_object_to_timespec, invalid, rnd)
Victor Stinner643cd682012-03-02 22:54:03 +0100669
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400670 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
671 def test_localtime_timezone(self):
Victor Stinner643cd682012-03-02 22:54:03 +0100672
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400673 # Get the localtime and examine it for the offset and zone.
674 lt = time.localtime()
675 self.assertTrue(hasattr(lt, "tm_gmtoff"))
676 self.assertTrue(hasattr(lt, "tm_zone"))
677
678 # See if the offset and zone are similar to the module
679 # attributes.
680 if lt.tm_gmtoff is None:
681 self.assertTrue(not hasattr(time, "timezone"))
682 else:
683 self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
684 if lt.tm_zone is None:
685 self.assertTrue(not hasattr(time, "tzname"))
686 else:
687 self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
688
689 # Try and make UNIX times from the localtime and a 9-tuple
690 # created from the localtime. Test to see that the times are
691 # the same.
692 t = time.mktime(lt); t9 = time.mktime(lt[:9])
693 self.assertEqual(t, t9)
694
695 # Make localtimes from the UNIX times and compare them to
696 # the original localtime, thus making a round trip.
697 new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
698 self.assertEqual(new_lt, lt)
699 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
700 self.assertEqual(new_lt.tm_zone, lt.tm_zone)
701 self.assertEqual(new_lt9, lt)
702 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
703 self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
704
705 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
706 def test_strptime_timezone(self):
707 t = time.strptime("UTC", "%Z")
708 self.assertEqual(t.tm_zone, 'UTC')
709 t = time.strptime("+0500", "%z")
710 self.assertEqual(t.tm_gmtoff, 5 * 3600)
711
712 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
713 def test_short_times(self):
714
715 import pickle
716
717 # Load a short time structure using pickle.
718 st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
719 lt = pickle.loads(st)
720 self.assertIs(lt.tm_gmtoff, None)
721 self.assertIs(lt.tm_zone, None)
Victor Stinner643cd682012-03-02 22:54:03 +0100722
Fred Drake2e2be372001-09-20 21:33:42 +0000723
Victor Stinner34dc0f42015-03-27 18:19:03 +0100724@unittest.skipUnless(_testcapi is not None,
725 'need the _testcapi module')
Victor Stinner992c43f2015-03-27 17:12:45 +0100726class TestPyTime_t(unittest.TestCase):
Victor Stinner13019fd2015-04-03 13:10:54 +0200727 def test_FromSeconds(self):
728 from _testcapi import PyTime_FromSeconds
729 for seconds in (0, 3, -456, _testcapi.INT_MAX, _testcapi.INT_MIN):
730 with self.subTest(seconds=seconds):
731 self.assertEqual(PyTime_FromSeconds(seconds),
732 seconds * SEC_TO_NS)
733
Victor Stinner992c43f2015-03-27 17:12:45 +0100734 def test_FromSecondsObject(self):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100735 from _testcapi import PyTime_FromSecondsObject
Victor Stinner992c43f2015-03-27 17:12:45 +0100736
737 # Conversion giving the same result for all rounding methods
738 for rnd in ALL_ROUNDING_METHODS:
739 for obj, ts in (
740 # integers
741 (0, 0),
742 (1, SEC_TO_NS),
743 (-3, -3 * SEC_TO_NS),
744
745 # float: subseconds
746 (0.0, 0),
747 (1e-9, 1),
748 (1e-6, 10 ** 3),
749 (1e-3, 10 ** 6),
750
751 # float: seconds
752 (2.0, 2 * SEC_TO_NS),
753 (123.0, 123 * SEC_TO_NS),
754 (-7.0, -7 * SEC_TO_NS),
755
756 # nanosecond are kept for value <= 2^23 seconds
757 (2**22 - 1e-9, 4194303999999999),
758 (2**22, 4194304000000000),
759 (2**22 + 1e-9, 4194304000000001),
760 (2**23 - 1e-9, 8388607999999999),
761 (2**23, 8388608000000000),
762
763 # start loosing precision for value > 2^23 seconds
764 (2**23 + 1e-9, 8388608000000002),
765
766 # nanoseconds are lost for value > 2^23 seconds
767 (2**24 - 1e-9, 16777215999999998),
768 (2**24, 16777216000000000),
769 (2**24 + 1e-9, 16777216000000000),
770 (2**25 - 1e-9, 33554432000000000),
771 (2**25 , 33554432000000000),
772 (2**25 + 1e-9, 33554432000000000),
773
Victor Stinner4bfb4602015-03-27 22:27:24 +0100774 # close to 2^63 nanoseconds (_PyTime_t limit)
Victor Stinner992c43f2015-03-27 17:12:45 +0100775 (9223372036, 9223372036 * SEC_TO_NS),
776 (9223372036.0, 9223372036 * SEC_TO_NS),
777 (-9223372036, -9223372036 * SEC_TO_NS),
778 (-9223372036.0, -9223372036 * SEC_TO_NS),
779 ):
780 with self.subTest(obj=obj, round=rnd, timestamp=ts):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100781 self.assertEqual(PyTime_FromSecondsObject(obj, rnd), ts)
Victor Stinner992c43f2015-03-27 17:12:45 +0100782
783 with self.subTest(round=rnd):
784 with self.assertRaises(OverflowError):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100785 PyTime_FromSecondsObject(9223372037, rnd)
786 PyTime_FromSecondsObject(9223372037.0, rnd)
787 PyTime_FromSecondsObject(-9223372037, rnd)
788 PyTime_FromSecondsObject(-9223372037.0, rnd)
Victor Stinner992c43f2015-03-27 17:12:45 +0100789
790 # Conversion giving different results depending on the rounding method
Victor Stinner02937aa2015-03-28 05:02:39 +0100791 FLOOR = _PyTime.ROUND_FLOOR
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200792 CEILING = _PyTime.ROUND_CEILING
Victor Stinner992c43f2015-03-27 17:12:45 +0100793 for obj, ts, rnd in (
794 # close to zero
Victor Stinner02937aa2015-03-28 05:02:39 +0100795 ( 1e-10, 0, FLOOR),
Victor Stinnera695f832015-03-30 03:57:14 +0200796 ( 1e-10, 1, CEILING),
Victor Stinner02937aa2015-03-28 05:02:39 +0100797 (-1e-10, -1, FLOOR),
Victor Stinnera695f832015-03-30 03:57:14 +0200798 (-1e-10, 0, CEILING),
Victor Stinner992c43f2015-03-27 17:12:45 +0100799
800 # test rounding of the last nanosecond
Victor Stinner02937aa2015-03-28 05:02:39 +0100801 ( 1.1234567899, 1123456789, FLOOR),
Victor Stinnera695f832015-03-30 03:57:14 +0200802 ( 1.1234567899, 1123456790, CEILING),
Victor Stinner02937aa2015-03-28 05:02:39 +0100803 (-1.1234567899, -1123456790, FLOOR),
Victor Stinnera695f832015-03-30 03:57:14 +0200804 (-1.1234567899, -1123456789, CEILING),
Victor Stinner992c43f2015-03-27 17:12:45 +0100805
806 # close to 1 second
Victor Stinner02937aa2015-03-28 05:02:39 +0100807 ( 0.9999999999, 999999999, FLOOR),
Victor Stinnera695f832015-03-30 03:57:14 +0200808 ( 0.9999999999, 1000000000, CEILING),
Victor Stinner02937aa2015-03-28 05:02:39 +0100809 (-0.9999999999, -1000000000, FLOOR),
Victor Stinnera695f832015-03-30 03:57:14 +0200810 (-0.9999999999, -999999999, CEILING),
Victor Stinner992c43f2015-03-27 17:12:45 +0100811 ):
812 with self.subTest(obj=obj, round=rnd, timestamp=ts):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100813 self.assertEqual(PyTime_FromSecondsObject(obj, rnd), ts)
814
815 def test_AsSecondsDouble(self):
816 from _testcapi import PyTime_AsSecondsDouble
817
818 for nanoseconds, seconds in (
819 # near 1 nanosecond
820 ( 0, 0.0),
821 ( 1, 1e-9),
822 (-1, -1e-9),
823
824 # near 1 second
825 (SEC_TO_NS + 1, 1.0 + 1e-9),
826 (SEC_TO_NS, 1.0),
827 (SEC_TO_NS - 1, 1.0 - 1e-9),
828
829 # a few seconds
830 (123 * SEC_TO_NS, 123.0),
831 (-567 * SEC_TO_NS, -567.0),
832
833 # nanosecond are kept for value <= 2^23 seconds
834 (4194303999999999, 2**22 - 1e-9),
835 (4194304000000000, 2**22),
836 (4194304000000001, 2**22 + 1e-9),
837
838 # start loosing precision for value > 2^23 seconds
839 (8388608000000002, 2**23 + 1e-9),
840
841 # nanoseconds are lost for value > 2^23 seconds
842 (16777215999999998, 2**24 - 1e-9),
843 (16777215999999999, 2**24 - 1e-9),
844 (16777216000000000, 2**24 ),
845 (16777216000000001, 2**24 ),
846 (16777216000000002, 2**24 + 2e-9),
847
848 (33554432000000000, 2**25 ),
849 (33554432000000002, 2**25 ),
850 (33554432000000004, 2**25 + 4e-9),
851
852 # close to 2^63 nanoseconds (_PyTime_t limit)
853 (9223372036 * SEC_TO_NS, 9223372036.0),
854 (-9223372036 * SEC_TO_NS, -9223372036.0),
855 ):
856 with self.subTest(nanoseconds=nanoseconds, seconds=seconds):
857 self.assertEqual(PyTime_AsSecondsDouble(nanoseconds),
858 seconds)
Victor Stinner992c43f2015-03-27 17:12:45 +0100859
Victor Stinner95e9cef2015-03-28 01:26:47 +0100860 def test_timeval(self):
861 from _testcapi import PyTime_AsTimeval
862 for rnd in ALL_ROUNDING_METHODS:
863 for ns, tv in (
864 # microseconds
865 (0, (0, 0)),
866 (1000, (0, 1)),
867 (-1000, (-1, 999999)),
868
869 # seconds
870 (2 * SEC_TO_NS, (2, 0)),
871 (-3 * SEC_TO_NS, (-3, 0)),
Victor Stinner95e9cef2015-03-28 01:26:47 +0100872 ):
873 with self.subTest(nanoseconds=ns, timeval=tv, round=rnd):
874 self.assertEqual(PyTime_AsTimeval(ns, rnd), tv)
875
Victor Stinner02937aa2015-03-28 05:02:39 +0100876 FLOOR = _PyTime.ROUND_FLOOR
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200877 CEILING = _PyTime.ROUND_CEILING
Victor Stinner95e9cef2015-03-28 01:26:47 +0100878 for ns, tv, rnd in (
879 # nanoseconds
Victor Stinner02937aa2015-03-28 05:02:39 +0100880 (1, (0, 0), FLOOR),
Victor Stinnera695f832015-03-30 03:57:14 +0200881 (1, (0, 1), CEILING),
Victor Stinner02937aa2015-03-28 05:02:39 +0100882 (-1, (-1, 999999), FLOOR),
Victor Stinnera695f832015-03-30 03:57:14 +0200883 (-1, (0, 0), CEILING),
Victor Stinner95e9cef2015-03-28 01:26:47 +0100884
885 # seconds + nanoseconds
Victor Stinner02937aa2015-03-28 05:02:39 +0100886 (1234567001, (1, 234567), FLOOR),
Victor Stinnera695f832015-03-30 03:57:14 +0200887 (1234567001, (1, 234568), CEILING),
Victor Stinner02937aa2015-03-28 05:02:39 +0100888 (-1234567001, (-2, 765432), FLOOR),
Victor Stinnera695f832015-03-30 03:57:14 +0200889 (-1234567001, (-2, 765433), CEILING),
Victor Stinner95e9cef2015-03-28 01:26:47 +0100890 ):
891 with self.subTest(nanoseconds=ns, timeval=tv, round=rnd):
892 self.assertEqual(PyTime_AsTimeval(ns, rnd), tv)
893
Victor Stinner34dc0f42015-03-27 18:19:03 +0100894 @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec'),
895 'need _testcapi.PyTime_AsTimespec')
896 def test_timespec(self):
897 from _testcapi import PyTime_AsTimespec
898 for ns, ts in (
899 # nanoseconds
900 (0, (0, 0)),
901 (1, (0, 1)),
902 (-1, (-1, 999999999)),
903
904 # seconds
905 (2 * SEC_TO_NS, (2, 0)),
906 (-3 * SEC_TO_NS, (-3, 0)),
907
908 # seconds + nanoseconds
909 (1234567890, (1, 234567890)),
910 (-1234567890, (-2, 765432110)),
911 ):
912 with self.subTest(nanoseconds=ns, timespec=ts):
913 self.assertEqual(PyTime_AsTimespec(ns), ts)
914
Victor Stinner62d1c702015-04-01 17:47:07 +0200915 def test_milliseconds(self):
916 from _testcapi import PyTime_AsMilliseconds
917 for rnd in ALL_ROUNDING_METHODS:
918 for ns, tv in (
919 # milliseconds
920 (1 * MS_TO_NS, 1),
921 (-2 * MS_TO_NS, -2),
922
923 # seconds
924 (2 * SEC_TO_NS, 2000),
925 (-3 * SEC_TO_NS, -3000),
926 ):
927 with self.subTest(nanoseconds=ns, timeval=tv, round=rnd):
928 self.assertEqual(PyTime_AsMilliseconds(ns, rnd), tv)
929
930 FLOOR = _PyTime.ROUND_FLOOR
931 CEILING = _PyTime.ROUND_CEILING
932 for ns, ms, rnd in (
933 # nanoseconds
934 (1, 0, FLOOR),
935 (1, 1, CEILING),
936 (-1, 0, FLOOR),
937 (-1, -1, CEILING),
938
939 # seconds + nanoseconds
940 (1234 * MS_TO_NS + 1, 1234, FLOOR),
941 (1234 * MS_TO_NS + 1, 1235, CEILING),
942 (-1234 * MS_TO_NS - 1, -1234, FLOOR),
943 (-1234 * MS_TO_NS - 1, -1235, CEILING),
944 ):
945 with self.subTest(nanoseconds=ns, milliseconds=ms, round=rnd):
946 self.assertEqual(PyTime_AsMilliseconds(ns, rnd), ms)
947
948 def test_microseconds(self):
949 from _testcapi import PyTime_AsMicroseconds
950 for rnd in ALL_ROUNDING_METHODS:
951 for ns, tv in (
952 # microseconds
953 (1 * US_TO_NS, 1),
954 (-2 * US_TO_NS, -2),
955
956 # milliseconds
957 (1 * MS_TO_NS, 1000),
958 (-2 * MS_TO_NS, -2000),
959
960 # seconds
961 (2 * SEC_TO_NS, 2000000),
962 (-3 * SEC_TO_NS, -3000000),
963 ):
964 with self.subTest(nanoseconds=ns, timeval=tv, round=rnd):
965 self.assertEqual(PyTime_AsMicroseconds(ns, rnd), tv)
966
967 FLOOR = _PyTime.ROUND_FLOOR
968 CEILING = _PyTime.ROUND_CEILING
969 for ns, ms, rnd in (
970 # nanoseconds
971 (1, 0, FLOOR),
972 (1, 1, CEILING),
973 (-1, 0, FLOOR),
974 (-1, -1, CEILING),
975
976 # seconds + nanoseconds
977 (1234 * US_TO_NS + 1, 1234, FLOOR),
978 (1234 * US_TO_NS + 1, 1235, CEILING),
979 (-1234 * US_TO_NS - 1, -1234, FLOOR),
980 (-1234 * US_TO_NS - 1, -1235, CEILING),
981 ):
982 with self.subTest(nanoseconds=ns, milliseconds=ms, round=rnd):
983 self.assertEqual(PyTime_AsMicroseconds(ns, rnd), ms)
984
Victor Stinner992c43f2015-03-27 17:12:45 +0100985
Fred Drake2e2be372001-09-20 21:33:42 +0000986if __name__ == "__main__":
Ezio Melotti3836d702013-04-11 20:29:42 +0300987 unittest.main()