blob: 44bcb943cba975613b492b5546ecffd874b0e1c6 [file] [log] [blame]
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001from test import support
Barry Warsawb0c22321996-12-06 23:30:07 +00002import time
Fred Drakebc561982001-05-22 17:02:02 +00003import unittest
Victor Stinner4195b5c2012-02-08 23:03:19 +01004import locale
5import sysconfig
6import sys
7import platform
Victor Stinnerec895392012-04-29 02:41:27 +02008try:
9 import threading
10except ImportError:
11 threading = None
Barry Warsawb0c22321996-12-06 23:30:07 +000012
Florent Xiclunabceb5282011-11-01 14:11:34 +010013# Max year is only limited by the size of C int.
14SIZEOF_INT = sysconfig.get_config_var('SIZEOF_INT') or 4
15TIME_MAXYEAR = (1 << 8 * SIZEOF_INT - 1) - 1
16TIME_MINYEAR = -TIME_MAXYEAR - 1
17
18
Fred Drakebc561982001-05-22 17:02:02 +000019class TimeTestCase(unittest.TestCase):
Barry Warsawb0c22321996-12-06 23:30:07 +000020
Fred Drakebc561982001-05-22 17:02:02 +000021 def setUp(self):
22 self.t = time.time()
Barry Warsawb0c22321996-12-06 23:30:07 +000023
Fred Drakebc561982001-05-22 17:02:02 +000024 def test_data_attributes(self):
25 time.altzone
26 time.daylight
27 time.timezone
28 time.tzname
Barry Warsawb0c22321996-12-06 23:30:07 +000029
Victor Stinnerec895392012-04-29 02:41:27 +020030 def test_time(self):
31 time.time()
32 info = time.get_clock_info('time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040033 self.assertFalse(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +020034 self.assertTrue(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020035
Fred Drakebc561982001-05-22 17:02:02 +000036 def test_clock(self):
37 time.clock()
Barry Warsawb0c22321996-12-06 23:30:07 +000038
Victor Stinnerec895392012-04-29 02:41:27 +020039 info = time.get_clock_info('clock')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040040 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +020041 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020042
Victor Stinnere0be4232011-10-25 13:06:09 +020043 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
44 'need time.clock_gettime()')
45 def test_clock_realtime(self):
46 time.clock_gettime(time.CLOCK_REALTIME)
47
48 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
49 'need time.clock_gettime()')
50 @unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'),
51 'need time.CLOCK_MONOTONIC')
52 def test_clock_monotonic(self):
53 a = time.clock_gettime(time.CLOCK_MONOTONIC)
54 b = time.clock_gettime(time.CLOCK_MONOTONIC)
55 self.assertLessEqual(a, b)
56
57 @unittest.skipUnless(hasattr(time, 'clock_getres'),
58 'need time.clock_getres()')
59 def test_clock_getres(self):
60 res = time.clock_getres(time.CLOCK_REALTIME)
61 self.assertGreater(res, 0.0)
62 self.assertLessEqual(res, 1.0)
63
Victor Stinner30d79472012-04-03 00:45:07 +020064 @unittest.skipUnless(hasattr(time, 'clock_settime'),
65 'need time.clock_settime()')
66 def test_clock_settime(self):
67 t = time.clock_gettime(time.CLOCK_REALTIME)
68 try:
69 time.clock_settime(time.CLOCK_REALTIME, t)
70 except PermissionError:
71 pass
72
Victor Stinnerec895392012-04-29 02:41:27 +020073 if hasattr(time, 'CLOCK_MONOTONIC'):
74 self.assertRaises(OSError,
75 time.clock_settime, time.CLOCK_MONOTONIC, 0)
Victor Stinner30d79472012-04-03 00:45:07 +020076
Fred Drakebc561982001-05-22 17:02:02 +000077 def test_conversions(self):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +000078 self.assertEqual(time.ctime(self.t),
79 time.asctime(time.localtime(self.t)))
80 self.assertEqual(int(time.mktime(time.localtime(self.t))),
81 int(self.t))
Fred Drakebc561982001-05-22 17:02:02 +000082
83 def test_sleep(self):
Victor Stinner7f53a502011-07-05 22:00:25 +020084 self.assertRaises(ValueError, time.sleep, -2)
85 self.assertRaises(ValueError, time.sleep, -1)
Fred Drakebc561982001-05-22 17:02:02 +000086 time.sleep(1.2)
87
88 def test_strftime(self):
89 tt = time.gmtime(self.t)
90 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
91 'j', 'm', 'M', 'p', 'S',
92 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
93 format = ' %' + directive
94 try:
95 time.strftime(format, tt)
96 except ValueError:
97 self.fail('conversion specifier: %r failed.' % format)
98
Senthil Kumaran8f377a32011-04-06 12:54:06 +080099 # Issue #10762: Guard against invalid/non-supported format string
100 # so that Python don't crash (Windows crashes when the format string
101 # input to [w]strftime is not kosher.
102 if sys.platform.startswith('win'):
103 with self.assertRaises(ValueError):
104 time.strftime('%f')
105
Florent Xicluna49ce0682011-11-01 12:56:14 +0100106 def _bounds_checking(self, func):
Brett Cannond1080a32004-03-02 04:38:10 +0000107 # Make sure that strftime() checks the bounds of the various parts
Florent Xicluna49ce0682011-11-01 12:56:14 +0100108 # of the time tuple (0 is valid for *all* values).
Brett Cannond1080a32004-03-02 04:38:10 +0000109
Victor Stinner73ea29c2011-01-08 01:56:31 +0000110 # The year field is tested by other test cases above
111
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000112 # Check month [1, 12] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100113 func((1900, 0, 1, 0, 0, 0, 0, 1, -1))
114 func((1900, 12, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000115 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000116 (1900, -1, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000117 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000118 (1900, 13, 1, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000119 # Check day of month [1, 31] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100120 func((1900, 1, 0, 0, 0, 0, 0, 1, -1))
121 func((1900, 1, 31, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000122 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000123 (1900, 1, -1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000124 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000125 (1900, 1, 32, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000126 # Check hour [0, 23]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100127 func((1900, 1, 1, 23, 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, 1, 1, -1, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000130 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000131 (1900, 1, 1, 24, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000132 # Check minute [0, 59]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100133 func((1900, 1, 1, 0, 59, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000134 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000135 (1900, 1, 1, 0, -1, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000136 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000137 (1900, 1, 1, 0, 60, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000138 # Check second [0, 61]
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000139 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000140 (1900, 1, 1, 0, 0, -1, 0, 1, -1))
141 # C99 only requires allowing for one leap second, but Python's docs say
142 # allow two leap seconds (0..61)
Florent Xicluna49ce0682011-11-01 12:56:14 +0100143 func((1900, 1, 1, 0, 0, 60, 0, 1, -1))
144 func((1900, 1, 1, 0, 0, 61, 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, 0, 62, 0, 1, -1))
147 # No check for upper-bound day of week;
148 # value forced into range by a ``% 7`` calculation.
149 # Start check at -2 since gettmarg() increments value before taking
150 # modulo.
Florent Xicluna49ce0682011-11-01 12:56:14 +0100151 self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)),
152 func((1900, 1, 1, 0, 0, 0, +6, 1, -1)))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000153 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000154 (1900, 1, 1, 0, 0, 0, -2, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000155 # Check day of the year [1, 366] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100156 func((1900, 1, 1, 0, 0, 0, 0, 0, -1))
157 func((1900, 1, 1, 0, 0, 0, 0, 366, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000158 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000159 (1900, 1, 1, 0, 0, 0, 0, -1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000160 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000161 (1900, 1, 1, 0, 0, 0, 0, 367, -1))
Brett Cannond1080a32004-03-02 04:38:10 +0000162
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000163 def test_strftime_bounding_check(self):
164 self._bounds_checking(lambda tup: time.strftime('', tup))
165
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000166 def test_default_values_for_zero(self):
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400167 # Make sure that using all zeros uses the proper default
168 # values. No test for daylight savings since strftime() does
169 # not change output based on its value and no test for year
170 # because systems vary in their support for year 0.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000171 expected = "2000 01 01 00 00 00 1 001"
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000172 with support.check_warnings():
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400173 result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000174 self.assertEqual(expected, result)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000175
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000176 def test_strptime(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000177 # Should be able to go round-trip from strftime to strptime without
Andrew Svetlov737fb892012-12-18 21:14:22 +0200178 # raising an exception.
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000179 tt = time.gmtime(self.t)
180 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
181 'j', 'm', 'M', 'p', 'S',
182 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000183 format = '%' + directive
184 strf_output = time.strftime(format, tt)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000185 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000186 time.strptime(strf_output, format)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000187 except ValueError:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000188 self.fail("conversion specifier %r failed with '%s' input." %
189 (format, strf_output))
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000190
Brett Cannon7f6b4f82009-03-30 21:30:26 +0000191 def test_strptime_bytes(self):
192 # Make sure only strings are accepted as arguments to strptime.
193 self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
194 self.assertRaises(TypeError, time.strptime, '2009', b'%Y')
195
Ezio Melotti0f389082013-04-04 02:09:20 +0300196 def test_strptime_exception_context(self):
197 # check that this doesn't chain exceptions needlessly (see #17572)
198 with self.assertRaises(ValueError) as e:
199 time.strptime('', '%D')
200 self.assertIs(e.exception.__suppress_context__, True)
Serhiy Storchakacdac3022013-11-24 18:15:37 +0200201 # additional check for IndexError branch (issue #19545)
202 with self.assertRaises(ValueError) as e:
203 time.strptime('19', '%Y %')
204 self.assertIs(e.exception.__suppress_context__, True)
Ezio Melotti0f389082013-04-04 02:09:20 +0300205
Fred Drakebc561982001-05-22 17:02:02 +0000206 def test_asctime(self):
207 time.asctime(time.gmtime(self.t))
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000208
209 # Max year is only limited by the size of C int.
Florent Xiclunabceb5282011-11-01 14:11:34 +0100210 for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
211 asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
212 self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
213 self.assertRaises(OverflowError, time.asctime,
214 (TIME_MAXYEAR + 1,) + (0,) * 8)
215 self.assertRaises(OverflowError, time.asctime,
216 (TIME_MINYEAR - 1,) + (0,) * 8)
Fred Drakebc561982001-05-22 17:02:02 +0000217 self.assertRaises(TypeError, time.asctime, 0)
Alexander Belopolskye2dc0822011-01-02 20:48:22 +0000218 self.assertRaises(TypeError, time.asctime, ())
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000219 self.assertRaises(TypeError, time.asctime, (0,) * 10)
Fred Drakebc561982001-05-22 17:02:02 +0000220
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000221 def test_asctime_bounding_check(self):
222 self._bounds_checking(time.asctime)
223
Georg Brandle10608c2011-01-02 22:33:43 +0000224 def test_ctime(self):
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000225 t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
226 self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
227 t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
228 self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000')
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000229 for year in [-100, 100, 1000, 2000, 10000]:
230 try:
231 testval = time.mktime((year, 1, 10) + (0,)*6)
232 except (ValueError, OverflowError):
233 # If mktime fails, ctime will fail too. This may happen
234 # on some platforms.
235 pass
236 else:
237 self.assertEqual(time.ctime(testval)[20:], str(year))
Georg Brandle10608c2011-01-02 22:33:43 +0000238
Florent Xiclunae54371e2011-11-11 18:59:30 +0100239 @unittest.skipUnless(hasattr(time, "tzset"),
240 "time module has no attribute tzset")
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000241 def test_tzset(self):
Guido van Rossumd2b738e2003-03-15 12:01:52 +0000242
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000243 from os import environ
244
Tim Peters0eadaac2003-04-24 16:02:54 +0000245 # Epoch time of midnight Dec 25th 2002. Never DST in northern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000246 # hemisphere.
Tim Peters0eadaac2003-04-24 16:02:54 +0000247 xmas2002 = 1040774400.0
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000248
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000249 # These formats are correct for 2002, and possibly future years
250 # This format is the 'standard' as documented at:
251 # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
252 # They are also documented in the tzset(3) man page on most Unix
253 # systems.
Tim Peters0eadaac2003-04-24 16:02:54 +0000254 eastern = 'EST+05EDT,M4.1.0,M10.5.0'
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000255 victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
256 utc='UTC+0'
257
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000258 org_TZ = environ.get('TZ',None)
259 try:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000260 # Make sure we can switch to UTC time and results are correct
261 # Note that unknown timezones default to UTC.
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000262 # Note that altzone is undefined in UTC, as there is no DST
263 environ['TZ'] = eastern
264 time.tzset()
265 environ['TZ'] = utc
266 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000267 self.assertEqual(
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000268 time.gmtime(xmas2002), time.localtime(xmas2002)
269 )
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000270 self.assertEqual(time.daylight, 0)
271 self.assertEqual(time.timezone, 0)
272 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000273
274 # Make sure we can switch to US/Eastern
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000275 environ['TZ'] = eastern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000276 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000277 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
278 self.assertEqual(time.tzname, ('EST', 'EDT'))
279 self.assertEqual(len(time.tzname), 2)
280 self.assertEqual(time.daylight, 1)
281 self.assertEqual(time.timezone, 18000)
282 self.assertEqual(time.altzone, 14400)
283 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
284 self.assertEqual(len(time.tzname), 2)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000285
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000286 # Now go to the southern hemisphere.
287 environ['TZ'] = victoria
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000288 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000289 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
Victor Stinner0cd47902011-12-08 00:32:51 +0100290
291 # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100292 # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
293 # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
294 # on some operating systems (e.g. FreeBSD), which is wrong. See for
295 # example this bug:
296 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
Victor Stinner0cd47902011-12-08 00:32:51 +0100297 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100298 self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000299 self.assertEqual(len(time.tzname), 2)
300 self.assertEqual(time.daylight, 1)
301 self.assertEqual(time.timezone, -36000)
302 self.assertEqual(time.altzone, -39600)
303 self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000304
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000305 finally:
306 # Repair TZ environment variable in case any other tests
307 # rely on it.
308 if org_TZ is not None:
309 environ['TZ'] = org_TZ
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000310 elif 'TZ' in environ:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000311 del environ['TZ']
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000312 time.tzset()
Tim Peters0eadaac2003-04-24 16:02:54 +0000313
Tim Peters1b6f7a92004-06-20 02:50:16 +0000314 def test_insane_timestamps(self):
315 # It's possible that some platform maps time_t to double,
316 # and that this test will fail there. This test should
317 # exempt such platforms (provided they return reasonable
318 # results!).
319 for func in time.ctime, time.gmtime, time.localtime:
320 for unreasonable in -1e200, 1e200:
Victor Stinner5d272cc2012-03-13 13:35:55 +0100321 self.assertRaises(OverflowError, func, unreasonable)
Fred Drakebc561982001-05-22 17:02:02 +0000322
Fred Drakef901abd2004-08-03 17:58:55 +0000323 def test_ctime_without_arg(self):
324 # Not sure how to check the values, since the clock could tick
325 # at any time. Make sure these are at least accepted and
326 # don't raise errors.
327 time.ctime()
328 time.ctime(None)
329
330 def test_gmtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000331 gt0 = time.gmtime()
332 gt1 = time.gmtime(None)
333 t0 = time.mktime(gt0)
334 t1 = time.mktime(gt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000335 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000336
337 def test_localtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000338 lt0 = time.localtime()
339 lt1 = time.localtime(None)
340 t0 = time.mktime(lt0)
341 t1 = time.mktime(lt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000342 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000343
Florent Xiclunae54371e2011-11-11 18:59:30 +0100344 def test_mktime(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100345 # Issue #1726687
346 for t in (-2, -1, 0, 1):
347 try:
348 tt = time.localtime(t)
Victor Stinner2cbae982012-01-27 00:50:33 +0100349 except (OverflowError, OSError):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100350 pass
351 else:
352 self.assertEqual(time.mktime(tt), t)
Florent Xiclunae54371e2011-11-11 18:59:30 +0100353
354 # Issue #13309: passing extreme values to mktime() or localtime()
355 # borks the glibc's internal timezone data.
356 @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
357 "disabled because of a bug in glibc. Issue #13309")
358 def test_mktime_error(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100359 # It may not be possible to reliably make mktime return error
360 # on all platfom. This will make sure that no other exception
361 # than OverflowError is raised for an extreme value.
Florent Xiclunae54371e2011-11-11 18:59:30 +0100362 tt = time.gmtime(self.t)
363 tzname = time.strftime('%Z', tt)
364 self.assertNotEqual(tzname, 'LMT')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100365 try:
366 time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
367 except OverflowError:
368 pass
Florent Xiclunae54371e2011-11-11 18:59:30 +0100369 self.assertEqual(time.strftime('%Z', tt), tzname)
Florent Xiclunabceb5282011-11-01 14:11:34 +0100370
Victor Stinnerec895392012-04-29 02:41:27 +0200371 @unittest.skipUnless(hasattr(time, 'monotonic'),
372 'need time.monotonic')
373 def test_monotonic(self):
Victor Stinner6c861812013-11-23 00:15:27 +0100374 # monotonic() should not go backward
375 times = [time.monotonic() for n in range(100)]
376 t1 = times[0]
377 for t2 in times[1:]:
378 self.assertGreaterEqual(t2, t1, "times=%s" % times)
379 t1 = t2
380
381 # monotonic() includes time elapsed during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200382 t1 = time.monotonic()
Victor Stinnera9c99a62013-07-03 23:07:37 +0200383 time.sleep(0.5)
Victor Stinnerec895392012-04-29 02:41:27 +0200384 t2 = time.monotonic()
Victor Stinner2dd254d2012-01-20 02:24:18 +0100385 dt = t2 - t1
Victor Stinner8b302012012-02-07 23:29:46 +0100386 self.assertGreater(t2, t1)
Victor Stinnera9c99a62013-07-03 23:07:37 +0200387 self.assertAlmostEqual(dt, 0.5, delta=0.2)
Antoine Pitrou391166f2012-01-18 22:35:21 +0100388
Victor Stinner6c861812013-11-23 00:15:27 +0100389 # monotonic() is a monotonic but non adjustable clock
Victor Stinnerec895392012-04-29 02:41:27 +0200390 info = time.get_clock_info('monotonic')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400391 self.assertTrue(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +0200392 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200393
394 def test_perf_counter(self):
395 time.perf_counter()
396
397 def test_process_time(self):
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200398 # process_time() should not include time spend during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200399 start = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200400 time.sleep(0.100)
Victor Stinnerec895392012-04-29 02:41:27 +0200401 stop = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200402 # use 20 ms because process_time() has usually a resolution of 15 ms
403 # on Windows
404 self.assertLess(stop - start, 0.020)
Victor Stinnerec895392012-04-29 02:41:27 +0200405
406 info = time.get_clock_info('process_time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400407 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200408 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200409
Victor Stinnerec895392012-04-29 02:41:27 +0200410 @unittest.skipUnless(hasattr(time, 'monotonic'),
411 'need time.monotonic')
412 @unittest.skipUnless(hasattr(time, 'clock_settime'),
413 'need time.clock_settime')
414 def test_monotonic_settime(self):
415 t1 = time.monotonic()
416 realtime = time.clock_gettime(time.CLOCK_REALTIME)
417 # jump backward with an offset of 1 hour
Victor Stinner071eca32012-03-15 01:17:09 +0100418 try:
Victor Stinnerec895392012-04-29 02:41:27 +0200419 time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
420 except PermissionError as err:
421 self.skipTest(err)
422 t2 = time.monotonic()
423 time.clock_settime(time.CLOCK_REALTIME, realtime)
424 # monotonic must not be affected by system clock updates
Victor Stinner071eca32012-03-15 01:17:09 +0100425 self.assertGreaterEqual(t2, t1)
426
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100427 def test_localtime_failure(self):
428 # Issue #13847: check for localtime() failure
Victor Stinner53d36452012-01-27 01:03:25 +0100429 invalid_time_t = None
430 for time_t in (-1, 2**30, 2**33, 2**60):
431 try:
432 time.localtime(time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100433 except OverflowError:
434 self.skipTest("need 64-bit time_t")
Victor Stinner53d36452012-01-27 01:03:25 +0100435 except OSError:
436 invalid_time_t = time_t
437 break
438 if invalid_time_t is None:
439 self.skipTest("unable to find an invalid time_t value")
440
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100441 self.assertRaises(OSError, time.localtime, invalid_time_t)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100442 self.assertRaises(OSError, time.ctime, invalid_time_t)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100443
Victor Stinnerec895392012-04-29 02:41:27 +0200444 def test_get_clock_info(self):
445 clocks = ['clock', 'perf_counter', 'process_time', 'time']
446 if hasattr(time, 'monotonic'):
447 clocks.append('monotonic')
448
449 for name in clocks:
450 info = time.get_clock_info(name)
451 #self.assertIsInstance(info, dict)
452 self.assertIsInstance(info.implementation, str)
453 self.assertNotEqual(info.implementation, '')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400454 self.assertIsInstance(info.monotonic, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200455 self.assertIsInstance(info.resolution, float)
456 # 0.0 < resolution <= 1.0
457 self.assertGreater(info.resolution, 0.0)
458 self.assertLessEqual(info.resolution, 1.0)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200459 self.assertIsInstance(info.adjustable, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200460
461 self.assertRaises(ValueError, time.get_clock_info, 'xxx')
462
463
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000464class TestLocale(unittest.TestCase):
465 def setUp(self):
466 self.oldloc = locale.setlocale(locale.LC_ALL)
Fred Drake2e2be372001-09-20 21:33:42 +0000467
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000468 def tearDown(self):
469 locale.setlocale(locale.LC_ALL, self.oldloc)
470
Martin v. Löwisa6a9c4d2009-05-30 06:15:30 +0000471 def test_bug_3061(self):
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000472 try:
473 tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
474 except locale.Error:
475 # skip this test
476 return
477 # This should not cause an exception
478 time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
479
Victor Stinner73ea29c2011-01-08 01:56:31 +0000480
Victor Stinner73ea29c2011-01-08 01:56:31 +0000481class _TestAsctimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100482 _format = '%d'
483
Victor Stinner73ea29c2011-01-08 01:56:31 +0000484 def yearstr(self, y):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000485 return time.asctime((y,) + (0,) * 8).split()[-1]
Alexander Belopolskya6867252011-01-05 23:00:47 +0000486
Victor Stinner73ea29c2011-01-08 01:56:31 +0000487 def test_large_year(self):
Victor Stinner73691322011-01-08 02:00:24 +0000488 # Check that it doesn't crash for year > 9999
Victor Stinner73ea29c2011-01-08 01:56:31 +0000489 self.assertEqual(self.yearstr(12345), '12345')
490 self.assertEqual(self.yearstr(123456789), '123456789')
491
492class _TestStrftimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100493
494 # Issue 13305: For years < 1000, the value is not always
495 # padded to 4 digits across platforms. The C standard
496 # assumes year >= 1900, so it does not specify the number
497 # of digits.
498
499 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
500 _format = '%04d'
501 else:
502 _format = '%d'
503
Victor Stinner73ea29c2011-01-08 01:56:31 +0000504 def yearstr(self, y):
Florent Xicluna49ce0682011-11-01 12:56:14 +0100505 return time.strftime('%Y', (y,) + (0,) * 8)
506
507 def test_4dyear(self):
508 # Check that we can return the zero padded value.
509 if self._format == '%04d':
510 self.test_year('%04d')
511 else:
512 def year4d(y):
513 return time.strftime('%4Y', (y,) + (0,) * 8)
514 self.test_year('%04d', func=year4d)
515
Florent Xiclunabceb5282011-11-01 14:11:34 +0100516 def skip_if_not_supported(y):
517 msg = "strftime() is limited to [1; 9999] with Visual Studio"
518 # Check that it doesn't crash for year > 9999
519 try:
520 time.strftime('%Y', (y,) + (0,) * 8)
521 except ValueError:
522 cond = False
523 else:
524 cond = True
525 return unittest.skipUnless(cond, msg)
526
527 @skip_if_not_supported(10000)
528 def test_large_year(self):
529 return super().test_large_year()
530
531 @skip_if_not_supported(0)
532 def test_negative(self):
533 return super().test_negative()
534
535 del skip_if_not_supported
536
537
Ezio Melotti3836d702013-04-11 20:29:42 +0300538class _Test4dYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100539 _format = '%d'
540
541 def test_year(self, fmt=None, func=None):
542 fmt = fmt or self._format
543 func = func or self.yearstr
544 self.assertEqual(func(1), fmt % 1)
545 self.assertEqual(func(68), fmt % 68)
546 self.assertEqual(func(69), fmt % 69)
547 self.assertEqual(func(99), fmt % 99)
548 self.assertEqual(func(999), fmt % 999)
549 self.assertEqual(func(9999), fmt % 9999)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000550
551 def test_large_year(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100552 self.assertEqual(self.yearstr(12345), '12345')
Victor Stinner13ed2ea2011-03-21 02:11:01 +0100553 self.assertEqual(self.yearstr(123456789), '123456789')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100554 self.assertEqual(self.yearstr(TIME_MAXYEAR), str(TIME_MAXYEAR))
555 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000556
Victor Stinner301f1212011-01-08 03:06:52 +0000557 def test_negative(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100558 self.assertEqual(self.yearstr(-1), self._format % -1)
Victor Stinner301f1212011-01-08 03:06:52 +0000559 self.assertEqual(self.yearstr(-1234), '-1234')
560 self.assertEqual(self.yearstr(-123456), '-123456')
Florent Xiclunad1bd7f72011-11-01 23:42:05 +0100561 self.assertEqual(self.yearstr(-123456789), str(-123456789))
562 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
Florent Xicluna2fbc1852011-11-02 08:13:43 +0100563 self.assertEqual(self.yearstr(TIME_MINYEAR + 1900), str(TIME_MINYEAR + 1900))
564 # Issue #13312: it may return wrong value for year < TIME_MINYEAR + 1900
565 # Skip the value test, but check that no error is raised
566 self.yearstr(TIME_MINYEAR)
Florent Xiclunae2a732e2011-11-02 01:28:17 +0100567 # self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
Florent Xiclunabceb5282011-11-01 14:11:34 +0100568 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
Victor Stinner301f1212011-01-08 03:06:52 +0000569
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000570
Ezio Melotti3836d702013-04-11 20:29:42 +0300571class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner73ea29c2011-01-08 01:56:31 +0000572 pass
573
Ezio Melotti3836d702013-04-11 20:29:42 +0300574class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner301f1212011-01-08 03:06:52 +0000575 pass
Victor Stinner73ea29c2011-01-08 01:56:31 +0000576
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000577
Victor Stinner643cd682012-03-02 22:54:03 +0100578class TestPytime(unittest.TestCase):
Victor Stinner5d272cc2012-03-13 13:35:55 +0100579 def setUp(self):
580 self.invalid_values = (
581 -(2 ** 100), 2 ** 100,
582 -(2.0 ** 100.0), 2.0 ** 100.0,
583 )
584
585 def test_time_t(self):
586 from _testcapi import pytime_object_to_time_t
587 for obj, time_t in (
588 (0, 0),
589 (-1, -1),
590 (-1.0, -1),
591 (-1.9, -1),
592 (1.0, 1),
593 (1.9, 1),
594 ):
595 self.assertEqual(pytime_object_to_time_t(obj), time_t)
596
597 for invalid in self.invalid_values:
598 self.assertRaises(OverflowError, pytime_object_to_time_t, invalid)
599
600 def test_timeval(self):
601 from _testcapi import pytime_object_to_timeval
602 for obj, timeval in (
603 (0, (0, 0)),
604 (-1, (-1, 0)),
605 (-1.0, (-1, 0)),
606 (1e-6, (0, 1)),
607 (-1e-6, (-1, 999999)),
608 (-1.2, (-2, 800000)),
609 (1.1234560, (1, 123456)),
610 (1.1234569, (1, 123456)),
611 (-1.1234560, (-2, 876544)),
612 (-1.1234561, (-2, 876543)),
613 ):
614 self.assertEqual(pytime_object_to_timeval(obj), timeval)
615
616 for invalid in self.invalid_values:
617 self.assertRaises(OverflowError, pytime_object_to_timeval, invalid)
618
Victor Stinner643cd682012-03-02 22:54:03 +0100619 def test_timespec(self):
620 from _testcapi import pytime_object_to_timespec
621 for obj, timespec in (
622 (0, (0, 0)),
623 (-1, (-1, 0)),
624 (-1.0, (-1, 0)),
Victor Stinner5d272cc2012-03-13 13:35:55 +0100625 (1e-9, (0, 1)),
Victor Stinner643cd682012-03-02 22:54:03 +0100626 (-1e-9, (-1, 999999999)),
627 (-1.2, (-2, 800000000)),
Victor Stinner5d272cc2012-03-13 13:35:55 +0100628 (1.1234567890, (1, 123456789)),
629 (1.1234567899, (1, 123456789)),
630 (-1.1234567890, (-2, 876543211)),
631 (-1.1234567891, (-2, 876543210)),
Victor Stinner643cd682012-03-02 22:54:03 +0100632 ):
633 self.assertEqual(pytime_object_to_timespec(obj), timespec)
634
Victor Stinner5d272cc2012-03-13 13:35:55 +0100635 for invalid in self.invalid_values:
Victor Stinner643cd682012-03-02 22:54:03 +0100636 self.assertRaises(OverflowError, pytime_object_to_timespec, invalid)
637
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400638 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
639 def test_localtime_timezone(self):
Victor Stinner643cd682012-03-02 22:54:03 +0100640
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400641 # Get the localtime and examine it for the offset and zone.
642 lt = time.localtime()
643 self.assertTrue(hasattr(lt, "tm_gmtoff"))
644 self.assertTrue(hasattr(lt, "tm_zone"))
645
646 # See if the offset and zone are similar to the module
647 # attributes.
648 if lt.tm_gmtoff is None:
649 self.assertTrue(not hasattr(time, "timezone"))
650 else:
651 self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
652 if lt.tm_zone is None:
653 self.assertTrue(not hasattr(time, "tzname"))
654 else:
655 self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
656
657 # Try and make UNIX times from the localtime and a 9-tuple
658 # created from the localtime. Test to see that the times are
659 # the same.
660 t = time.mktime(lt); t9 = time.mktime(lt[:9])
661 self.assertEqual(t, t9)
662
663 # Make localtimes from the UNIX times and compare them to
664 # the original localtime, thus making a round trip.
665 new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
666 self.assertEqual(new_lt, lt)
667 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
668 self.assertEqual(new_lt.tm_zone, lt.tm_zone)
669 self.assertEqual(new_lt9, lt)
670 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
671 self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
672
673 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
674 def test_strptime_timezone(self):
675 t = time.strptime("UTC", "%Z")
676 self.assertEqual(t.tm_zone, 'UTC')
677 t = time.strptime("+0500", "%z")
678 self.assertEqual(t.tm_gmtoff, 5 * 3600)
679
680 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
681 def test_short_times(self):
682
683 import pickle
684
685 # Load a short time structure using pickle.
686 st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
687 lt = pickle.loads(st)
688 self.assertIs(lt.tm_gmtoff, None)
689 self.assertIs(lt.tm_zone, None)
Victor Stinner643cd682012-03-02 22:54:03 +0100690
Fred Drake2e2be372001-09-20 21:33:42 +0000691
692if __name__ == "__main__":
Ezio Melotti3836d702013-04-11 20:29:42 +0300693 unittest.main()