blob: f00660bb37a7458708593380fcca45298382eaae [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')
33 self.assertEqual(info.is_monotonic, False)
34 if sys.platform != 'win32':
35 self.assertEqual(info.is_adjusted, True)
36
Fred Drakebc561982001-05-22 17:02:02 +000037 def test_clock(self):
38 time.clock()
Barry Warsawb0c22321996-12-06 23:30:07 +000039
Victor Stinnerec895392012-04-29 02:41:27 +020040 info = time.get_clock_info('clock')
41 self.assertEqual(info.is_monotonic, True)
42 self.assertEqual(info.is_adjusted, False)
43
Victor Stinnere0be4232011-10-25 13:06:09 +020044 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
45 'need time.clock_gettime()')
46 def test_clock_realtime(self):
47 time.clock_gettime(time.CLOCK_REALTIME)
48
49 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
50 'need time.clock_gettime()')
51 @unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'),
52 'need time.CLOCK_MONOTONIC')
53 def test_clock_monotonic(self):
54 a = time.clock_gettime(time.CLOCK_MONOTONIC)
55 b = time.clock_gettime(time.CLOCK_MONOTONIC)
56 self.assertLessEqual(a, b)
57
58 @unittest.skipUnless(hasattr(time, 'clock_getres'),
59 'need time.clock_getres()')
60 def test_clock_getres(self):
61 res = time.clock_getres(time.CLOCK_REALTIME)
62 self.assertGreater(res, 0.0)
63 self.assertLessEqual(res, 1.0)
64
Victor Stinner30d79472012-04-03 00:45:07 +020065 @unittest.skipUnless(hasattr(time, 'clock_settime'),
66 'need time.clock_settime()')
67 def test_clock_settime(self):
68 t = time.clock_gettime(time.CLOCK_REALTIME)
69 try:
70 time.clock_settime(time.CLOCK_REALTIME, t)
71 except PermissionError:
72 pass
73
Victor Stinnerec895392012-04-29 02:41:27 +020074 if hasattr(time, 'CLOCK_MONOTONIC'):
75 self.assertRaises(OSError,
76 time.clock_settime, time.CLOCK_MONOTONIC, 0)
Victor Stinner30d79472012-04-03 00:45:07 +020077
Fred Drakebc561982001-05-22 17:02:02 +000078 def test_conversions(self):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +000079 self.assertEqual(time.ctime(self.t),
80 time.asctime(time.localtime(self.t)))
81 self.assertEqual(int(time.mktime(time.localtime(self.t))),
82 int(self.t))
Fred Drakebc561982001-05-22 17:02:02 +000083
84 def test_sleep(self):
Victor Stinner7f53a502011-07-05 22:00:25 +020085 self.assertRaises(ValueError, time.sleep, -2)
86 self.assertRaises(ValueError, time.sleep, -1)
Fred Drakebc561982001-05-22 17:02:02 +000087 time.sleep(1.2)
88
89 def test_strftime(self):
90 tt = time.gmtime(self.t)
91 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
92 'j', 'm', 'M', 'p', 'S',
93 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
94 format = ' %' + directive
95 try:
96 time.strftime(format, tt)
97 except ValueError:
98 self.fail('conversion specifier: %r failed.' % format)
99
Senthil Kumaran8f377a32011-04-06 12:54:06 +0800100 # Issue #10762: Guard against invalid/non-supported format string
101 # so that Python don't crash (Windows crashes when the format string
102 # input to [w]strftime is not kosher.
103 if sys.platform.startswith('win'):
104 with self.assertRaises(ValueError):
105 time.strftime('%f')
106
Florent Xicluna49ce0682011-11-01 12:56:14 +0100107 def _bounds_checking(self, func):
Brett Cannond1080a32004-03-02 04:38:10 +0000108 # Make sure that strftime() checks the bounds of the various parts
Florent Xicluna49ce0682011-11-01 12:56:14 +0100109 # of the time tuple (0 is valid for *all* values).
Brett Cannond1080a32004-03-02 04:38:10 +0000110
Victor Stinner73ea29c2011-01-08 01:56:31 +0000111 # The year field is tested by other test cases above
112
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000113 # Check month [1, 12] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100114 func((1900, 0, 1, 0, 0, 0, 0, 1, -1))
115 func((1900, 12, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000116 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000117 (1900, -1, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000118 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000119 (1900, 13, 1, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000120 # Check day of month [1, 31] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100121 func((1900, 1, 0, 0, 0, 0, 0, 1, -1))
122 func((1900, 1, 31, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000123 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000124 (1900, 1, -1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000125 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000126 (1900, 1, 32, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000127 # Check hour [0, 23]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100128 func((1900, 1, 1, 23, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000129 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000130 (1900, 1, 1, -1, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000131 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000132 (1900, 1, 1, 24, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000133 # Check minute [0, 59]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100134 func((1900, 1, 1, 0, 59, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000135 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000136 (1900, 1, 1, 0, -1, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000137 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000138 (1900, 1, 1, 0, 60, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000139 # Check second [0, 61]
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000140 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000141 (1900, 1, 1, 0, 0, -1, 0, 1, -1))
142 # C99 only requires allowing for one leap second, but Python's docs say
143 # allow two leap seconds (0..61)
Florent Xicluna49ce0682011-11-01 12:56:14 +0100144 func((1900, 1, 1, 0, 0, 60, 0, 1, -1))
145 func((1900, 1, 1, 0, 0, 61, 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, 0, 0, 62, 0, 1, -1))
148 # No check for upper-bound day of week;
149 # value forced into range by a ``% 7`` calculation.
150 # Start check at -2 since gettmarg() increments value before taking
151 # modulo.
Florent Xicluna49ce0682011-11-01 12:56:14 +0100152 self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)),
153 func((1900, 1, 1, 0, 0, 0, +6, 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, 0, 0, -2, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000156 # Check day of the year [1, 366] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100157 func((1900, 1, 1, 0, 0, 0, 0, 0, -1))
158 func((1900, 1, 1, 0, 0, 0, 0, 366, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000159 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000160 (1900, 1, 1, 0, 0, 0, 0, -1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000161 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000162 (1900, 1, 1, 0, 0, 0, 0, 367, -1))
Brett Cannond1080a32004-03-02 04:38:10 +0000163
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000164 def test_strftime_bounding_check(self):
165 self._bounds_checking(lambda tup: time.strftime('', tup))
166
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000167 def test_default_values_for_zero(self):
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400168 # Make sure that using all zeros uses the proper default
169 # values. No test for daylight savings since strftime() does
170 # not change output based on its value and no test for year
171 # because systems vary in their support for year 0.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000172 expected = "2000 01 01 00 00 00 1 001"
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000173 with support.check_warnings():
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400174 result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000175 self.assertEqual(expected, result)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000176
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000177 def test_strptime(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000178 # Should be able to go round-trip from strftime to strptime without
179 # throwing an exception.
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000180 tt = time.gmtime(self.t)
181 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
182 'j', 'm', 'M', 'p', 'S',
183 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000184 format = '%' + directive
185 strf_output = time.strftime(format, tt)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000186 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000187 time.strptime(strf_output, format)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000188 except ValueError:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000189 self.fail("conversion specifier %r failed with '%s' input." %
190 (format, strf_output))
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000191
Brett Cannon7f6b4f82009-03-30 21:30:26 +0000192 def test_strptime_bytes(self):
193 # Make sure only strings are accepted as arguments to strptime.
194 self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
195 self.assertRaises(TypeError, time.strptime, '2009', b'%Y')
196
Fred Drakebc561982001-05-22 17:02:02 +0000197 def test_asctime(self):
198 time.asctime(time.gmtime(self.t))
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000199
200 # Max year is only limited by the size of C int.
Florent Xiclunabceb5282011-11-01 14:11:34 +0100201 for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
202 asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
203 self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
204 self.assertRaises(OverflowError, time.asctime,
205 (TIME_MAXYEAR + 1,) + (0,) * 8)
206 self.assertRaises(OverflowError, time.asctime,
207 (TIME_MINYEAR - 1,) + (0,) * 8)
Fred Drakebc561982001-05-22 17:02:02 +0000208 self.assertRaises(TypeError, time.asctime, 0)
Alexander Belopolskye2dc0822011-01-02 20:48:22 +0000209 self.assertRaises(TypeError, time.asctime, ())
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000210 self.assertRaises(TypeError, time.asctime, (0,) * 10)
Fred Drakebc561982001-05-22 17:02:02 +0000211
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000212 def test_asctime_bounding_check(self):
213 self._bounds_checking(time.asctime)
214
Georg Brandle10608c2011-01-02 22:33:43 +0000215 def test_ctime(self):
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000216 t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
217 self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
218 t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
219 self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000')
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000220 for year in [-100, 100, 1000, 2000, 10000]:
221 try:
222 testval = time.mktime((year, 1, 10) + (0,)*6)
223 except (ValueError, OverflowError):
224 # If mktime fails, ctime will fail too. This may happen
225 # on some platforms.
226 pass
227 else:
228 self.assertEqual(time.ctime(testval)[20:], str(year))
Georg Brandle10608c2011-01-02 22:33:43 +0000229
Florent Xiclunae54371e2011-11-11 18:59:30 +0100230 @unittest.skipUnless(hasattr(time, "tzset"),
231 "time module has no attribute tzset")
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000232 def test_tzset(self):
Guido van Rossumd2b738e2003-03-15 12:01:52 +0000233
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000234 from os import environ
235
Tim Peters0eadaac2003-04-24 16:02:54 +0000236 # Epoch time of midnight Dec 25th 2002. Never DST in northern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000237 # hemisphere.
Tim Peters0eadaac2003-04-24 16:02:54 +0000238 xmas2002 = 1040774400.0
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000239
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000240 # These formats are correct for 2002, and possibly future years
241 # This format is the 'standard' as documented at:
242 # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
243 # They are also documented in the tzset(3) man page on most Unix
244 # systems.
Tim Peters0eadaac2003-04-24 16:02:54 +0000245 eastern = 'EST+05EDT,M4.1.0,M10.5.0'
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000246 victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
247 utc='UTC+0'
248
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000249 org_TZ = environ.get('TZ',None)
250 try:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000251 # Make sure we can switch to UTC time and results are correct
252 # Note that unknown timezones default to UTC.
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000253 # Note that altzone is undefined in UTC, as there is no DST
254 environ['TZ'] = eastern
255 time.tzset()
256 environ['TZ'] = utc
257 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000258 self.assertEqual(
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000259 time.gmtime(xmas2002), time.localtime(xmas2002)
260 )
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000261 self.assertEqual(time.daylight, 0)
262 self.assertEqual(time.timezone, 0)
263 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000264
265 # Make sure we can switch to US/Eastern
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000266 environ['TZ'] = eastern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000267 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000268 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
269 self.assertEqual(time.tzname, ('EST', 'EDT'))
270 self.assertEqual(len(time.tzname), 2)
271 self.assertEqual(time.daylight, 1)
272 self.assertEqual(time.timezone, 18000)
273 self.assertEqual(time.altzone, 14400)
274 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
275 self.assertEqual(len(time.tzname), 2)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000276
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000277 # Now go to the southern hemisphere.
278 environ['TZ'] = victoria
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000279 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000280 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
Victor Stinner0cd47902011-12-08 00:32:51 +0100281
282 # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100283 # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
284 # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
285 # on some operating systems (e.g. FreeBSD), which is wrong. See for
286 # example this bug:
287 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
Victor Stinner0cd47902011-12-08 00:32:51 +0100288 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100289 self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000290 self.assertEqual(len(time.tzname), 2)
291 self.assertEqual(time.daylight, 1)
292 self.assertEqual(time.timezone, -36000)
293 self.assertEqual(time.altzone, -39600)
294 self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000295
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000296 finally:
297 # Repair TZ environment variable in case any other tests
298 # rely on it.
299 if org_TZ is not None:
300 environ['TZ'] = org_TZ
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000301 elif 'TZ' in environ:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000302 del environ['TZ']
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000303 time.tzset()
Tim Peters0eadaac2003-04-24 16:02:54 +0000304
Tim Peters1b6f7a92004-06-20 02:50:16 +0000305 def test_insane_timestamps(self):
306 # It's possible that some platform maps time_t to double,
307 # and that this test will fail there. This test should
308 # exempt such platforms (provided they return reasonable
309 # results!).
310 for func in time.ctime, time.gmtime, time.localtime:
311 for unreasonable in -1e200, 1e200:
Victor Stinner5d272cc2012-03-13 13:35:55 +0100312 self.assertRaises(OverflowError, func, unreasonable)
Fred Drakebc561982001-05-22 17:02:02 +0000313
Fred Drakef901abd2004-08-03 17:58:55 +0000314 def test_ctime_without_arg(self):
315 # Not sure how to check the values, since the clock could tick
316 # at any time. Make sure these are at least accepted and
317 # don't raise errors.
318 time.ctime()
319 time.ctime(None)
320
321 def test_gmtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000322 gt0 = time.gmtime()
323 gt1 = time.gmtime(None)
324 t0 = time.mktime(gt0)
325 t1 = time.mktime(gt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000326 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000327
328 def test_localtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000329 lt0 = time.localtime()
330 lt1 = time.localtime(None)
331 t0 = time.mktime(lt0)
332 t1 = time.mktime(lt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000333 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000334
Florent Xiclunae54371e2011-11-11 18:59:30 +0100335 def test_mktime(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100336 # Issue #1726687
337 for t in (-2, -1, 0, 1):
338 try:
339 tt = time.localtime(t)
Victor Stinner2cbae982012-01-27 00:50:33 +0100340 except (OverflowError, OSError):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100341 pass
342 else:
343 self.assertEqual(time.mktime(tt), t)
Florent Xiclunae54371e2011-11-11 18:59:30 +0100344
345 # Issue #13309: passing extreme values to mktime() or localtime()
346 # borks the glibc's internal timezone data.
347 @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
348 "disabled because of a bug in glibc. Issue #13309")
349 def test_mktime_error(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100350 # It may not be possible to reliably make mktime return error
351 # on all platfom. This will make sure that no other exception
352 # than OverflowError is raised for an extreme value.
Florent Xiclunae54371e2011-11-11 18:59:30 +0100353 tt = time.gmtime(self.t)
354 tzname = time.strftime('%Z', tt)
355 self.assertNotEqual(tzname, 'LMT')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100356 try:
357 time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
358 except OverflowError:
359 pass
Florent Xiclunae54371e2011-11-11 18:59:30 +0100360 self.assertEqual(time.strftime('%Z', tt), tzname)
Florent Xiclunabceb5282011-11-01 14:11:34 +0100361
Victor Stinnerec895392012-04-29 02:41:27 +0200362 @unittest.skipUnless(hasattr(time, 'monotonic'),
363 'need time.monotonic')
364 def test_monotonic(self):
365 t1 = time.monotonic()
Victor Stinner8b302012012-02-07 23:29:46 +0100366 time.sleep(0.1)
Victor Stinnerec895392012-04-29 02:41:27 +0200367 t2 = time.monotonic()
Victor Stinner2dd254d2012-01-20 02:24:18 +0100368 dt = t2 - t1
Victor Stinner8b302012012-02-07 23:29:46 +0100369 self.assertGreater(t2, t1)
Victor Stinner2dd254d2012-01-20 02:24:18 +0100370 self.assertAlmostEqual(dt, 0.1, delta=0.2)
Antoine Pitrou391166f2012-01-18 22:35:21 +0100371
Victor Stinnerec895392012-04-29 02:41:27 +0200372 info = time.get_clock_info('monotonic')
373 self.assertEqual(info.is_monotonic, True)
374 if sys.platform == 'linux':
375 self.assertEqual(info.is_adjusted, True)
376 else:
377 self.assertEqual(info.is_adjusted, False)
378
379 def test_perf_counter(self):
380 time.perf_counter()
381
382 def test_process_time(self):
383 start = time.process_time()
384 time.sleep(0.1)
385 stop = time.process_time()
386 self.assertLess(stop - start, 0.01)
387
388 info = time.get_clock_info('process_time')
389 self.assertEqual(info.is_monotonic, True)
390 self.assertEqual(info.is_adjusted, False)
391
392 @unittest.skipUnless(threading,
393 'need threading')
394 def test_process_time_threads(self):
395 class BusyThread(threading.Thread):
396 def run(self):
397 while not self.stop:
398 pass
399
400 thread = BusyThread()
401 thread.stop = False
402 t1 = time.process_time()
403 thread.start()
404 time.sleep(0.2)
405 t2 = time.process_time()
406 thread.stop = True
407 thread.join()
408 self.assertGreater(t2 - t1, 0.1)
409
410 @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, '')
454 self.assertIsInstance(info.is_monotonic, bool)
455 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)
459 self.assertIsInstance(info.is_adjusted, bool)
460
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
481class _BaseYearTest(unittest.TestCase):
Alexander Belopolskya6867252011-01-05 23:00:47 +0000482 def yearstr(self, y):
Victor Stinner73ea29c2011-01-08 01:56:31 +0000483 raise NotImplementedError()
484
485class _TestAsctimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100486 _format = '%d'
487
Victor Stinner73ea29c2011-01-08 01:56:31 +0000488 def yearstr(self, y):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000489 return time.asctime((y,) + (0,) * 8).split()[-1]
Alexander Belopolskya6867252011-01-05 23:00:47 +0000490
Victor Stinner73ea29c2011-01-08 01:56:31 +0000491 def test_large_year(self):
Victor Stinner73691322011-01-08 02:00:24 +0000492 # Check that it doesn't crash for year > 9999
Victor Stinner73ea29c2011-01-08 01:56:31 +0000493 self.assertEqual(self.yearstr(12345), '12345')
494 self.assertEqual(self.yearstr(123456789), '123456789')
495
496class _TestStrftimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100497
498 # Issue 13305: For years < 1000, the value is not always
499 # padded to 4 digits across platforms. The C standard
500 # assumes year >= 1900, so it does not specify the number
501 # of digits.
502
503 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
504 _format = '%04d'
505 else:
506 _format = '%d'
507
Victor Stinner73ea29c2011-01-08 01:56:31 +0000508 def yearstr(self, y):
Florent Xicluna49ce0682011-11-01 12:56:14 +0100509 return time.strftime('%Y', (y,) + (0,) * 8)
510
511 def test_4dyear(self):
512 # Check that we can return the zero padded value.
513 if self._format == '%04d':
514 self.test_year('%04d')
515 else:
516 def year4d(y):
517 return time.strftime('%4Y', (y,) + (0,) * 8)
518 self.test_year('%04d', func=year4d)
519
Florent Xiclunabceb5282011-11-01 14:11:34 +0100520 def skip_if_not_supported(y):
521 msg = "strftime() is limited to [1; 9999] with Visual Studio"
522 # Check that it doesn't crash for year > 9999
523 try:
524 time.strftime('%Y', (y,) + (0,) * 8)
525 except ValueError:
526 cond = False
527 else:
528 cond = True
529 return unittest.skipUnless(cond, msg)
530
531 @skip_if_not_supported(10000)
532 def test_large_year(self):
533 return super().test_large_year()
534
535 @skip_if_not_supported(0)
536 def test_negative(self):
537 return super().test_negative()
538
539 del skip_if_not_supported
540
541
Florent Xicluna49ce0682011-11-01 12:56:14 +0100542class _Test4dYear(_BaseYearTest):
543 _format = '%d'
544
545 def test_year(self, fmt=None, func=None):
546 fmt = fmt or self._format
547 func = func or self.yearstr
548 self.assertEqual(func(1), fmt % 1)
549 self.assertEqual(func(68), fmt % 68)
550 self.assertEqual(func(69), fmt % 69)
551 self.assertEqual(func(99), fmt % 99)
552 self.assertEqual(func(999), fmt % 999)
553 self.assertEqual(func(9999), fmt % 9999)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000554
555 def test_large_year(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100556 self.assertEqual(self.yearstr(12345), '12345')
Victor Stinner13ed2ea2011-03-21 02:11:01 +0100557 self.assertEqual(self.yearstr(123456789), '123456789')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100558 self.assertEqual(self.yearstr(TIME_MAXYEAR), str(TIME_MAXYEAR))
559 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000560
Victor Stinner301f1212011-01-08 03:06:52 +0000561 def test_negative(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100562 self.assertEqual(self.yearstr(-1), self._format % -1)
Victor Stinner301f1212011-01-08 03:06:52 +0000563 self.assertEqual(self.yearstr(-1234), '-1234')
564 self.assertEqual(self.yearstr(-123456), '-123456')
Florent Xiclunad1bd7f72011-11-01 23:42:05 +0100565 self.assertEqual(self.yearstr(-123456789), str(-123456789))
566 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
Florent Xicluna2fbc1852011-11-02 08:13:43 +0100567 self.assertEqual(self.yearstr(TIME_MINYEAR + 1900), str(TIME_MINYEAR + 1900))
568 # Issue #13312: it may return wrong value for year < TIME_MINYEAR + 1900
569 # Skip the value test, but check that no error is raised
570 self.yearstr(TIME_MINYEAR)
Florent Xiclunae2a732e2011-11-02 01:28:17 +0100571 # self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
Florent Xiclunabceb5282011-11-01 14:11:34 +0100572 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
Victor Stinner301f1212011-01-08 03:06:52 +0000573
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000574
Victor Stinner73ea29c2011-01-08 01:56:31 +0000575class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear):
576 pass
577
578class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear):
Victor Stinner301f1212011-01-08 03:06:52 +0000579 pass
Victor Stinner73ea29c2011-01-08 01:56:31 +0000580
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000581
Victor Stinner643cd682012-03-02 22:54:03 +0100582class TestPytime(unittest.TestCase):
Victor Stinner5d272cc2012-03-13 13:35:55 +0100583 def setUp(self):
584 self.invalid_values = (
585 -(2 ** 100), 2 ** 100,
586 -(2.0 ** 100.0), 2.0 ** 100.0,
587 )
588
589 def test_time_t(self):
590 from _testcapi import pytime_object_to_time_t
591 for obj, time_t in (
592 (0, 0),
593 (-1, -1),
594 (-1.0, -1),
595 (-1.9, -1),
596 (1.0, 1),
597 (1.9, 1),
598 ):
599 self.assertEqual(pytime_object_to_time_t(obj), time_t)
600
601 for invalid in self.invalid_values:
602 self.assertRaises(OverflowError, pytime_object_to_time_t, invalid)
603
604 def test_timeval(self):
605 from _testcapi import pytime_object_to_timeval
606 for obj, timeval in (
607 (0, (0, 0)),
608 (-1, (-1, 0)),
609 (-1.0, (-1, 0)),
610 (1e-6, (0, 1)),
611 (-1e-6, (-1, 999999)),
612 (-1.2, (-2, 800000)),
613 (1.1234560, (1, 123456)),
614 (1.1234569, (1, 123456)),
615 (-1.1234560, (-2, 876544)),
616 (-1.1234561, (-2, 876543)),
617 ):
618 self.assertEqual(pytime_object_to_timeval(obj), timeval)
619
620 for invalid in self.invalid_values:
621 self.assertRaises(OverflowError, pytime_object_to_timeval, invalid)
622
Victor Stinner643cd682012-03-02 22:54:03 +0100623 def test_timespec(self):
624 from _testcapi import pytime_object_to_timespec
625 for obj, timespec in (
626 (0, (0, 0)),
627 (-1, (-1, 0)),
628 (-1.0, (-1, 0)),
Victor Stinner5d272cc2012-03-13 13:35:55 +0100629 (1e-9, (0, 1)),
Victor Stinner643cd682012-03-02 22:54:03 +0100630 (-1e-9, (-1, 999999999)),
631 (-1.2, (-2, 800000000)),
Victor Stinner5d272cc2012-03-13 13:35:55 +0100632 (1.1234567890, (1, 123456789)),
633 (1.1234567899, (1, 123456789)),
634 (-1.1234567890, (-2, 876543211)),
635 (-1.1234567891, (-2, 876543210)),
Victor Stinner643cd682012-03-02 22:54:03 +0100636 ):
637 self.assertEqual(pytime_object_to_timespec(obj), timespec)
638
Victor Stinner5d272cc2012-03-13 13:35:55 +0100639 for invalid in self.invalid_values:
Victor Stinner643cd682012-03-02 22:54:03 +0100640 self.assertRaises(OverflowError, pytime_object_to_timespec, invalid)
641
642
643
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000644def test_main():
Victor Stinner73ea29c2011-01-08 01:56:31 +0000645 support.run_unittest(
646 TimeTestCase,
647 TestLocale,
Victor Stinner73ea29c2011-01-08 01:56:31 +0000648 TestAsctime4dyear,
Victor Stinner643cd682012-03-02 22:54:03 +0100649 TestStrftime4dyear,
650 TestPytime)
Fred Drake2e2be372001-09-20 21:33:42 +0000651
652if __name__ == "__main__":
653 test_main()