blob: a9f6fd87edbe05271dab3dbd2fb8aea98325561d [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
Senthil Kumaran8f377a32011-04-06 12:54:06 +0800117 # Issue #10762: Guard against invalid/non-supported format string
118 # so that Python don't crash (Windows crashes when the format string
119 # input to [w]strftime is not kosher.
120 if sys.platform.startswith('win'):
121 with self.assertRaises(ValueError):
122 time.strftime('%f')
123
Florent Xicluna49ce0682011-11-01 12:56:14 +0100124 def _bounds_checking(self, func):
Brett Cannond1080a32004-03-02 04:38:10 +0000125 # Make sure that strftime() checks the bounds of the various parts
Florent Xicluna49ce0682011-11-01 12:56:14 +0100126 # of the time tuple (0 is valid for *all* values).
Brett Cannond1080a32004-03-02 04:38:10 +0000127
Victor Stinner73ea29c2011-01-08 01:56:31 +0000128 # The year field is tested by other test cases above
129
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000130 # Check month [1, 12] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100131 func((1900, 0, 1, 0, 0, 0, 0, 1, -1))
132 func((1900, 12, 1, 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, 13, 1, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000137 # Check day of month [1, 31] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100138 func((1900, 1, 0, 0, 0, 0, 0, 1, -1))
139 func((1900, 1, 31, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000140 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000141 (1900, 1, -1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000142 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000143 (1900, 1, 32, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000144 # Check hour [0, 23]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100145 func((1900, 1, 1, 23, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000146 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000147 (1900, 1, 1, -1, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000148 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000149 (1900, 1, 1, 24, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000150 # Check minute [0, 59]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100151 func((1900, 1, 1, 0, 59, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000152 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000153 (1900, 1, 1, 0, -1, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000154 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000155 (1900, 1, 1, 0, 60, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000156 # Check second [0, 61]
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000157 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000158 (1900, 1, 1, 0, 0, -1, 0, 1, -1))
159 # C99 only requires allowing for one leap second, but Python's docs say
160 # allow two leap seconds (0..61)
Florent Xicluna49ce0682011-11-01 12:56:14 +0100161 func((1900, 1, 1, 0, 0, 60, 0, 1, -1))
162 func((1900, 1, 1, 0, 0, 61, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000163 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000164 (1900, 1, 1, 0, 0, 62, 0, 1, -1))
165 # No check for upper-bound day of week;
166 # value forced into range by a ``% 7`` calculation.
167 # Start check at -2 since gettmarg() increments value before taking
168 # modulo.
Florent Xicluna49ce0682011-11-01 12:56:14 +0100169 self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)),
170 func((1900, 1, 1, 0, 0, 0, +6, 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, -2, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000173 # Check day of the year [1, 366] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100174 func((1900, 1, 1, 0, 0, 0, 0, 0, -1))
175 func((1900, 1, 1, 0, 0, 0, 0, 366, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000176 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000177 (1900, 1, 1, 0, 0, 0, 0, -1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000178 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000179 (1900, 1, 1, 0, 0, 0, 0, 367, -1))
Brett Cannond1080a32004-03-02 04:38:10 +0000180
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000181 def test_strftime_bounding_check(self):
182 self._bounds_checking(lambda tup: time.strftime('', tup))
183
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000184 def test_default_values_for_zero(self):
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400185 # Make sure that using all zeros uses the proper default
186 # values. No test for daylight savings since strftime() does
187 # not change output based on its value and no test for year
188 # because systems vary in their support for year 0.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000189 expected = "2000 01 01 00 00 00 1 001"
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000190 with support.check_warnings():
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400191 result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000192 self.assertEqual(expected, result)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000193
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000194 def test_strptime(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000195 # Should be able to go round-trip from strftime to strptime without
Andrew Svetlov737fb892012-12-18 21:14:22 +0200196 # raising an exception.
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000197 tt = time.gmtime(self.t)
198 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
199 'j', 'm', 'M', 'p', 'S',
200 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000201 format = '%' + directive
202 strf_output = time.strftime(format, tt)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000203 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000204 time.strptime(strf_output, format)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000205 except ValueError:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000206 self.fail("conversion specifier %r failed with '%s' input." %
207 (format, strf_output))
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000208
Brett Cannon7f6b4f82009-03-30 21:30:26 +0000209 def test_strptime_bytes(self):
210 # Make sure only strings are accepted as arguments to strptime.
211 self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
212 self.assertRaises(TypeError, time.strptime, '2009', b'%Y')
213
Ezio Melotti0f389082013-04-04 02:09:20 +0300214 def test_strptime_exception_context(self):
215 # check that this doesn't chain exceptions needlessly (see #17572)
216 with self.assertRaises(ValueError) as e:
217 time.strptime('', '%D')
218 self.assertIs(e.exception.__suppress_context__, True)
Serhiy Storchakacdac3022013-11-24 18:15:37 +0200219 # additional check for IndexError branch (issue #19545)
220 with self.assertRaises(ValueError) as e:
221 time.strptime('19', '%Y %')
222 self.assertIs(e.exception.__suppress_context__, True)
Ezio Melotti0f389082013-04-04 02:09:20 +0300223
Fred Drakebc561982001-05-22 17:02:02 +0000224 def test_asctime(self):
225 time.asctime(time.gmtime(self.t))
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000226
227 # Max year is only limited by the size of C int.
Florent Xiclunabceb5282011-11-01 14:11:34 +0100228 for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
229 asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
230 self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
231 self.assertRaises(OverflowError, time.asctime,
232 (TIME_MAXYEAR + 1,) + (0,) * 8)
233 self.assertRaises(OverflowError, time.asctime,
234 (TIME_MINYEAR - 1,) + (0,) * 8)
Fred Drakebc561982001-05-22 17:02:02 +0000235 self.assertRaises(TypeError, time.asctime, 0)
Alexander Belopolskye2dc0822011-01-02 20:48:22 +0000236 self.assertRaises(TypeError, time.asctime, ())
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000237 self.assertRaises(TypeError, time.asctime, (0,) * 10)
Fred Drakebc561982001-05-22 17:02:02 +0000238
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000239 def test_asctime_bounding_check(self):
240 self._bounds_checking(time.asctime)
241
Georg Brandle10608c2011-01-02 22:33:43 +0000242 def test_ctime(self):
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000243 t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
244 self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
245 t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
246 self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000')
Victor Stinner1ac42612014-02-21 09:27:17 +0100247 for year in [-100, 100, 1000, 2000, 2050, 10000]:
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000248 try:
249 testval = time.mktime((year, 1, 10) + (0,)*6)
250 except (ValueError, OverflowError):
251 # If mktime fails, ctime will fail too. This may happen
252 # on some platforms.
253 pass
254 else:
255 self.assertEqual(time.ctime(testval)[20:], str(year))
Georg Brandle10608c2011-01-02 22:33:43 +0000256
Florent Xiclunae54371e2011-11-11 18:59:30 +0100257 @unittest.skipUnless(hasattr(time, "tzset"),
258 "time module has no attribute tzset")
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000259 def test_tzset(self):
Guido van Rossumd2b738e2003-03-15 12:01:52 +0000260
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000261 from os import environ
262
Tim Peters0eadaac2003-04-24 16:02:54 +0000263 # Epoch time of midnight Dec 25th 2002. Never DST in northern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000264 # hemisphere.
Tim Peters0eadaac2003-04-24 16:02:54 +0000265 xmas2002 = 1040774400.0
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000266
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000267 # These formats are correct for 2002, and possibly future years
268 # This format is the 'standard' as documented at:
269 # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
270 # They are also documented in the tzset(3) man page on most Unix
271 # systems.
Tim Peters0eadaac2003-04-24 16:02:54 +0000272 eastern = 'EST+05EDT,M4.1.0,M10.5.0'
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000273 victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
274 utc='UTC+0'
275
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000276 org_TZ = environ.get('TZ',None)
277 try:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000278 # Make sure we can switch to UTC time and results are correct
279 # Note that unknown timezones default to UTC.
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000280 # Note that altzone is undefined in UTC, as there is no DST
281 environ['TZ'] = eastern
282 time.tzset()
283 environ['TZ'] = utc
284 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000285 self.assertEqual(
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000286 time.gmtime(xmas2002), time.localtime(xmas2002)
287 )
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000288 self.assertEqual(time.daylight, 0)
289 self.assertEqual(time.timezone, 0)
290 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000291
292 # Make sure we can switch to US/Eastern
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000293 environ['TZ'] = eastern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000294 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000295 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
296 self.assertEqual(time.tzname, ('EST', 'EDT'))
297 self.assertEqual(len(time.tzname), 2)
298 self.assertEqual(time.daylight, 1)
299 self.assertEqual(time.timezone, 18000)
300 self.assertEqual(time.altzone, 14400)
301 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
302 self.assertEqual(len(time.tzname), 2)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000303
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000304 # Now go to the southern hemisphere.
305 environ['TZ'] = victoria
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000306 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000307 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
Victor Stinner0cd47902011-12-08 00:32:51 +0100308
309 # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100310 # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
311 # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
312 # on some operating systems (e.g. FreeBSD), which is wrong. See for
313 # example this bug:
314 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
Victor Stinner0cd47902011-12-08 00:32:51 +0100315 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100316 self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000317 self.assertEqual(len(time.tzname), 2)
318 self.assertEqual(time.daylight, 1)
319 self.assertEqual(time.timezone, -36000)
320 self.assertEqual(time.altzone, -39600)
321 self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000322
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000323 finally:
324 # Repair TZ environment variable in case any other tests
325 # rely on it.
326 if org_TZ is not None:
327 environ['TZ'] = org_TZ
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000328 elif 'TZ' in environ:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000329 del environ['TZ']
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000330 time.tzset()
Tim Peters0eadaac2003-04-24 16:02:54 +0000331
Tim Peters1b6f7a92004-06-20 02:50:16 +0000332 def test_insane_timestamps(self):
333 # It's possible that some platform maps time_t to double,
334 # and that this test will fail there. This test should
335 # exempt such platforms (provided they return reasonable
336 # results!).
337 for func in time.ctime, time.gmtime, time.localtime:
338 for unreasonable in -1e200, 1e200:
Victor Stinner5d272cc2012-03-13 13:35:55 +0100339 self.assertRaises(OverflowError, func, unreasonable)
Fred Drakebc561982001-05-22 17:02:02 +0000340
Fred Drakef901abd2004-08-03 17:58:55 +0000341 def test_ctime_without_arg(self):
342 # Not sure how to check the values, since the clock could tick
343 # at any time. Make sure these are at least accepted and
344 # don't raise errors.
345 time.ctime()
346 time.ctime(None)
347
348 def test_gmtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000349 gt0 = time.gmtime()
350 gt1 = time.gmtime(None)
351 t0 = time.mktime(gt0)
352 t1 = time.mktime(gt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000353 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000354
355 def test_localtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000356 lt0 = time.localtime()
357 lt1 = time.localtime(None)
358 t0 = time.mktime(lt0)
359 t1 = time.mktime(lt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000360 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000361
Florent Xiclunae54371e2011-11-11 18:59:30 +0100362 def test_mktime(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100363 # Issue #1726687
364 for t in (-2, -1, 0, 1):
Victor Stinner8c8b4e02014-02-21 23:54:32 +0100365 if sys.platform.startswith('aix') and t == -1:
366 # Issue #11188, #19748: mktime() returns -1 on error. On Linux,
367 # the tm_wday field is used as a sentinel () to detect if -1 is
368 # really an error or a valid timestamp. On AIX, tm_wday is
369 # unchanged even on success and so cannot be used as a
370 # sentinel.
371 continue
Florent Xiclunabceb5282011-11-01 14:11:34 +0100372 try:
373 tt = time.localtime(t)
Victor Stinner2cbae982012-01-27 00:50:33 +0100374 except (OverflowError, OSError):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100375 pass
376 else:
377 self.assertEqual(time.mktime(tt), t)
Florent Xiclunae54371e2011-11-11 18:59:30 +0100378
379 # Issue #13309: passing extreme values to mktime() or localtime()
380 # borks the glibc's internal timezone data.
381 @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
382 "disabled because of a bug in glibc. Issue #13309")
383 def test_mktime_error(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100384 # It may not be possible to reliably make mktime return error
385 # on all platfom. This will make sure that no other exception
386 # than OverflowError is raised for an extreme value.
Florent Xiclunae54371e2011-11-11 18:59:30 +0100387 tt = time.gmtime(self.t)
388 tzname = time.strftime('%Z', tt)
389 self.assertNotEqual(tzname, 'LMT')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100390 try:
391 time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
392 except OverflowError:
393 pass
Florent Xiclunae54371e2011-11-11 18:59:30 +0100394 self.assertEqual(time.strftime('%Z', tt), tzname)
Florent Xiclunabceb5282011-11-01 14:11:34 +0100395
Victor Stinnerec895392012-04-29 02:41:27 +0200396 @unittest.skipUnless(hasattr(time, 'monotonic'),
397 'need time.monotonic')
398 def test_monotonic(self):
Victor Stinner6c861812013-11-23 00:15:27 +0100399 # monotonic() should not go backward
400 times = [time.monotonic() for n in range(100)]
401 t1 = times[0]
402 for t2 in times[1:]:
403 self.assertGreaterEqual(t2, t1, "times=%s" % times)
404 t1 = t2
405
406 # monotonic() includes time elapsed during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200407 t1 = time.monotonic()
Victor Stinnera9c99a62013-07-03 23:07:37 +0200408 time.sleep(0.5)
Victor Stinnerec895392012-04-29 02:41:27 +0200409 t2 = time.monotonic()
Victor Stinner2dd254d2012-01-20 02:24:18 +0100410 dt = t2 - t1
Victor Stinner8b302012012-02-07 23:29:46 +0100411 self.assertGreater(t2, t1)
Zachary Ware487aedb2014-01-02 09:41:10 -0600412 # Issue #20101: On some Windows machines, dt may be slightly low
413 self.assertTrue(0.45 <= dt <= 1.0, dt)
Antoine Pitrou391166f2012-01-18 22:35:21 +0100414
Victor Stinner6c861812013-11-23 00:15:27 +0100415 # monotonic() is a monotonic but non adjustable clock
Victor Stinnerec895392012-04-29 02:41:27 +0200416 info = time.get_clock_info('monotonic')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400417 self.assertTrue(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +0200418 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200419
420 def test_perf_counter(self):
421 time.perf_counter()
422
423 def test_process_time(self):
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200424 # process_time() should not include time spend during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200425 start = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200426 time.sleep(0.100)
Victor Stinnerec895392012-04-29 02:41:27 +0200427 stop = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200428 # use 20 ms because process_time() has usually a resolution of 15 ms
429 # on Windows
430 self.assertLess(stop - start, 0.020)
Victor Stinnerec895392012-04-29 02:41:27 +0200431
432 info = time.get_clock_info('process_time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400433 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200434 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200435
Victor Stinnerec895392012-04-29 02:41:27 +0200436 @unittest.skipUnless(hasattr(time, 'monotonic'),
437 'need time.monotonic')
438 @unittest.skipUnless(hasattr(time, 'clock_settime'),
439 'need time.clock_settime')
440 def test_monotonic_settime(self):
441 t1 = time.monotonic()
442 realtime = time.clock_gettime(time.CLOCK_REALTIME)
443 # jump backward with an offset of 1 hour
Victor Stinner071eca32012-03-15 01:17:09 +0100444 try:
Victor Stinnerec895392012-04-29 02:41:27 +0200445 time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
446 except PermissionError as err:
447 self.skipTest(err)
448 t2 = time.monotonic()
449 time.clock_settime(time.CLOCK_REALTIME, realtime)
450 # monotonic must not be affected by system clock updates
Victor Stinner071eca32012-03-15 01:17:09 +0100451 self.assertGreaterEqual(t2, t1)
452
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100453 def test_localtime_failure(self):
454 # Issue #13847: check for localtime() failure
Victor Stinner53d36452012-01-27 01:03:25 +0100455 invalid_time_t = None
456 for time_t in (-1, 2**30, 2**33, 2**60):
457 try:
458 time.localtime(time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100459 except OverflowError:
460 self.skipTest("need 64-bit time_t")
Victor Stinner53d36452012-01-27 01:03:25 +0100461 except OSError:
462 invalid_time_t = time_t
463 break
464 if invalid_time_t is None:
465 self.skipTest("unable to find an invalid time_t value")
466
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100467 self.assertRaises(OSError, time.localtime, invalid_time_t)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100468 self.assertRaises(OSError, time.ctime, invalid_time_t)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100469
Victor Stinnerec895392012-04-29 02:41:27 +0200470 def test_get_clock_info(self):
471 clocks = ['clock', 'perf_counter', 'process_time', 'time']
472 if hasattr(time, 'monotonic'):
473 clocks.append('monotonic')
474
475 for name in clocks:
476 info = time.get_clock_info(name)
477 #self.assertIsInstance(info, dict)
478 self.assertIsInstance(info.implementation, str)
479 self.assertNotEqual(info.implementation, '')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400480 self.assertIsInstance(info.monotonic, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200481 self.assertIsInstance(info.resolution, float)
482 # 0.0 < resolution <= 1.0
483 self.assertGreater(info.resolution, 0.0)
484 self.assertLessEqual(info.resolution, 1.0)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200485 self.assertIsInstance(info.adjustable, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200486
487 self.assertRaises(ValueError, time.get_clock_info, 'xxx')
488
489
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000490class TestLocale(unittest.TestCase):
491 def setUp(self):
492 self.oldloc = locale.setlocale(locale.LC_ALL)
Fred Drake2e2be372001-09-20 21:33:42 +0000493
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000494 def tearDown(self):
495 locale.setlocale(locale.LC_ALL, self.oldloc)
496
Martin v. Löwisa6a9c4d2009-05-30 06:15:30 +0000497 def test_bug_3061(self):
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000498 try:
499 tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
500 except locale.Error:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600501 self.skipTest('could not set locale.LC_ALL to fr_FR')
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000502 # This should not cause an exception
503 time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
504
Victor Stinner73ea29c2011-01-08 01:56:31 +0000505
Victor Stinner73ea29c2011-01-08 01:56:31 +0000506class _TestAsctimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100507 _format = '%d'
508
Victor Stinner73ea29c2011-01-08 01:56:31 +0000509 def yearstr(self, y):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000510 return time.asctime((y,) + (0,) * 8).split()[-1]
Alexander Belopolskya6867252011-01-05 23:00:47 +0000511
Victor Stinner73ea29c2011-01-08 01:56:31 +0000512 def test_large_year(self):
Victor Stinner73691322011-01-08 02:00:24 +0000513 # Check that it doesn't crash for year > 9999
Victor Stinner73ea29c2011-01-08 01:56:31 +0000514 self.assertEqual(self.yearstr(12345), '12345')
515 self.assertEqual(self.yearstr(123456789), '123456789')
516
517class _TestStrftimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100518
519 # Issue 13305: For years < 1000, the value is not always
520 # padded to 4 digits across platforms. The C standard
521 # assumes year >= 1900, so it does not specify the number
522 # of digits.
523
524 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
525 _format = '%04d'
526 else:
527 _format = '%d'
528
Victor Stinner73ea29c2011-01-08 01:56:31 +0000529 def yearstr(self, y):
Florent Xicluna49ce0682011-11-01 12:56:14 +0100530 return time.strftime('%Y', (y,) + (0,) * 8)
531
532 def test_4dyear(self):
533 # Check that we can return the zero padded value.
534 if self._format == '%04d':
535 self.test_year('%04d')
536 else:
537 def year4d(y):
538 return time.strftime('%4Y', (y,) + (0,) * 8)
539 self.test_year('%04d', func=year4d)
540
Florent Xiclunabceb5282011-11-01 14:11:34 +0100541 def skip_if_not_supported(y):
542 msg = "strftime() is limited to [1; 9999] with Visual Studio"
543 # Check that it doesn't crash for year > 9999
544 try:
545 time.strftime('%Y', (y,) + (0,) * 8)
546 except ValueError:
547 cond = False
548 else:
549 cond = True
550 return unittest.skipUnless(cond, msg)
551
552 @skip_if_not_supported(10000)
553 def test_large_year(self):
554 return super().test_large_year()
555
556 @skip_if_not_supported(0)
557 def test_negative(self):
558 return super().test_negative()
559
560 del skip_if_not_supported
561
562
Ezio Melotti3836d702013-04-11 20:29:42 +0300563class _Test4dYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100564 _format = '%d'
565
566 def test_year(self, fmt=None, func=None):
567 fmt = fmt or self._format
568 func = func or self.yearstr
569 self.assertEqual(func(1), fmt % 1)
570 self.assertEqual(func(68), fmt % 68)
571 self.assertEqual(func(69), fmt % 69)
572 self.assertEqual(func(99), fmt % 99)
573 self.assertEqual(func(999), fmt % 999)
574 self.assertEqual(func(9999), fmt % 9999)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000575
576 def test_large_year(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100577 self.assertEqual(self.yearstr(12345), '12345')
Victor Stinner13ed2ea2011-03-21 02:11:01 +0100578 self.assertEqual(self.yearstr(123456789), '123456789')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100579 self.assertEqual(self.yearstr(TIME_MAXYEAR), str(TIME_MAXYEAR))
580 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000581
Victor Stinner301f1212011-01-08 03:06:52 +0000582 def test_negative(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100583 self.assertEqual(self.yearstr(-1), self._format % -1)
Victor Stinner301f1212011-01-08 03:06:52 +0000584 self.assertEqual(self.yearstr(-1234), '-1234')
585 self.assertEqual(self.yearstr(-123456), '-123456')
Florent Xiclunad1bd7f72011-11-01 23:42:05 +0100586 self.assertEqual(self.yearstr(-123456789), str(-123456789))
587 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
Florent Xicluna2fbc1852011-11-02 08:13:43 +0100588 self.assertEqual(self.yearstr(TIME_MINYEAR + 1900), str(TIME_MINYEAR + 1900))
589 # Issue #13312: it may return wrong value for year < TIME_MINYEAR + 1900
590 # Skip the value test, but check that no error is raised
591 self.yearstr(TIME_MINYEAR)
Florent Xiclunae2a732e2011-11-02 01:28:17 +0100592 # self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
Florent Xiclunabceb5282011-11-01 14:11:34 +0100593 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
Victor Stinner301f1212011-01-08 03:06:52 +0000594
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000595
Ezio Melotti3836d702013-04-11 20:29:42 +0300596class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner73ea29c2011-01-08 01:56:31 +0000597 pass
598
Ezio Melotti3836d702013-04-11 20:29:42 +0300599class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner301f1212011-01-08 03:06:52 +0000600 pass
Victor Stinner73ea29c2011-01-08 01:56:31 +0000601
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000602
Victor Stinner643cd682012-03-02 22:54:03 +0100603class TestPytime(unittest.TestCase):
Victor Stinner5d272cc2012-03-13 13:35:55 +0100604 def setUp(self):
605 self.invalid_values = (
606 -(2 ** 100), 2 ** 100,
607 -(2.0 ** 100.0), 2.0 ** 100.0,
608 )
609
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200610 @support.cpython_only
Victor Stinner5d272cc2012-03-13 13:35:55 +0100611 def test_time_t(self):
612 from _testcapi import pytime_object_to_time_t
Victor Stinner3c1b3792014-02-17 00:02:43 +0100613 for obj, time_t, rnd in (
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200614 # Round towards minus infinity (-inf)
615 (0, 0, _PyTime.ROUND_FLOOR),
616 (-1, -1, _PyTime.ROUND_FLOOR),
617 (-1.0, -1, _PyTime.ROUND_FLOOR),
618 (-1.9, -2, _PyTime.ROUND_FLOOR),
619 (1.0, 1, _PyTime.ROUND_FLOOR),
620 (1.9, 1, _PyTime.ROUND_FLOOR),
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200621 # Round towards infinity (+inf)
622 (0, 0, _PyTime.ROUND_CEILING),
623 (-1, -1, _PyTime.ROUND_CEILING),
624 (-1.0, -1, _PyTime.ROUND_CEILING),
625 (-1.9, -1, _PyTime.ROUND_CEILING),
626 (1.0, 1, _PyTime.ROUND_CEILING),
627 (1.9, 2, _PyTime.ROUND_CEILING),
Victor Stinner5d272cc2012-03-13 13:35:55 +0100628 ):
Victor Stinner3c1b3792014-02-17 00:02:43 +0100629 self.assertEqual(pytime_object_to_time_t(obj, rnd), time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100630
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200631 rnd = _PyTime.ROUND_FLOOR
Victor Stinner5d272cc2012-03-13 13:35:55 +0100632 for invalid in self.invalid_values:
Victor Stinner3c1b3792014-02-17 00:02:43 +0100633 self.assertRaises(OverflowError,
634 pytime_object_to_time_t, invalid, rnd)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100635
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200636 @support.cpython_only
Victor Stinner643cd682012-03-02 22:54:03 +0100637 def test_timespec(self):
638 from _testcapi import pytime_object_to_timespec
Victor Stinner3c1b3792014-02-17 00:02:43 +0100639 for obj, timespec, rnd in (
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200640 # Round towards minus infinity (-inf)
641 (0, (0, 0), _PyTime.ROUND_FLOOR),
642 (-1, (-1, 0), _PyTime.ROUND_FLOOR),
643 (-1.0, (-1, 0), _PyTime.ROUND_FLOOR),
644 (1e-9, (0, 1), _PyTime.ROUND_FLOOR),
645 (1e-10, (0, 0), _PyTime.ROUND_FLOOR),
646 (-1e-9, (-1, 999999999), _PyTime.ROUND_FLOOR),
647 (-1e-10, (-1, 999999999), _PyTime.ROUND_FLOOR),
648 (-1.2, (-2, 800000000), _PyTime.ROUND_FLOOR),
649 (0.9999999999, (0, 999999999), _PyTime.ROUND_FLOOR),
650 (1.1234567890, (1, 123456789), _PyTime.ROUND_FLOOR),
651 (1.1234567899, (1, 123456789), _PyTime.ROUND_FLOOR),
652 (-1.1234567890, (-2, 876543211), _PyTime.ROUND_FLOOR),
653 (-1.1234567891, (-2, 876543210), _PyTime.ROUND_FLOOR),
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200654 # Round towards infinity (+inf)
655 (0, (0, 0), _PyTime.ROUND_CEILING),
656 (-1, (-1, 0), _PyTime.ROUND_CEILING),
657 (-1.0, (-1, 0), _PyTime.ROUND_CEILING),
658 (1e-9, (0, 1), _PyTime.ROUND_CEILING),
659 (1e-10, (0, 1), _PyTime.ROUND_CEILING),
660 (-1e-9, (-1, 999999999), _PyTime.ROUND_CEILING),
661 (-1e-10, (0, 0), _PyTime.ROUND_CEILING),
662 (-1.2, (-2, 800000000), _PyTime.ROUND_CEILING),
663 (0.9999999999, (1, 0), _PyTime.ROUND_CEILING),
664 (1.1234567890, (1, 123456790), _PyTime.ROUND_CEILING),
665 (1.1234567899, (1, 123456790), _PyTime.ROUND_CEILING),
666 (-1.1234567890, (-2, 876543211), _PyTime.ROUND_CEILING),
667 (-1.1234567891, (-2, 876543211), _PyTime.ROUND_CEILING),
Victor Stinner643cd682012-03-02 22:54:03 +0100668 ):
Victor Stinner3c1b3792014-02-17 00:02:43 +0100669 with self.subTest(obj=obj, round=rnd, timespec=timespec):
670 self.assertEqual(pytime_object_to_timespec(obj, rnd), timespec)
Victor Stinner643cd682012-03-02 22:54:03 +0100671
Victor Stinnerbcdd7772015-03-30 03:52:49 +0200672 rnd = _PyTime.ROUND_FLOOR
Victor Stinner5d272cc2012-03-13 13:35:55 +0100673 for invalid in self.invalid_values:
Victor Stinner3c1b3792014-02-17 00:02:43 +0100674 self.assertRaises(OverflowError,
675 pytime_object_to_timespec, invalid, rnd)
Victor Stinner643cd682012-03-02 22:54:03 +0100676
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400677 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
678 def test_localtime_timezone(self):
Victor Stinner643cd682012-03-02 22:54:03 +0100679
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400680 # Get the localtime and examine it for the offset and zone.
681 lt = time.localtime()
682 self.assertTrue(hasattr(lt, "tm_gmtoff"))
683 self.assertTrue(hasattr(lt, "tm_zone"))
684
685 # See if the offset and zone are similar to the module
686 # attributes.
687 if lt.tm_gmtoff is None:
688 self.assertTrue(not hasattr(time, "timezone"))
689 else:
690 self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
691 if lt.tm_zone is None:
692 self.assertTrue(not hasattr(time, "tzname"))
693 else:
694 self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
695
696 # Try and make UNIX times from the localtime and a 9-tuple
697 # created from the localtime. Test to see that the times are
698 # the same.
699 t = time.mktime(lt); t9 = time.mktime(lt[:9])
700 self.assertEqual(t, t9)
701
702 # Make localtimes from the UNIX times and compare them to
703 # the original localtime, thus making a round trip.
704 new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
705 self.assertEqual(new_lt, lt)
706 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
707 self.assertEqual(new_lt.tm_zone, lt.tm_zone)
708 self.assertEqual(new_lt9, lt)
709 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
710 self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
711
712 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
713 def test_strptime_timezone(self):
714 t = time.strptime("UTC", "%Z")
715 self.assertEqual(t.tm_zone, 'UTC')
716 t = time.strptime("+0500", "%z")
717 self.assertEqual(t.tm_gmtoff, 5 * 3600)
718
719 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
720 def test_short_times(self):
721
722 import pickle
723
724 # Load a short time structure using pickle.
725 st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
726 lt = pickle.loads(st)
727 self.assertIs(lt.tm_gmtoff, None)
728 self.assertIs(lt.tm_zone, None)
Victor Stinner643cd682012-03-02 22:54:03 +0100729
Fred Drake2e2be372001-09-20 21:33:42 +0000730
Victor Stinner34dc0f42015-03-27 18:19:03 +0100731@unittest.skipUnless(_testcapi is not None,
732 'need the _testcapi module')
Victor Stinner992c43f2015-03-27 17:12:45 +0100733class TestPyTime_t(unittest.TestCase):
734 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()