blob: da0f555d916b9c97ff271823111569d6312841b1 [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
Fred Drakebc561982001-05-22 17:02:02 +0000196 def test_asctime(self):
197 time.asctime(time.gmtime(self.t))
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000198
199 # Max year is only limited by the size of C int.
Florent Xiclunabceb5282011-11-01 14:11:34 +0100200 for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
201 asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
202 self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
203 self.assertRaises(OverflowError, time.asctime,
204 (TIME_MAXYEAR + 1,) + (0,) * 8)
205 self.assertRaises(OverflowError, time.asctime,
206 (TIME_MINYEAR - 1,) + (0,) * 8)
Fred Drakebc561982001-05-22 17:02:02 +0000207 self.assertRaises(TypeError, time.asctime, 0)
Alexander Belopolskye2dc0822011-01-02 20:48:22 +0000208 self.assertRaises(TypeError, time.asctime, ())
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000209 self.assertRaises(TypeError, time.asctime, (0,) * 10)
Fred Drakebc561982001-05-22 17:02:02 +0000210
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000211 def test_asctime_bounding_check(self):
212 self._bounds_checking(time.asctime)
213
Georg Brandle10608c2011-01-02 22:33:43 +0000214 def test_ctime(self):
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000215 t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
216 self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
217 t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
218 self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000')
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000219 for year in [-100, 100, 1000, 2000, 10000]:
220 try:
221 testval = time.mktime((year, 1, 10) + (0,)*6)
222 except (ValueError, OverflowError):
223 # If mktime fails, ctime will fail too. This may happen
224 # on some platforms.
225 pass
226 else:
227 self.assertEqual(time.ctime(testval)[20:], str(year))
Georg Brandle10608c2011-01-02 22:33:43 +0000228
Florent Xiclunae54371e2011-11-11 18:59:30 +0100229 @unittest.skipUnless(hasattr(time, "tzset"),
230 "time module has no attribute tzset")
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000231 def test_tzset(self):
Guido van Rossumd2b738e2003-03-15 12:01:52 +0000232
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000233 from os import environ
234
Tim Peters0eadaac2003-04-24 16:02:54 +0000235 # Epoch time of midnight Dec 25th 2002. Never DST in northern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000236 # hemisphere.
Tim Peters0eadaac2003-04-24 16:02:54 +0000237 xmas2002 = 1040774400.0
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000238
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000239 # These formats are correct for 2002, and possibly future years
240 # This format is the 'standard' as documented at:
241 # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
242 # They are also documented in the tzset(3) man page on most Unix
243 # systems.
Tim Peters0eadaac2003-04-24 16:02:54 +0000244 eastern = 'EST+05EDT,M4.1.0,M10.5.0'
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000245 victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
246 utc='UTC+0'
247
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000248 org_TZ = environ.get('TZ',None)
249 try:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000250 # Make sure we can switch to UTC time and results are correct
251 # Note that unknown timezones default to UTC.
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000252 # Note that altzone is undefined in UTC, as there is no DST
253 environ['TZ'] = eastern
254 time.tzset()
255 environ['TZ'] = utc
256 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000257 self.assertEqual(
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000258 time.gmtime(xmas2002), time.localtime(xmas2002)
259 )
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000260 self.assertEqual(time.daylight, 0)
261 self.assertEqual(time.timezone, 0)
262 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000263
264 # Make sure we can switch to US/Eastern
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000265 environ['TZ'] = eastern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000266 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000267 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
268 self.assertEqual(time.tzname, ('EST', 'EDT'))
269 self.assertEqual(len(time.tzname), 2)
270 self.assertEqual(time.daylight, 1)
271 self.assertEqual(time.timezone, 18000)
272 self.assertEqual(time.altzone, 14400)
273 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
274 self.assertEqual(len(time.tzname), 2)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000275
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000276 # Now go to the southern hemisphere.
277 environ['TZ'] = victoria
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000278 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000279 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
Victor Stinner0cd47902011-12-08 00:32:51 +0100280
281 # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100282 # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
283 # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
284 # on some operating systems (e.g. FreeBSD), which is wrong. See for
285 # example this bug:
286 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
Victor Stinner0cd47902011-12-08 00:32:51 +0100287 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100288 self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000289 self.assertEqual(len(time.tzname), 2)
290 self.assertEqual(time.daylight, 1)
291 self.assertEqual(time.timezone, -36000)
292 self.assertEqual(time.altzone, -39600)
293 self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000294
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000295 finally:
296 # Repair TZ environment variable in case any other tests
297 # rely on it.
298 if org_TZ is not None:
299 environ['TZ'] = org_TZ
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000300 elif 'TZ' in environ:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000301 del environ['TZ']
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000302 time.tzset()
Tim Peters0eadaac2003-04-24 16:02:54 +0000303
Tim Peters1b6f7a92004-06-20 02:50:16 +0000304 def test_insane_timestamps(self):
305 # It's possible that some platform maps time_t to double,
306 # and that this test will fail there. This test should
307 # exempt such platforms (provided they return reasonable
308 # results!).
309 for func in time.ctime, time.gmtime, time.localtime:
310 for unreasonable in -1e200, 1e200:
Victor Stinner5d272cc2012-03-13 13:35:55 +0100311 self.assertRaises(OverflowError, func, unreasonable)
Fred Drakebc561982001-05-22 17:02:02 +0000312
Fred Drakef901abd2004-08-03 17:58:55 +0000313 def test_ctime_without_arg(self):
314 # Not sure how to check the values, since the clock could tick
315 # at any time. Make sure these are at least accepted and
316 # don't raise errors.
317 time.ctime()
318 time.ctime(None)
319
320 def test_gmtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000321 gt0 = time.gmtime()
322 gt1 = time.gmtime(None)
323 t0 = time.mktime(gt0)
324 t1 = time.mktime(gt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000325 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000326
327 def test_localtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000328 lt0 = time.localtime()
329 lt1 = time.localtime(None)
330 t0 = time.mktime(lt0)
331 t1 = time.mktime(lt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000332 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000333
Florent Xiclunae54371e2011-11-11 18:59:30 +0100334 def test_mktime(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100335 # Issue #1726687
336 for t in (-2, -1, 0, 1):
337 try:
338 tt = time.localtime(t)
Victor Stinner2cbae982012-01-27 00:50:33 +0100339 except (OverflowError, OSError):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100340 pass
341 else:
342 self.assertEqual(time.mktime(tt), t)
Florent Xiclunae54371e2011-11-11 18:59:30 +0100343
344 # Issue #13309: passing extreme values to mktime() or localtime()
345 # borks the glibc's internal timezone data.
346 @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
347 "disabled because of a bug in glibc. Issue #13309")
348 def test_mktime_error(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100349 # It may not be possible to reliably make mktime return error
350 # on all platfom. This will make sure that no other exception
351 # than OverflowError is raised for an extreme value.
Florent Xiclunae54371e2011-11-11 18:59:30 +0100352 tt = time.gmtime(self.t)
353 tzname = time.strftime('%Z', tt)
354 self.assertNotEqual(tzname, 'LMT')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100355 try:
356 time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
357 except OverflowError:
358 pass
Florent Xiclunae54371e2011-11-11 18:59:30 +0100359 self.assertEqual(time.strftime('%Z', tt), tzname)
Florent Xiclunabceb5282011-11-01 14:11:34 +0100360
Victor Stinnerec895392012-04-29 02:41:27 +0200361 @unittest.skipUnless(hasattr(time, 'monotonic'),
362 'need time.monotonic')
363 def test_monotonic(self):
364 t1 = time.monotonic()
Victor Stinner8b302012012-02-07 23:29:46 +0100365 time.sleep(0.1)
Victor Stinnerec895392012-04-29 02:41:27 +0200366 t2 = time.monotonic()
Victor Stinner2dd254d2012-01-20 02:24:18 +0100367 dt = t2 - t1
Victor Stinner8b302012012-02-07 23:29:46 +0100368 self.assertGreater(t2, t1)
Victor Stinner2dd254d2012-01-20 02:24:18 +0100369 self.assertAlmostEqual(dt, 0.1, delta=0.2)
Antoine Pitrou391166f2012-01-18 22:35:21 +0100370
Victor Stinnerec895392012-04-29 02:41:27 +0200371 info = time.get_clock_info('monotonic')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400372 self.assertTrue(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +0200373 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200374
375 def test_perf_counter(self):
376 time.perf_counter()
377
378 def test_process_time(self):
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200379 # process_time() should not include time spend during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200380 start = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200381 time.sleep(0.100)
Victor Stinnerec895392012-04-29 02:41:27 +0200382 stop = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200383 # use 20 ms because process_time() has usually a resolution of 15 ms
384 # on Windows
385 self.assertLess(stop - start, 0.020)
Victor Stinnerec895392012-04-29 02:41:27 +0200386
387 info = time.get_clock_info('process_time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400388 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200389 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200390
Victor Stinnerec895392012-04-29 02:41:27 +0200391 @unittest.skipUnless(hasattr(time, 'monotonic'),
392 'need time.monotonic')
393 @unittest.skipUnless(hasattr(time, 'clock_settime'),
394 'need time.clock_settime')
395 def test_monotonic_settime(self):
396 t1 = time.monotonic()
397 realtime = time.clock_gettime(time.CLOCK_REALTIME)
398 # jump backward with an offset of 1 hour
Victor Stinner071eca32012-03-15 01:17:09 +0100399 try:
Victor Stinnerec895392012-04-29 02:41:27 +0200400 time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
401 except PermissionError as err:
402 self.skipTest(err)
403 t2 = time.monotonic()
404 time.clock_settime(time.CLOCK_REALTIME, realtime)
405 # monotonic must not be affected by system clock updates
Victor Stinner071eca32012-03-15 01:17:09 +0100406 self.assertGreaterEqual(t2, t1)
407
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100408 def test_localtime_failure(self):
409 # Issue #13847: check for localtime() failure
Victor Stinner53d36452012-01-27 01:03:25 +0100410 invalid_time_t = None
411 for time_t in (-1, 2**30, 2**33, 2**60):
412 try:
413 time.localtime(time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100414 except OverflowError:
415 self.skipTest("need 64-bit time_t")
Victor Stinner53d36452012-01-27 01:03:25 +0100416 except OSError:
417 invalid_time_t = time_t
418 break
419 if invalid_time_t is None:
420 self.skipTest("unable to find an invalid time_t value")
421
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100422 self.assertRaises(OSError, time.localtime, invalid_time_t)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100423 self.assertRaises(OSError, time.ctime, invalid_time_t)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100424
Victor Stinnerec895392012-04-29 02:41:27 +0200425 def test_get_clock_info(self):
426 clocks = ['clock', 'perf_counter', 'process_time', 'time']
427 if hasattr(time, 'monotonic'):
428 clocks.append('monotonic')
429
430 for name in clocks:
431 info = time.get_clock_info(name)
432 #self.assertIsInstance(info, dict)
433 self.assertIsInstance(info.implementation, str)
434 self.assertNotEqual(info.implementation, '')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400435 self.assertIsInstance(info.monotonic, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200436 self.assertIsInstance(info.resolution, float)
437 # 0.0 < resolution <= 1.0
438 self.assertGreater(info.resolution, 0.0)
439 self.assertLessEqual(info.resolution, 1.0)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200440 self.assertIsInstance(info.adjustable, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200441
442 self.assertRaises(ValueError, time.get_clock_info, 'xxx')
443
444
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000445class TestLocale(unittest.TestCase):
446 def setUp(self):
447 self.oldloc = locale.setlocale(locale.LC_ALL)
Fred Drake2e2be372001-09-20 21:33:42 +0000448
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000449 def tearDown(self):
450 locale.setlocale(locale.LC_ALL, self.oldloc)
451
Martin v. Löwisa6a9c4d2009-05-30 06:15:30 +0000452 def test_bug_3061(self):
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000453 try:
454 tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
455 except locale.Error:
456 # skip this test
457 return
458 # This should not cause an exception
459 time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
460
Victor Stinner73ea29c2011-01-08 01:56:31 +0000461
462class _BaseYearTest(unittest.TestCase):
Alexander Belopolskya6867252011-01-05 23:00:47 +0000463 def yearstr(self, y):
Victor Stinner73ea29c2011-01-08 01:56:31 +0000464 raise NotImplementedError()
465
466class _TestAsctimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100467 _format = '%d'
468
Victor Stinner73ea29c2011-01-08 01:56:31 +0000469 def yearstr(self, y):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000470 return time.asctime((y,) + (0,) * 8).split()[-1]
Alexander Belopolskya6867252011-01-05 23:00:47 +0000471
Victor Stinner73ea29c2011-01-08 01:56:31 +0000472 def test_large_year(self):
Victor Stinner73691322011-01-08 02:00:24 +0000473 # Check that it doesn't crash for year > 9999
Victor Stinner73ea29c2011-01-08 01:56:31 +0000474 self.assertEqual(self.yearstr(12345), '12345')
475 self.assertEqual(self.yearstr(123456789), '123456789')
476
477class _TestStrftimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100478
479 # Issue 13305: For years < 1000, the value is not always
480 # padded to 4 digits across platforms. The C standard
481 # assumes year >= 1900, so it does not specify the number
482 # of digits.
483
484 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
485 _format = '%04d'
486 else:
487 _format = '%d'
488
Victor Stinner73ea29c2011-01-08 01:56:31 +0000489 def yearstr(self, y):
Florent Xicluna49ce0682011-11-01 12:56:14 +0100490 return time.strftime('%Y', (y,) + (0,) * 8)
491
492 def test_4dyear(self):
493 # Check that we can return the zero padded value.
494 if self._format == '%04d':
495 self.test_year('%04d')
496 else:
497 def year4d(y):
498 return time.strftime('%4Y', (y,) + (0,) * 8)
499 self.test_year('%04d', func=year4d)
500
Florent Xiclunabceb5282011-11-01 14:11:34 +0100501 def skip_if_not_supported(y):
502 msg = "strftime() is limited to [1; 9999] with Visual Studio"
503 # Check that it doesn't crash for year > 9999
504 try:
505 time.strftime('%Y', (y,) + (0,) * 8)
506 except ValueError:
507 cond = False
508 else:
509 cond = True
510 return unittest.skipUnless(cond, msg)
511
512 @skip_if_not_supported(10000)
513 def test_large_year(self):
514 return super().test_large_year()
515
516 @skip_if_not_supported(0)
517 def test_negative(self):
518 return super().test_negative()
519
520 del skip_if_not_supported
521
522
Florent Xicluna49ce0682011-11-01 12:56:14 +0100523class _Test4dYear(_BaseYearTest):
524 _format = '%d'
525
526 def test_year(self, fmt=None, func=None):
527 fmt = fmt or self._format
528 func = func or self.yearstr
529 self.assertEqual(func(1), fmt % 1)
530 self.assertEqual(func(68), fmt % 68)
531 self.assertEqual(func(69), fmt % 69)
532 self.assertEqual(func(99), fmt % 99)
533 self.assertEqual(func(999), fmt % 999)
534 self.assertEqual(func(9999), fmt % 9999)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000535
536 def test_large_year(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100537 self.assertEqual(self.yearstr(12345), '12345')
Victor Stinner13ed2ea2011-03-21 02:11:01 +0100538 self.assertEqual(self.yearstr(123456789), '123456789')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100539 self.assertEqual(self.yearstr(TIME_MAXYEAR), str(TIME_MAXYEAR))
540 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000541
Victor Stinner301f1212011-01-08 03:06:52 +0000542 def test_negative(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100543 self.assertEqual(self.yearstr(-1), self._format % -1)
Victor Stinner301f1212011-01-08 03:06:52 +0000544 self.assertEqual(self.yearstr(-1234), '-1234')
545 self.assertEqual(self.yearstr(-123456), '-123456')
Florent Xiclunad1bd7f72011-11-01 23:42:05 +0100546 self.assertEqual(self.yearstr(-123456789), str(-123456789))
547 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
Florent Xicluna2fbc1852011-11-02 08:13:43 +0100548 self.assertEqual(self.yearstr(TIME_MINYEAR + 1900), str(TIME_MINYEAR + 1900))
549 # Issue #13312: it may return wrong value for year < TIME_MINYEAR + 1900
550 # Skip the value test, but check that no error is raised
551 self.yearstr(TIME_MINYEAR)
Florent Xiclunae2a732e2011-11-02 01:28:17 +0100552 # self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
Florent Xiclunabceb5282011-11-01 14:11:34 +0100553 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
Victor Stinner301f1212011-01-08 03:06:52 +0000554
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000555
Victor Stinner73ea29c2011-01-08 01:56:31 +0000556class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear):
557 pass
558
559class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear):
Victor Stinner301f1212011-01-08 03:06:52 +0000560 pass
Victor Stinner73ea29c2011-01-08 01:56:31 +0000561
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000562
Victor Stinner643cd682012-03-02 22:54:03 +0100563class TestPytime(unittest.TestCase):
Victor Stinner5d272cc2012-03-13 13:35:55 +0100564 def setUp(self):
565 self.invalid_values = (
566 -(2 ** 100), 2 ** 100,
567 -(2.0 ** 100.0), 2.0 ** 100.0,
568 )
569
570 def test_time_t(self):
571 from _testcapi import pytime_object_to_time_t
572 for obj, time_t in (
573 (0, 0),
574 (-1, -1),
575 (-1.0, -1),
576 (-1.9, -1),
577 (1.0, 1),
578 (1.9, 1),
579 ):
580 self.assertEqual(pytime_object_to_time_t(obj), time_t)
581
582 for invalid in self.invalid_values:
583 self.assertRaises(OverflowError, pytime_object_to_time_t, invalid)
584
585 def test_timeval(self):
586 from _testcapi import pytime_object_to_timeval
587 for obj, timeval in (
588 (0, (0, 0)),
589 (-1, (-1, 0)),
590 (-1.0, (-1, 0)),
591 (1e-6, (0, 1)),
592 (-1e-6, (-1, 999999)),
593 (-1.2, (-2, 800000)),
594 (1.1234560, (1, 123456)),
595 (1.1234569, (1, 123456)),
596 (-1.1234560, (-2, 876544)),
597 (-1.1234561, (-2, 876543)),
598 ):
599 self.assertEqual(pytime_object_to_timeval(obj), timeval)
600
601 for invalid in self.invalid_values:
602 self.assertRaises(OverflowError, pytime_object_to_timeval, invalid)
603
Victor Stinner643cd682012-03-02 22:54:03 +0100604 def test_timespec(self):
605 from _testcapi import pytime_object_to_timespec
606 for obj, timespec in (
607 (0, (0, 0)),
608 (-1, (-1, 0)),
609 (-1.0, (-1, 0)),
Victor Stinner5d272cc2012-03-13 13:35:55 +0100610 (1e-9, (0, 1)),
Victor Stinner643cd682012-03-02 22:54:03 +0100611 (-1e-9, (-1, 999999999)),
612 (-1.2, (-2, 800000000)),
Victor Stinner5d272cc2012-03-13 13:35:55 +0100613 (1.1234567890, (1, 123456789)),
614 (1.1234567899, (1, 123456789)),
615 (-1.1234567890, (-2, 876543211)),
616 (-1.1234567891, (-2, 876543210)),
Victor Stinner643cd682012-03-02 22:54:03 +0100617 ):
618 self.assertEqual(pytime_object_to_timespec(obj), timespec)
619
Victor Stinner5d272cc2012-03-13 13:35:55 +0100620 for invalid in self.invalid_values:
Victor Stinner643cd682012-03-02 22:54:03 +0100621 self.assertRaises(OverflowError, pytime_object_to_timespec, invalid)
622
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400623 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
624 def test_localtime_timezone(self):
Victor Stinner643cd682012-03-02 22:54:03 +0100625
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400626 # Get the localtime and examine it for the offset and zone.
627 lt = time.localtime()
628 self.assertTrue(hasattr(lt, "tm_gmtoff"))
629 self.assertTrue(hasattr(lt, "tm_zone"))
630
631 # See if the offset and zone are similar to the module
632 # attributes.
633 if lt.tm_gmtoff is None:
634 self.assertTrue(not hasattr(time, "timezone"))
635 else:
636 self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
637 if lt.tm_zone is None:
638 self.assertTrue(not hasattr(time, "tzname"))
639 else:
640 self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
641
642 # Try and make UNIX times from the localtime and a 9-tuple
643 # created from the localtime. Test to see that the times are
644 # the same.
645 t = time.mktime(lt); t9 = time.mktime(lt[:9])
646 self.assertEqual(t, t9)
647
648 # Make localtimes from the UNIX times and compare them to
649 # the original localtime, thus making a round trip.
650 new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
651 self.assertEqual(new_lt, lt)
652 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
653 self.assertEqual(new_lt.tm_zone, lt.tm_zone)
654 self.assertEqual(new_lt9, lt)
655 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
656 self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
657
658 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
659 def test_strptime_timezone(self):
660 t = time.strptime("UTC", "%Z")
661 self.assertEqual(t.tm_zone, 'UTC')
662 t = time.strptime("+0500", "%z")
663 self.assertEqual(t.tm_gmtoff, 5 * 3600)
664
665 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
666 def test_short_times(self):
667
668 import pickle
669
670 # Load a short time structure using pickle.
671 st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
672 lt = pickle.loads(st)
673 self.assertIs(lt.tm_gmtoff, None)
674 self.assertIs(lt.tm_zone, None)
Victor Stinner643cd682012-03-02 22:54:03 +0100675
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000676def test_main():
Victor Stinner73ea29c2011-01-08 01:56:31 +0000677 support.run_unittest(
678 TimeTestCase,
679 TestLocale,
Victor Stinner73ea29c2011-01-08 01:56:31 +0000680 TestAsctime4dyear,
Victor Stinner643cd682012-03-02 22:54:03 +0100681 TestStrftime4dyear,
682 TestPytime)
Fred Drake2e2be372001-09-20 21:33:42 +0000683
684if __name__ == "__main__":
685 test_main()