blob: aff5c8285bb39b8774a4c52d5af6fff7e5ac5091 [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 Peterson49a69e42012-05-01 09:38:34 -040033 self.assertEqual(info.monotonic, False)
Victor Stinnerec895392012-04-29 02:41:27 +020034 if sys.platform != 'win32':
Benjamin Peterson49a69e42012-05-01 09:38:34 -040035 self.assertEqual(info.adjusted, True)
Victor Stinnerec895392012-04-29 02:41:27 +020036
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')
Benjamin Peterson49a69e42012-05-01 09:38:34 -040041 self.assertEqual(info.monotonic, True)
42 self.assertEqual(info.adjusted, False)
Victor Stinnerec895392012-04-29 02:41:27 +020043
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')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400373 self.assertEqual(info.monotonic, True)
Victor Stinnerec895392012-04-29 02:41:27 +0200374 if sys.platform == 'linux':
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400375 self.assertEqual(info.adjusted, True)
Victor Stinnerec895392012-04-29 02:41:27 +0200376 else:
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400377 self.assertEqual(info.adjusted, False)
Victor Stinnerec895392012-04-29 02:41:27 +0200378
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')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400389 self.assertEqual(info.monotonic, True)
390 self.assertEqual(info.adjusted, False)
Victor Stinnerec895392012-04-29 02:41:27 +0200391
Victor Stinnerec895392012-04-29 02:41:27 +0200392 @unittest.skipUnless(hasattr(time, 'monotonic'),
393 'need time.monotonic')
394 @unittest.skipUnless(hasattr(time, 'clock_settime'),
395 'need time.clock_settime')
396 def test_monotonic_settime(self):
397 t1 = time.monotonic()
398 realtime = time.clock_gettime(time.CLOCK_REALTIME)
399 # jump backward with an offset of 1 hour
Victor Stinner071eca32012-03-15 01:17:09 +0100400 try:
Victor Stinnerec895392012-04-29 02:41:27 +0200401 time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
402 except PermissionError as err:
403 self.skipTest(err)
404 t2 = time.monotonic()
405 time.clock_settime(time.CLOCK_REALTIME, realtime)
406 # monotonic must not be affected by system clock updates
Victor Stinner071eca32012-03-15 01:17:09 +0100407 self.assertGreaterEqual(t2, t1)
408
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100409 def test_localtime_failure(self):
410 # Issue #13847: check for localtime() failure
Victor Stinner53d36452012-01-27 01:03:25 +0100411 invalid_time_t = None
412 for time_t in (-1, 2**30, 2**33, 2**60):
413 try:
414 time.localtime(time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100415 except OverflowError:
416 self.skipTest("need 64-bit time_t")
Victor Stinner53d36452012-01-27 01:03:25 +0100417 except OSError:
418 invalid_time_t = time_t
419 break
420 if invalid_time_t is None:
421 self.skipTest("unable to find an invalid time_t value")
422
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100423 self.assertRaises(OSError, time.localtime, invalid_time_t)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100424 self.assertRaises(OSError, time.ctime, invalid_time_t)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100425
Victor Stinnerec895392012-04-29 02:41:27 +0200426 def test_get_clock_info(self):
427 clocks = ['clock', 'perf_counter', 'process_time', 'time']
428 if hasattr(time, 'monotonic'):
429 clocks.append('monotonic')
430
431 for name in clocks:
432 info = time.get_clock_info(name)
433 #self.assertIsInstance(info, dict)
434 self.assertIsInstance(info.implementation, str)
435 self.assertNotEqual(info.implementation, '')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400436 self.assertIsInstance(info.monotonic, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200437 self.assertIsInstance(info.resolution, float)
438 # 0.0 < resolution <= 1.0
439 self.assertGreater(info.resolution, 0.0)
440 self.assertLessEqual(info.resolution, 1.0)
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400441 self.assertIsInstance(info.adjusted, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200442
443 self.assertRaises(ValueError, time.get_clock_info, 'xxx')
444
445
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000446class TestLocale(unittest.TestCase):
447 def setUp(self):
448 self.oldloc = locale.setlocale(locale.LC_ALL)
Fred Drake2e2be372001-09-20 21:33:42 +0000449
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000450 def tearDown(self):
451 locale.setlocale(locale.LC_ALL, self.oldloc)
452
Martin v. Löwisa6a9c4d2009-05-30 06:15:30 +0000453 def test_bug_3061(self):
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000454 try:
455 tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
456 except locale.Error:
457 # skip this test
458 return
459 # This should not cause an exception
460 time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
461
Victor Stinner73ea29c2011-01-08 01:56:31 +0000462
463class _BaseYearTest(unittest.TestCase):
Alexander Belopolskya6867252011-01-05 23:00:47 +0000464 def yearstr(self, y):
Victor Stinner73ea29c2011-01-08 01:56:31 +0000465 raise NotImplementedError()
466
467class _TestAsctimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100468 _format = '%d'
469
Victor Stinner73ea29c2011-01-08 01:56:31 +0000470 def yearstr(self, y):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000471 return time.asctime((y,) + (0,) * 8).split()[-1]
Alexander Belopolskya6867252011-01-05 23:00:47 +0000472
Victor Stinner73ea29c2011-01-08 01:56:31 +0000473 def test_large_year(self):
Victor Stinner73691322011-01-08 02:00:24 +0000474 # Check that it doesn't crash for year > 9999
Victor Stinner73ea29c2011-01-08 01:56:31 +0000475 self.assertEqual(self.yearstr(12345), '12345')
476 self.assertEqual(self.yearstr(123456789), '123456789')
477
478class _TestStrftimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100479
480 # Issue 13305: For years < 1000, the value is not always
481 # padded to 4 digits across platforms. The C standard
482 # assumes year >= 1900, so it does not specify the number
483 # of digits.
484
485 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
486 _format = '%04d'
487 else:
488 _format = '%d'
489
Victor Stinner73ea29c2011-01-08 01:56:31 +0000490 def yearstr(self, y):
Florent Xicluna49ce0682011-11-01 12:56:14 +0100491 return time.strftime('%Y', (y,) + (0,) * 8)
492
493 def test_4dyear(self):
494 # Check that we can return the zero padded value.
495 if self._format == '%04d':
496 self.test_year('%04d')
497 else:
498 def year4d(y):
499 return time.strftime('%4Y', (y,) + (0,) * 8)
500 self.test_year('%04d', func=year4d)
501
Florent Xiclunabceb5282011-11-01 14:11:34 +0100502 def skip_if_not_supported(y):
503 msg = "strftime() is limited to [1; 9999] with Visual Studio"
504 # Check that it doesn't crash for year > 9999
505 try:
506 time.strftime('%Y', (y,) + (0,) * 8)
507 except ValueError:
508 cond = False
509 else:
510 cond = True
511 return unittest.skipUnless(cond, msg)
512
513 @skip_if_not_supported(10000)
514 def test_large_year(self):
515 return super().test_large_year()
516
517 @skip_if_not_supported(0)
518 def test_negative(self):
519 return super().test_negative()
520
521 del skip_if_not_supported
522
523
Florent Xicluna49ce0682011-11-01 12:56:14 +0100524class _Test4dYear(_BaseYearTest):
525 _format = '%d'
526
527 def test_year(self, fmt=None, func=None):
528 fmt = fmt or self._format
529 func = func or self.yearstr
530 self.assertEqual(func(1), fmt % 1)
531 self.assertEqual(func(68), fmt % 68)
532 self.assertEqual(func(69), fmt % 69)
533 self.assertEqual(func(99), fmt % 99)
534 self.assertEqual(func(999), fmt % 999)
535 self.assertEqual(func(9999), fmt % 9999)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000536
537 def test_large_year(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100538 self.assertEqual(self.yearstr(12345), '12345')
Victor Stinner13ed2ea2011-03-21 02:11:01 +0100539 self.assertEqual(self.yearstr(123456789), '123456789')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100540 self.assertEqual(self.yearstr(TIME_MAXYEAR), str(TIME_MAXYEAR))
541 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000542
Victor Stinner301f1212011-01-08 03:06:52 +0000543 def test_negative(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100544 self.assertEqual(self.yearstr(-1), self._format % -1)
Victor Stinner301f1212011-01-08 03:06:52 +0000545 self.assertEqual(self.yearstr(-1234), '-1234')
546 self.assertEqual(self.yearstr(-123456), '-123456')
Florent Xiclunad1bd7f72011-11-01 23:42:05 +0100547 self.assertEqual(self.yearstr(-123456789), str(-123456789))
548 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
Florent Xicluna2fbc1852011-11-02 08:13:43 +0100549 self.assertEqual(self.yearstr(TIME_MINYEAR + 1900), str(TIME_MINYEAR + 1900))
550 # Issue #13312: it may return wrong value for year < TIME_MINYEAR + 1900
551 # Skip the value test, but check that no error is raised
552 self.yearstr(TIME_MINYEAR)
Florent Xiclunae2a732e2011-11-02 01:28:17 +0100553 # self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
Florent Xiclunabceb5282011-11-01 14:11:34 +0100554 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
Victor Stinner301f1212011-01-08 03:06:52 +0000555
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000556
Victor Stinner73ea29c2011-01-08 01:56:31 +0000557class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear):
558 pass
559
560class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear):
Victor Stinner301f1212011-01-08 03:06:52 +0000561 pass
Victor Stinner73ea29c2011-01-08 01:56:31 +0000562
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000563
Victor Stinner643cd682012-03-02 22:54:03 +0100564class TestPytime(unittest.TestCase):
Victor Stinner5d272cc2012-03-13 13:35:55 +0100565 def setUp(self):
566 self.invalid_values = (
567 -(2 ** 100), 2 ** 100,
568 -(2.0 ** 100.0), 2.0 ** 100.0,
569 )
570
571 def test_time_t(self):
572 from _testcapi import pytime_object_to_time_t
573 for obj, time_t in (
574 (0, 0),
575 (-1, -1),
576 (-1.0, -1),
577 (-1.9, -1),
578 (1.0, 1),
579 (1.9, 1),
580 ):
581 self.assertEqual(pytime_object_to_time_t(obj), time_t)
582
583 for invalid in self.invalid_values:
584 self.assertRaises(OverflowError, pytime_object_to_time_t, invalid)
585
586 def test_timeval(self):
587 from _testcapi import pytime_object_to_timeval
588 for obj, timeval in (
589 (0, (0, 0)),
590 (-1, (-1, 0)),
591 (-1.0, (-1, 0)),
592 (1e-6, (0, 1)),
593 (-1e-6, (-1, 999999)),
594 (-1.2, (-2, 800000)),
595 (1.1234560, (1, 123456)),
596 (1.1234569, (1, 123456)),
597 (-1.1234560, (-2, 876544)),
598 (-1.1234561, (-2, 876543)),
599 ):
600 self.assertEqual(pytime_object_to_timeval(obj), timeval)
601
602 for invalid in self.invalid_values:
603 self.assertRaises(OverflowError, pytime_object_to_timeval, invalid)
604
Victor Stinner643cd682012-03-02 22:54:03 +0100605 def test_timespec(self):
606 from _testcapi import pytime_object_to_timespec
607 for obj, timespec in (
608 (0, (0, 0)),
609 (-1, (-1, 0)),
610 (-1.0, (-1, 0)),
Victor Stinner5d272cc2012-03-13 13:35:55 +0100611 (1e-9, (0, 1)),
Victor Stinner643cd682012-03-02 22:54:03 +0100612 (-1e-9, (-1, 999999999)),
613 (-1.2, (-2, 800000000)),
Victor Stinner5d272cc2012-03-13 13:35:55 +0100614 (1.1234567890, (1, 123456789)),
615 (1.1234567899, (1, 123456789)),
616 (-1.1234567890, (-2, 876543211)),
617 (-1.1234567891, (-2, 876543210)),
Victor Stinner643cd682012-03-02 22:54:03 +0100618 ):
619 self.assertEqual(pytime_object_to_timespec(obj), timespec)
620
Victor Stinner5d272cc2012-03-13 13:35:55 +0100621 for invalid in self.invalid_values:
Victor Stinner643cd682012-03-02 22:54:03 +0100622 self.assertRaises(OverflowError, pytime_object_to_timespec, invalid)
623
624
625
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000626def test_main():
Victor Stinner73ea29c2011-01-08 01:56:31 +0000627 support.run_unittest(
628 TimeTestCase,
629 TestLocale,
Victor Stinner73ea29c2011-01-08 01:56:31 +0000630 TestAsctime4dyear,
Victor Stinner643cd682012-03-02 22:54:03 +0100631 TestStrftime4dyear,
632 TestPytime)
Fred Drake2e2be372001-09-20 21:33:42 +0000633
634if __name__ == "__main__":
635 test_main()