blob: faf9779a4732dafccaa0f386c87c84ee672a43c6 [file] [log] [blame]
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001from test import support
Barry Warsawb0c22321996-12-06 23:30:07 +00002import time
Fred Drakebc561982001-05-22 17:02:02 +00003import unittest
Victor Stinner4195b5c2012-02-08 23:03:19 +01004import locale
5import sysconfig
6import sys
7import platform
Victor Stinnerec895392012-04-29 02:41:27 +02008try:
9 import threading
10except ImportError:
11 threading = None
Barry Warsawb0c22321996-12-06 23:30:07 +000012
Florent Xiclunabceb5282011-11-01 14:11:34 +010013# Max year is only limited by the size of C int.
14SIZEOF_INT = sysconfig.get_config_var('SIZEOF_INT') or 4
15TIME_MAXYEAR = (1 << 8 * SIZEOF_INT - 1) - 1
16TIME_MINYEAR = -TIME_MAXYEAR - 1
17
18
Fred Drakebc561982001-05-22 17:02:02 +000019class TimeTestCase(unittest.TestCase):
Barry Warsawb0c22321996-12-06 23:30:07 +000020
Fred Drakebc561982001-05-22 17:02:02 +000021 def setUp(self):
22 self.t = time.time()
Barry Warsawb0c22321996-12-06 23:30:07 +000023
Fred Drakebc561982001-05-22 17:02:02 +000024 def test_data_attributes(self):
25 time.altzone
26 time.daylight
27 time.timezone
28 time.tzname
Barry Warsawb0c22321996-12-06 23:30:07 +000029
Victor Stinnerec895392012-04-29 02:41:27 +020030 def test_time(self):
31 time.time()
32 info = time.get_clock_info('time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040033 self.assertFalse(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +020034 self.assertTrue(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020035
Fred Drakebc561982001-05-22 17:02:02 +000036 def test_clock(self):
37 time.clock()
Barry Warsawb0c22321996-12-06 23:30:07 +000038
Victor Stinnerec895392012-04-29 02:41:27 +020039 info = time.get_clock_info('clock')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040040 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +020041 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020042
Victor Stinnere0be4232011-10-25 13:06:09 +020043 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
44 'need time.clock_gettime()')
45 def test_clock_realtime(self):
46 time.clock_gettime(time.CLOCK_REALTIME)
47
48 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
49 'need time.clock_gettime()')
50 @unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'),
51 'need time.CLOCK_MONOTONIC')
52 def test_clock_monotonic(self):
53 a = time.clock_gettime(time.CLOCK_MONOTONIC)
54 b = time.clock_gettime(time.CLOCK_MONOTONIC)
55 self.assertLessEqual(a, b)
56
57 @unittest.skipUnless(hasattr(time, 'clock_getres'),
58 'need time.clock_getres()')
59 def test_clock_getres(self):
60 res = time.clock_getres(time.CLOCK_REALTIME)
61 self.assertGreater(res, 0.0)
62 self.assertLessEqual(res, 1.0)
63
Victor Stinner30d79472012-04-03 00:45:07 +020064 @unittest.skipUnless(hasattr(time, 'clock_settime'),
65 'need time.clock_settime()')
66 def test_clock_settime(self):
67 t = time.clock_gettime(time.CLOCK_REALTIME)
68 try:
69 time.clock_settime(time.CLOCK_REALTIME, t)
70 except PermissionError:
71 pass
72
Victor Stinnerec895392012-04-29 02:41:27 +020073 if hasattr(time, 'CLOCK_MONOTONIC'):
74 self.assertRaises(OSError,
75 time.clock_settime, time.CLOCK_MONOTONIC, 0)
Victor Stinner30d79472012-04-03 00:45:07 +020076
Fred Drakebc561982001-05-22 17:02:02 +000077 def test_conversions(self):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +000078 self.assertEqual(time.ctime(self.t),
79 time.asctime(time.localtime(self.t)))
80 self.assertEqual(int(time.mktime(time.localtime(self.t))),
81 int(self.t))
Fred Drakebc561982001-05-22 17:02:02 +000082
83 def test_sleep(self):
Victor Stinner7f53a502011-07-05 22:00:25 +020084 self.assertRaises(ValueError, time.sleep, -2)
85 self.assertRaises(ValueError, time.sleep, -1)
Fred Drakebc561982001-05-22 17:02:02 +000086 time.sleep(1.2)
87
88 def test_strftime(self):
89 tt = time.gmtime(self.t)
90 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
91 'j', 'm', 'M', 'p', 'S',
92 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
93 format = ' %' + directive
94 try:
95 time.strftime(format, tt)
96 except ValueError:
97 self.fail('conversion specifier: %r failed.' % format)
98
Senthil Kumaran8f377a32011-04-06 12:54:06 +080099 # Issue #10762: Guard against invalid/non-supported format string
100 # so that Python don't crash (Windows crashes when the format string
101 # input to [w]strftime is not kosher.
102 if sys.platform.startswith('win'):
103 with self.assertRaises(ValueError):
104 time.strftime('%f')
105
Florent Xicluna49ce0682011-11-01 12:56:14 +0100106 def _bounds_checking(self, func):
Brett Cannond1080a32004-03-02 04:38:10 +0000107 # Make sure that strftime() checks the bounds of the various parts
Florent Xicluna49ce0682011-11-01 12:56:14 +0100108 # of the time tuple (0 is valid for *all* values).
Brett Cannond1080a32004-03-02 04:38:10 +0000109
Victor Stinner73ea29c2011-01-08 01:56:31 +0000110 # The year field is tested by other test cases above
111
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000112 # Check month [1, 12] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100113 func((1900, 0, 1, 0, 0, 0, 0, 1, -1))
114 func((1900, 12, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000115 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000116 (1900, -1, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000117 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000118 (1900, 13, 1, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000119 # Check day of month [1, 31] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100120 func((1900, 1, 0, 0, 0, 0, 0, 1, -1))
121 func((1900, 1, 31, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000122 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000123 (1900, 1, -1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000124 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000125 (1900, 1, 32, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000126 # Check hour [0, 23]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100127 func((1900, 1, 1, 23, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000128 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000129 (1900, 1, 1, -1, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000130 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000131 (1900, 1, 1, 24, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000132 # Check minute [0, 59]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100133 func((1900, 1, 1, 0, 59, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000134 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000135 (1900, 1, 1, 0, -1, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000136 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000137 (1900, 1, 1, 0, 60, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000138 # Check second [0, 61]
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000139 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000140 (1900, 1, 1, 0, 0, -1, 0, 1, -1))
141 # C99 only requires allowing for one leap second, but Python's docs say
142 # allow two leap seconds (0..61)
Florent Xicluna49ce0682011-11-01 12:56:14 +0100143 func((1900, 1, 1, 0, 0, 60, 0, 1, -1))
144 func((1900, 1, 1, 0, 0, 61, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000145 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000146 (1900, 1, 1, 0, 0, 62, 0, 1, -1))
147 # No check for upper-bound day of week;
148 # value forced into range by a ``% 7`` calculation.
149 # Start check at -2 since gettmarg() increments value before taking
150 # modulo.
Florent Xicluna49ce0682011-11-01 12:56:14 +0100151 self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)),
152 func((1900, 1, 1, 0, 0, 0, +6, 1, -1)))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000153 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000154 (1900, 1, 1, 0, 0, 0, -2, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000155 # Check day of the year [1, 366] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100156 func((1900, 1, 1, 0, 0, 0, 0, 0, -1))
157 func((1900, 1, 1, 0, 0, 0, 0, 366, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000158 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000159 (1900, 1, 1, 0, 0, 0, 0, -1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000160 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000161 (1900, 1, 1, 0, 0, 0, 0, 367, -1))
Brett Cannond1080a32004-03-02 04:38:10 +0000162
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000163 def test_strftime_bounding_check(self):
164 self._bounds_checking(lambda tup: time.strftime('', tup))
165
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000166 def test_default_values_for_zero(self):
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400167 # Make sure that using all zeros uses the proper default
168 # values. No test for daylight savings since strftime() does
169 # not change output based on its value and no test for year
170 # because systems vary in their support for year 0.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000171 expected = "2000 01 01 00 00 00 1 001"
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000172 with support.check_warnings():
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400173 result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000174 self.assertEqual(expected, result)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000175
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000176 def test_strptime(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000177 # Should be able to go round-trip from strftime to strptime without
Andrew Svetlov737fb892012-12-18 21:14:22 +0200178 # raising an exception.
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000179 tt = time.gmtime(self.t)
180 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
181 'j', 'm', 'M', 'p', 'S',
182 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000183 format = '%' + directive
184 strf_output = time.strftime(format, tt)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000185 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000186 time.strptime(strf_output, format)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000187 except ValueError:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000188 self.fail("conversion specifier %r failed with '%s' input." %
189 (format, strf_output))
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000190
Brett Cannon7f6b4f82009-03-30 21:30:26 +0000191 def test_strptime_bytes(self):
192 # Make sure only strings are accepted as arguments to strptime.
193 self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
194 self.assertRaises(TypeError, time.strptime, '2009', b'%Y')
195
Ezio Melotti0f389082013-04-04 02:09:20 +0300196 def test_strptime_exception_context(self):
197 # check that this doesn't chain exceptions needlessly (see #17572)
198 with self.assertRaises(ValueError) as e:
199 time.strptime('', '%D')
200 self.assertIs(e.exception.__suppress_context__, True)
201
Fred Drakebc561982001-05-22 17:02:02 +0000202 def test_asctime(self):
203 time.asctime(time.gmtime(self.t))
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000204
205 # Max year is only limited by the size of C int.
Florent Xiclunabceb5282011-11-01 14:11:34 +0100206 for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
207 asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
208 self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
209 self.assertRaises(OverflowError, time.asctime,
210 (TIME_MAXYEAR + 1,) + (0,) * 8)
211 self.assertRaises(OverflowError, time.asctime,
212 (TIME_MINYEAR - 1,) + (0,) * 8)
Fred Drakebc561982001-05-22 17:02:02 +0000213 self.assertRaises(TypeError, time.asctime, 0)
Alexander Belopolskye2dc0822011-01-02 20:48:22 +0000214 self.assertRaises(TypeError, time.asctime, ())
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000215 self.assertRaises(TypeError, time.asctime, (0,) * 10)
Fred Drakebc561982001-05-22 17:02:02 +0000216
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000217 def test_asctime_bounding_check(self):
218 self._bounds_checking(time.asctime)
219
Georg Brandle10608c2011-01-02 22:33:43 +0000220 def test_ctime(self):
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000221 t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
222 self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
223 t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
224 self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000')
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000225 for year in [-100, 100, 1000, 2000, 10000]:
226 try:
227 testval = time.mktime((year, 1, 10) + (0,)*6)
228 except (ValueError, OverflowError):
229 # If mktime fails, ctime will fail too. This may happen
230 # on some platforms.
231 pass
232 else:
233 self.assertEqual(time.ctime(testval)[20:], str(year))
Georg Brandle10608c2011-01-02 22:33:43 +0000234
Florent Xiclunae54371e2011-11-11 18:59:30 +0100235 @unittest.skipUnless(hasattr(time, "tzset"),
236 "time module has no attribute tzset")
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000237 def test_tzset(self):
Guido van Rossumd2b738e2003-03-15 12:01:52 +0000238
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000239 from os import environ
240
Tim Peters0eadaac2003-04-24 16:02:54 +0000241 # Epoch time of midnight Dec 25th 2002. Never DST in northern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000242 # hemisphere.
Tim Peters0eadaac2003-04-24 16:02:54 +0000243 xmas2002 = 1040774400.0
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000244
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000245 # These formats are correct for 2002, and possibly future years
246 # This format is the 'standard' as documented at:
247 # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
248 # They are also documented in the tzset(3) man page on most Unix
249 # systems.
Tim Peters0eadaac2003-04-24 16:02:54 +0000250 eastern = 'EST+05EDT,M4.1.0,M10.5.0'
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000251 victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
252 utc='UTC+0'
253
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000254 org_TZ = environ.get('TZ',None)
255 try:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000256 # Make sure we can switch to UTC time and results are correct
257 # Note that unknown timezones default to UTC.
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000258 # Note that altzone is undefined in UTC, as there is no DST
259 environ['TZ'] = eastern
260 time.tzset()
261 environ['TZ'] = utc
262 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000263 self.assertEqual(
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000264 time.gmtime(xmas2002), time.localtime(xmas2002)
265 )
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000266 self.assertEqual(time.daylight, 0)
267 self.assertEqual(time.timezone, 0)
268 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000269
270 # Make sure we can switch to US/Eastern
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000271 environ['TZ'] = eastern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000272 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000273 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
274 self.assertEqual(time.tzname, ('EST', 'EDT'))
275 self.assertEqual(len(time.tzname), 2)
276 self.assertEqual(time.daylight, 1)
277 self.assertEqual(time.timezone, 18000)
278 self.assertEqual(time.altzone, 14400)
279 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
280 self.assertEqual(len(time.tzname), 2)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000281
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000282 # Now go to the southern hemisphere.
283 environ['TZ'] = victoria
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000284 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000285 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
Victor Stinner0cd47902011-12-08 00:32:51 +0100286
287 # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100288 # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
289 # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
290 # on some operating systems (e.g. FreeBSD), which is wrong. See for
291 # example this bug:
292 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
Victor Stinner0cd47902011-12-08 00:32:51 +0100293 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100294 self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000295 self.assertEqual(len(time.tzname), 2)
296 self.assertEqual(time.daylight, 1)
297 self.assertEqual(time.timezone, -36000)
298 self.assertEqual(time.altzone, -39600)
299 self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000300
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000301 finally:
302 # Repair TZ environment variable in case any other tests
303 # rely on it.
304 if org_TZ is not None:
305 environ['TZ'] = org_TZ
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000306 elif 'TZ' in environ:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000307 del environ['TZ']
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000308 time.tzset()
Tim Peters0eadaac2003-04-24 16:02:54 +0000309
Tim Peters1b6f7a92004-06-20 02:50:16 +0000310 def test_insane_timestamps(self):
311 # It's possible that some platform maps time_t to double,
312 # and that this test will fail there. This test should
313 # exempt such platforms (provided they return reasonable
314 # results!).
315 for func in time.ctime, time.gmtime, time.localtime:
316 for unreasonable in -1e200, 1e200:
Victor Stinner5d272cc2012-03-13 13:35:55 +0100317 self.assertRaises(OverflowError, func, unreasonable)
Fred Drakebc561982001-05-22 17:02:02 +0000318
Fred Drakef901abd2004-08-03 17:58:55 +0000319 def test_ctime_without_arg(self):
320 # Not sure how to check the values, since the clock could tick
321 # at any time. Make sure these are at least accepted and
322 # don't raise errors.
323 time.ctime()
324 time.ctime(None)
325
326 def test_gmtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000327 gt0 = time.gmtime()
328 gt1 = time.gmtime(None)
329 t0 = time.mktime(gt0)
330 t1 = time.mktime(gt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000331 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000332
333 def test_localtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000334 lt0 = time.localtime()
335 lt1 = time.localtime(None)
336 t0 = time.mktime(lt0)
337 t1 = time.mktime(lt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000338 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000339
Florent Xiclunae54371e2011-11-11 18:59:30 +0100340 def test_mktime(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100341 # Issue #1726687
342 for t in (-2, -1, 0, 1):
343 try:
344 tt = time.localtime(t)
Victor Stinner2cbae982012-01-27 00:50:33 +0100345 except (OverflowError, OSError):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100346 pass
347 else:
348 self.assertEqual(time.mktime(tt), t)
Florent Xiclunae54371e2011-11-11 18:59:30 +0100349
350 # Issue #13309: passing extreme values to mktime() or localtime()
351 # borks the glibc's internal timezone data.
352 @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
353 "disabled because of a bug in glibc. Issue #13309")
354 def test_mktime_error(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100355 # It may not be possible to reliably make mktime return error
356 # on all platfom. This will make sure that no other exception
357 # than OverflowError is raised for an extreme value.
Florent Xiclunae54371e2011-11-11 18:59:30 +0100358 tt = time.gmtime(self.t)
359 tzname = time.strftime('%Z', tt)
360 self.assertNotEqual(tzname, 'LMT')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100361 try:
362 time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
363 except OverflowError:
364 pass
Florent Xiclunae54371e2011-11-11 18:59:30 +0100365 self.assertEqual(time.strftime('%Z', tt), tzname)
Florent Xiclunabceb5282011-11-01 14:11:34 +0100366
Victor Stinnerec895392012-04-29 02:41:27 +0200367 @unittest.skipUnless(hasattr(time, 'monotonic'),
368 'need time.monotonic')
369 def test_monotonic(self):
370 t1 = time.monotonic()
Victor Stinnera9c99a62013-07-03 23:07:37 +0200371 time.sleep(0.5)
Victor Stinnerec895392012-04-29 02:41:27 +0200372 t2 = time.monotonic()
Victor Stinner2dd254d2012-01-20 02:24:18 +0100373 dt = t2 - t1
Victor Stinner8b302012012-02-07 23:29:46 +0100374 self.assertGreater(t2, t1)
Victor Stinnera9c99a62013-07-03 23:07:37 +0200375 self.assertAlmostEqual(dt, 0.5, delta=0.2)
Antoine Pitrou391166f2012-01-18 22:35:21 +0100376
Victor Stinnerec895392012-04-29 02:41:27 +0200377 info = time.get_clock_info('monotonic')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400378 self.assertTrue(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +0200379 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200380
381 def test_perf_counter(self):
382 time.perf_counter()
383
384 def test_process_time(self):
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200385 # process_time() should not include time spend during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200386 start = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200387 time.sleep(0.100)
Victor Stinnerec895392012-04-29 02:41:27 +0200388 stop = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200389 # use 20 ms because process_time() has usually a resolution of 15 ms
390 # on Windows
391 self.assertLess(stop - start, 0.020)
Victor Stinnerec895392012-04-29 02:41:27 +0200392
393 info = time.get_clock_info('process_time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400394 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200395 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200396
Victor Stinnerec895392012-04-29 02:41:27 +0200397 @unittest.skipUnless(hasattr(time, 'monotonic'),
398 'need time.monotonic')
399 @unittest.skipUnless(hasattr(time, 'clock_settime'),
400 'need time.clock_settime')
401 def test_monotonic_settime(self):
402 t1 = time.monotonic()
403 realtime = time.clock_gettime(time.CLOCK_REALTIME)
404 # jump backward with an offset of 1 hour
Victor Stinner071eca32012-03-15 01:17:09 +0100405 try:
Victor Stinnerec895392012-04-29 02:41:27 +0200406 time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
407 except PermissionError as err:
408 self.skipTest(err)
409 t2 = time.monotonic()
410 time.clock_settime(time.CLOCK_REALTIME, realtime)
411 # monotonic must not be affected by system clock updates
Victor Stinner071eca32012-03-15 01:17:09 +0100412 self.assertGreaterEqual(t2, t1)
413
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100414 def test_localtime_failure(self):
415 # Issue #13847: check for localtime() failure
Victor Stinner53d36452012-01-27 01:03:25 +0100416 invalid_time_t = None
417 for time_t in (-1, 2**30, 2**33, 2**60):
418 try:
419 time.localtime(time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100420 except OverflowError:
421 self.skipTest("need 64-bit time_t")
Victor Stinner53d36452012-01-27 01:03:25 +0100422 except OSError:
423 invalid_time_t = time_t
424 break
425 if invalid_time_t is None:
426 self.skipTest("unable to find an invalid time_t value")
427
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100428 self.assertRaises(OSError, time.localtime, invalid_time_t)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100429 self.assertRaises(OSError, time.ctime, invalid_time_t)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100430
Victor Stinnerec895392012-04-29 02:41:27 +0200431 def test_get_clock_info(self):
432 clocks = ['clock', 'perf_counter', 'process_time', 'time']
433 if hasattr(time, 'monotonic'):
434 clocks.append('monotonic')
435
436 for name in clocks:
437 info = time.get_clock_info(name)
438 #self.assertIsInstance(info, dict)
439 self.assertIsInstance(info.implementation, str)
440 self.assertNotEqual(info.implementation, '')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400441 self.assertIsInstance(info.monotonic, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200442 self.assertIsInstance(info.resolution, float)
443 # 0.0 < resolution <= 1.0
444 self.assertGreater(info.resolution, 0.0)
445 self.assertLessEqual(info.resolution, 1.0)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200446 self.assertIsInstance(info.adjustable, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200447
448 self.assertRaises(ValueError, time.get_clock_info, 'xxx')
449
450
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000451class TestLocale(unittest.TestCase):
452 def setUp(self):
453 self.oldloc = locale.setlocale(locale.LC_ALL)
Fred Drake2e2be372001-09-20 21:33:42 +0000454
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000455 def tearDown(self):
456 locale.setlocale(locale.LC_ALL, self.oldloc)
457
Martin v. Löwisa6a9c4d2009-05-30 06:15:30 +0000458 def test_bug_3061(self):
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000459 try:
460 tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
461 except locale.Error:
462 # skip this test
463 return
464 # This should not cause an exception
465 time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
466
Victor Stinner73ea29c2011-01-08 01:56:31 +0000467
Victor Stinner73ea29c2011-01-08 01:56:31 +0000468class _TestAsctimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100469 _format = '%d'
470
Victor Stinner73ea29c2011-01-08 01:56:31 +0000471 def yearstr(self, y):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000472 return time.asctime((y,) + (0,) * 8).split()[-1]
Alexander Belopolskya6867252011-01-05 23:00:47 +0000473
Victor Stinner73ea29c2011-01-08 01:56:31 +0000474 def test_large_year(self):
Victor Stinner73691322011-01-08 02:00:24 +0000475 # Check that it doesn't crash for year > 9999
Victor Stinner73ea29c2011-01-08 01:56:31 +0000476 self.assertEqual(self.yearstr(12345), '12345')
477 self.assertEqual(self.yearstr(123456789), '123456789')
478
479class _TestStrftimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100480
481 # Issue 13305: For years < 1000, the value is not always
482 # padded to 4 digits across platforms. The C standard
483 # assumes year >= 1900, so it does not specify the number
484 # of digits.
485
486 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
487 _format = '%04d'
488 else:
489 _format = '%d'
490
Victor Stinner73ea29c2011-01-08 01:56:31 +0000491 def yearstr(self, y):
Florent Xicluna49ce0682011-11-01 12:56:14 +0100492 return time.strftime('%Y', (y,) + (0,) * 8)
493
494 def test_4dyear(self):
495 # Check that we can return the zero padded value.
496 if self._format == '%04d':
497 self.test_year('%04d')
498 else:
499 def year4d(y):
500 return time.strftime('%4Y', (y,) + (0,) * 8)
501 self.test_year('%04d', func=year4d)
502
Florent Xiclunabceb5282011-11-01 14:11:34 +0100503 def skip_if_not_supported(y):
504 msg = "strftime() is limited to [1; 9999] with Visual Studio"
505 # Check that it doesn't crash for year > 9999
506 try:
507 time.strftime('%Y', (y,) + (0,) * 8)
508 except ValueError:
509 cond = False
510 else:
511 cond = True
512 return unittest.skipUnless(cond, msg)
513
514 @skip_if_not_supported(10000)
515 def test_large_year(self):
516 return super().test_large_year()
517
518 @skip_if_not_supported(0)
519 def test_negative(self):
520 return super().test_negative()
521
522 del skip_if_not_supported
523
524
Ezio Melotti3836d702013-04-11 20:29:42 +0300525class _Test4dYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100526 _format = '%d'
527
528 def test_year(self, fmt=None, func=None):
529 fmt = fmt or self._format
530 func = func or self.yearstr
531 self.assertEqual(func(1), fmt % 1)
532 self.assertEqual(func(68), fmt % 68)
533 self.assertEqual(func(69), fmt % 69)
534 self.assertEqual(func(99), fmt % 99)
535 self.assertEqual(func(999), fmt % 999)
536 self.assertEqual(func(9999), fmt % 9999)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000537
538 def test_large_year(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100539 self.assertEqual(self.yearstr(12345), '12345')
Victor Stinner13ed2ea2011-03-21 02:11:01 +0100540 self.assertEqual(self.yearstr(123456789), '123456789')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100541 self.assertEqual(self.yearstr(TIME_MAXYEAR), str(TIME_MAXYEAR))
542 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000543
Victor Stinner301f1212011-01-08 03:06:52 +0000544 def test_negative(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100545 self.assertEqual(self.yearstr(-1), self._format % -1)
Victor Stinner301f1212011-01-08 03:06:52 +0000546 self.assertEqual(self.yearstr(-1234), '-1234')
547 self.assertEqual(self.yearstr(-123456), '-123456')
Florent Xiclunad1bd7f72011-11-01 23:42:05 +0100548 self.assertEqual(self.yearstr(-123456789), str(-123456789))
549 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
Florent Xicluna2fbc1852011-11-02 08:13:43 +0100550 self.assertEqual(self.yearstr(TIME_MINYEAR + 1900), str(TIME_MINYEAR + 1900))
551 # Issue #13312: it may return wrong value for year < TIME_MINYEAR + 1900
552 # Skip the value test, but check that no error is raised
553 self.yearstr(TIME_MINYEAR)
Florent Xiclunae2a732e2011-11-02 01:28:17 +0100554 # self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
Florent Xiclunabceb5282011-11-01 14:11:34 +0100555 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
Victor Stinner301f1212011-01-08 03:06:52 +0000556
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000557
Ezio Melotti3836d702013-04-11 20:29:42 +0300558class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner73ea29c2011-01-08 01:56:31 +0000559 pass
560
Ezio Melotti3836d702013-04-11 20:29:42 +0300561class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner301f1212011-01-08 03:06:52 +0000562 pass
Victor Stinner73ea29c2011-01-08 01:56:31 +0000563
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000564
Victor Stinner643cd682012-03-02 22:54:03 +0100565class TestPytime(unittest.TestCase):
Victor Stinner5d272cc2012-03-13 13:35:55 +0100566 def setUp(self):
567 self.invalid_values = (
568 -(2 ** 100), 2 ** 100,
569 -(2.0 ** 100.0), 2.0 ** 100.0,
570 )
571
572 def test_time_t(self):
573 from _testcapi import pytime_object_to_time_t
574 for obj, time_t in (
575 (0, 0),
576 (-1, -1),
577 (-1.0, -1),
578 (-1.9, -1),
579 (1.0, 1),
580 (1.9, 1),
581 ):
582 self.assertEqual(pytime_object_to_time_t(obj), time_t)
583
584 for invalid in self.invalid_values:
585 self.assertRaises(OverflowError, pytime_object_to_time_t, invalid)
586
587 def test_timeval(self):
588 from _testcapi import pytime_object_to_timeval
589 for obj, timeval in (
590 (0, (0, 0)),
591 (-1, (-1, 0)),
592 (-1.0, (-1, 0)),
593 (1e-6, (0, 1)),
594 (-1e-6, (-1, 999999)),
595 (-1.2, (-2, 800000)),
596 (1.1234560, (1, 123456)),
597 (1.1234569, (1, 123456)),
598 (-1.1234560, (-2, 876544)),
599 (-1.1234561, (-2, 876543)),
600 ):
601 self.assertEqual(pytime_object_to_timeval(obj), timeval)
602
603 for invalid in self.invalid_values:
604 self.assertRaises(OverflowError, pytime_object_to_timeval, invalid)
605
Victor Stinner643cd682012-03-02 22:54:03 +0100606 def test_timespec(self):
607 from _testcapi import pytime_object_to_timespec
608 for obj, timespec in (
609 (0, (0, 0)),
610 (-1, (-1, 0)),
611 (-1.0, (-1, 0)),
Victor Stinner5d272cc2012-03-13 13:35:55 +0100612 (1e-9, (0, 1)),
Victor Stinner643cd682012-03-02 22:54:03 +0100613 (-1e-9, (-1, 999999999)),
614 (-1.2, (-2, 800000000)),
Victor Stinner5d272cc2012-03-13 13:35:55 +0100615 (1.1234567890, (1, 123456789)),
616 (1.1234567899, (1, 123456789)),
617 (-1.1234567890, (-2, 876543211)),
618 (-1.1234567891, (-2, 876543210)),
Victor Stinner643cd682012-03-02 22:54:03 +0100619 ):
620 self.assertEqual(pytime_object_to_timespec(obj), timespec)
621
Victor Stinner5d272cc2012-03-13 13:35:55 +0100622 for invalid in self.invalid_values:
Victor Stinner643cd682012-03-02 22:54:03 +0100623 self.assertRaises(OverflowError, pytime_object_to_timespec, invalid)
624
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400625 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
626 def test_localtime_timezone(self):
Victor Stinner643cd682012-03-02 22:54:03 +0100627
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400628 # Get the localtime and examine it for the offset and zone.
629 lt = time.localtime()
630 self.assertTrue(hasattr(lt, "tm_gmtoff"))
631 self.assertTrue(hasattr(lt, "tm_zone"))
632
633 # See if the offset and zone are similar to the module
634 # attributes.
635 if lt.tm_gmtoff is None:
636 self.assertTrue(not hasattr(time, "timezone"))
637 else:
638 self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
639 if lt.tm_zone is None:
640 self.assertTrue(not hasattr(time, "tzname"))
641 else:
642 self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
643
644 # Try and make UNIX times from the localtime and a 9-tuple
645 # created from the localtime. Test to see that the times are
646 # the same.
647 t = time.mktime(lt); t9 = time.mktime(lt[:9])
648 self.assertEqual(t, t9)
649
650 # Make localtimes from the UNIX times and compare them to
651 # the original localtime, thus making a round trip.
652 new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
653 self.assertEqual(new_lt, lt)
654 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
655 self.assertEqual(new_lt.tm_zone, lt.tm_zone)
656 self.assertEqual(new_lt9, lt)
657 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
658 self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
659
660 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
661 def test_strptime_timezone(self):
662 t = time.strptime("UTC", "%Z")
663 self.assertEqual(t.tm_zone, 'UTC')
664 t = time.strptime("+0500", "%z")
665 self.assertEqual(t.tm_gmtoff, 5 * 3600)
666
667 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
668 def test_short_times(self):
669
670 import pickle
671
672 # Load a short time structure using pickle.
673 st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
674 lt = pickle.loads(st)
675 self.assertIs(lt.tm_gmtoff, None)
676 self.assertIs(lt.tm_zone, None)
Victor Stinner643cd682012-03-02 22:54:03 +0100677
Fred Drake2e2be372001-09-20 21:33:42 +0000678
679if __name__ == "__main__":
Ezio Melotti3836d702013-04-11 20:29:42 +0300680 unittest.main()