blob: 6b7a4fb7686ec2451832954e2962e421d89cfde4 [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):
374 t1 = time.monotonic()
Victor Stinnera9c99a62013-07-03 23:07:37 +0200375 time.sleep(0.5)
Victor Stinnerec895392012-04-29 02:41:27 +0200376 t2 = time.monotonic()
Victor Stinner2dd254d2012-01-20 02:24:18 +0100377 dt = t2 - t1
Victor Stinner8b302012012-02-07 23:29:46 +0100378 self.assertGreater(t2, t1)
Victor Stinner17007882013-12-16 22:36:50 +0100379 self.assertTrue(0.5 <= dt <= 1.0, dt)
Antoine Pitrou391166f2012-01-18 22:35:21 +0100380
Victor Stinnerec895392012-04-29 02:41:27 +0200381 info = time.get_clock_info('monotonic')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400382 self.assertTrue(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +0200383 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200384
385 def test_perf_counter(self):
386 time.perf_counter()
387
388 def test_process_time(self):
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200389 # process_time() should not include time spend during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200390 start = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200391 time.sleep(0.100)
Victor Stinnerec895392012-04-29 02:41:27 +0200392 stop = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200393 # use 20 ms because process_time() has usually a resolution of 15 ms
394 # on Windows
395 self.assertLess(stop - start, 0.020)
Victor Stinnerec895392012-04-29 02:41:27 +0200396
397 info = time.get_clock_info('process_time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400398 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200399 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200400
Victor Stinnerec895392012-04-29 02:41:27 +0200401 @unittest.skipUnless(hasattr(time, 'monotonic'),
402 'need time.monotonic')
403 @unittest.skipUnless(hasattr(time, 'clock_settime'),
404 'need time.clock_settime')
405 def test_monotonic_settime(self):
406 t1 = time.monotonic()
407 realtime = time.clock_gettime(time.CLOCK_REALTIME)
408 # jump backward with an offset of 1 hour
Victor Stinner071eca32012-03-15 01:17:09 +0100409 try:
Victor Stinnerec895392012-04-29 02:41:27 +0200410 time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
411 except PermissionError as err:
412 self.skipTest(err)
413 t2 = time.monotonic()
414 time.clock_settime(time.CLOCK_REALTIME, realtime)
415 # monotonic must not be affected by system clock updates
Victor Stinner071eca32012-03-15 01:17:09 +0100416 self.assertGreaterEqual(t2, t1)
417
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100418 def test_localtime_failure(self):
419 # Issue #13847: check for localtime() failure
Victor Stinner53d36452012-01-27 01:03:25 +0100420 invalid_time_t = None
421 for time_t in (-1, 2**30, 2**33, 2**60):
422 try:
423 time.localtime(time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100424 except OverflowError:
425 self.skipTest("need 64-bit time_t")
Victor Stinner53d36452012-01-27 01:03:25 +0100426 except OSError:
427 invalid_time_t = time_t
428 break
429 if invalid_time_t is None:
430 self.skipTest("unable to find an invalid time_t value")
431
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100432 self.assertRaises(OSError, time.localtime, invalid_time_t)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100433 self.assertRaises(OSError, time.ctime, invalid_time_t)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100434
Victor Stinnerec895392012-04-29 02:41:27 +0200435 def test_get_clock_info(self):
436 clocks = ['clock', 'perf_counter', 'process_time', 'time']
437 if hasattr(time, 'monotonic'):
438 clocks.append('monotonic')
439
440 for name in clocks:
441 info = time.get_clock_info(name)
442 #self.assertIsInstance(info, dict)
443 self.assertIsInstance(info.implementation, str)
444 self.assertNotEqual(info.implementation, '')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400445 self.assertIsInstance(info.monotonic, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200446 self.assertIsInstance(info.resolution, float)
447 # 0.0 < resolution <= 1.0
448 self.assertGreater(info.resolution, 0.0)
449 self.assertLessEqual(info.resolution, 1.0)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200450 self.assertIsInstance(info.adjustable, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200451
452 self.assertRaises(ValueError, time.get_clock_info, 'xxx')
453
454
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000455class TestLocale(unittest.TestCase):
456 def setUp(self):
457 self.oldloc = locale.setlocale(locale.LC_ALL)
Fred Drake2e2be372001-09-20 21:33:42 +0000458
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000459 def tearDown(self):
460 locale.setlocale(locale.LC_ALL, self.oldloc)
461
Martin v. Löwisa6a9c4d2009-05-30 06:15:30 +0000462 def test_bug_3061(self):
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000463 try:
464 tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
465 except locale.Error:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600466 self.skipTest('could not set locale.LC_ALL to fr_FR')
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000467 # This should not cause an exception
468 time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
469
Victor Stinner73ea29c2011-01-08 01:56:31 +0000470
Victor Stinner73ea29c2011-01-08 01:56:31 +0000471class _TestAsctimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100472 _format = '%d'
473
Victor Stinner73ea29c2011-01-08 01:56:31 +0000474 def yearstr(self, y):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000475 return time.asctime((y,) + (0,) * 8).split()[-1]
Alexander Belopolskya6867252011-01-05 23:00:47 +0000476
Victor Stinner73ea29c2011-01-08 01:56:31 +0000477 def test_large_year(self):
Victor Stinner73691322011-01-08 02:00:24 +0000478 # Check that it doesn't crash for year > 9999
Victor Stinner73ea29c2011-01-08 01:56:31 +0000479 self.assertEqual(self.yearstr(12345), '12345')
480 self.assertEqual(self.yearstr(123456789), '123456789')
481
482class _TestStrftimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100483
484 # Issue 13305: For years < 1000, the value is not always
485 # padded to 4 digits across platforms. The C standard
486 # assumes year >= 1900, so it does not specify the number
487 # of digits.
488
489 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
490 _format = '%04d'
491 else:
492 _format = '%d'
493
Victor Stinner73ea29c2011-01-08 01:56:31 +0000494 def yearstr(self, y):
Florent Xicluna49ce0682011-11-01 12:56:14 +0100495 return time.strftime('%Y', (y,) + (0,) * 8)
496
497 def test_4dyear(self):
498 # Check that we can return the zero padded value.
499 if self._format == '%04d':
500 self.test_year('%04d')
501 else:
502 def year4d(y):
503 return time.strftime('%4Y', (y,) + (0,) * 8)
504 self.test_year('%04d', func=year4d)
505
Florent Xiclunabceb5282011-11-01 14:11:34 +0100506 def skip_if_not_supported(y):
507 msg = "strftime() is limited to [1; 9999] with Visual Studio"
508 # Check that it doesn't crash for year > 9999
509 try:
510 time.strftime('%Y', (y,) + (0,) * 8)
511 except ValueError:
512 cond = False
513 else:
514 cond = True
515 return unittest.skipUnless(cond, msg)
516
517 @skip_if_not_supported(10000)
518 def test_large_year(self):
519 return super().test_large_year()
520
521 @skip_if_not_supported(0)
522 def test_negative(self):
523 return super().test_negative()
524
525 del skip_if_not_supported
526
527
Ezio Melotti3836d702013-04-11 20:29:42 +0300528class _Test4dYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100529 _format = '%d'
530
531 def test_year(self, fmt=None, func=None):
532 fmt = fmt or self._format
533 func = func or self.yearstr
534 self.assertEqual(func(1), fmt % 1)
535 self.assertEqual(func(68), fmt % 68)
536 self.assertEqual(func(69), fmt % 69)
537 self.assertEqual(func(99), fmt % 99)
538 self.assertEqual(func(999), fmt % 999)
539 self.assertEqual(func(9999), fmt % 9999)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000540
541 def test_large_year(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100542 self.assertEqual(self.yearstr(12345), '12345')
Victor Stinner13ed2ea2011-03-21 02:11:01 +0100543 self.assertEqual(self.yearstr(123456789), '123456789')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100544 self.assertEqual(self.yearstr(TIME_MAXYEAR), str(TIME_MAXYEAR))
545 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000546
Victor Stinner301f1212011-01-08 03:06:52 +0000547 def test_negative(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100548 self.assertEqual(self.yearstr(-1), self._format % -1)
Victor Stinner301f1212011-01-08 03:06:52 +0000549 self.assertEqual(self.yearstr(-1234), '-1234')
550 self.assertEqual(self.yearstr(-123456), '-123456')
Florent Xiclunad1bd7f72011-11-01 23:42:05 +0100551 self.assertEqual(self.yearstr(-123456789), str(-123456789))
552 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
Florent Xicluna2fbc1852011-11-02 08:13:43 +0100553 self.assertEqual(self.yearstr(TIME_MINYEAR + 1900), str(TIME_MINYEAR + 1900))
554 # Issue #13312: it may return wrong value for year < TIME_MINYEAR + 1900
555 # Skip the value test, but check that no error is raised
556 self.yearstr(TIME_MINYEAR)
Florent Xiclunae2a732e2011-11-02 01:28:17 +0100557 # self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
Florent Xiclunabceb5282011-11-01 14:11:34 +0100558 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
Victor Stinner301f1212011-01-08 03:06:52 +0000559
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000560
Ezio Melotti3836d702013-04-11 20:29:42 +0300561class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner73ea29c2011-01-08 01:56:31 +0000562 pass
563
Ezio Melotti3836d702013-04-11 20:29:42 +0300564class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner301f1212011-01-08 03:06:52 +0000565 pass
Victor Stinner73ea29c2011-01-08 01:56:31 +0000566
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000567
Victor Stinner643cd682012-03-02 22:54:03 +0100568class TestPytime(unittest.TestCase):
Victor Stinner5d272cc2012-03-13 13:35:55 +0100569 def setUp(self):
570 self.invalid_values = (
571 -(2 ** 100), 2 ** 100,
572 -(2.0 ** 100.0), 2.0 ** 100.0,
573 )
574
575 def test_time_t(self):
576 from _testcapi import pytime_object_to_time_t
577 for obj, time_t in (
578 (0, 0),
579 (-1, -1),
580 (-1.0, -1),
581 (-1.9, -1),
582 (1.0, 1),
583 (1.9, 1),
584 ):
585 self.assertEqual(pytime_object_to_time_t(obj), time_t)
586
587 for invalid in self.invalid_values:
588 self.assertRaises(OverflowError, pytime_object_to_time_t, invalid)
589
590 def test_timeval(self):
591 from _testcapi import pytime_object_to_timeval
592 for obj, timeval in (
593 (0, (0, 0)),
594 (-1, (-1, 0)),
595 (-1.0, (-1, 0)),
596 (1e-6, (0, 1)),
597 (-1e-6, (-1, 999999)),
598 (-1.2, (-2, 800000)),
599 (1.1234560, (1, 123456)),
600 (1.1234569, (1, 123456)),
601 (-1.1234560, (-2, 876544)),
602 (-1.1234561, (-2, 876543)),
603 ):
604 self.assertEqual(pytime_object_to_timeval(obj), timeval)
605
606 for invalid in self.invalid_values:
607 self.assertRaises(OverflowError, pytime_object_to_timeval, invalid)
608
Victor Stinner643cd682012-03-02 22:54:03 +0100609 def test_timespec(self):
610 from _testcapi import pytime_object_to_timespec
611 for obj, timespec in (
612 (0, (0, 0)),
613 (-1, (-1, 0)),
614 (-1.0, (-1, 0)),
Victor Stinner5d272cc2012-03-13 13:35:55 +0100615 (1e-9, (0, 1)),
Victor Stinner643cd682012-03-02 22:54:03 +0100616 (-1e-9, (-1, 999999999)),
617 (-1.2, (-2, 800000000)),
Victor Stinner5d272cc2012-03-13 13:35:55 +0100618 (1.1234567890, (1, 123456789)),
619 (1.1234567899, (1, 123456789)),
620 (-1.1234567890, (-2, 876543211)),
621 (-1.1234567891, (-2, 876543210)),
Victor Stinner643cd682012-03-02 22:54:03 +0100622 ):
623 self.assertEqual(pytime_object_to_timespec(obj), timespec)
624
Victor Stinner5d272cc2012-03-13 13:35:55 +0100625 for invalid in self.invalid_values:
Victor Stinner643cd682012-03-02 22:54:03 +0100626 self.assertRaises(OverflowError, pytime_object_to_timespec, invalid)
627
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400628 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
629 def test_localtime_timezone(self):
Victor Stinner643cd682012-03-02 22:54:03 +0100630
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400631 # Get the localtime and examine it for the offset and zone.
632 lt = time.localtime()
633 self.assertTrue(hasattr(lt, "tm_gmtoff"))
634 self.assertTrue(hasattr(lt, "tm_zone"))
635
636 # See if the offset and zone are similar to the module
637 # attributes.
638 if lt.tm_gmtoff is None:
639 self.assertTrue(not hasattr(time, "timezone"))
640 else:
641 self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
642 if lt.tm_zone is None:
643 self.assertTrue(not hasattr(time, "tzname"))
644 else:
645 self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
646
647 # Try and make UNIX times from the localtime and a 9-tuple
648 # created from the localtime. Test to see that the times are
649 # the same.
650 t = time.mktime(lt); t9 = time.mktime(lt[:9])
651 self.assertEqual(t, t9)
652
653 # Make localtimes from the UNIX times and compare them to
654 # the original localtime, thus making a round trip.
655 new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
656 self.assertEqual(new_lt, lt)
657 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
658 self.assertEqual(new_lt.tm_zone, lt.tm_zone)
659 self.assertEqual(new_lt9, lt)
660 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
661 self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
662
663 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
664 def test_strptime_timezone(self):
665 t = time.strptime("UTC", "%Z")
666 self.assertEqual(t.tm_zone, 'UTC')
667 t = time.strptime("+0500", "%z")
668 self.assertEqual(t.tm_gmtoff, 5 * 3600)
669
670 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
671 def test_short_times(self):
672
673 import pickle
674
675 # Load a short time structure using pickle.
676 st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
677 lt = pickle.loads(st)
678 self.assertIs(lt.tm_gmtoff, None)
679 self.assertIs(lt.tm_zone, None)
Victor Stinner643cd682012-03-02 22:54:03 +0100680
Fred Drake2e2be372001-09-20 21:33:42 +0000681
682if __name__ == "__main__":
Ezio Melotti3836d702013-04-11 20:29:42 +0300683 unittest.main()