blob: 78314a7228e9cf4120f9d0623c419c8cbfd9bbba [file] [log] [blame]
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001from test import support
Victor Stinner992c43f2015-03-27 17:12:45 +01002import enum
3import locale
4import platform
5import sys
6import sysconfig
Barry Warsawb0c22321996-12-06 23:30:07 +00007import time
Fred Drakebc561982001-05-22 17:02:02 +00008import unittest
Victor Stinnerec895392012-04-29 02:41:27 +02009try:
10 import threading
11except ImportError:
12 threading = None
Victor Stinner34dc0f42015-03-27 18:19:03 +010013try:
14 import _testcapi
15except ImportError:
16 _testcapi = None
17
Barry Warsawb0c22321996-12-06 23:30:07 +000018
Florent Xiclunabceb5282011-11-01 14:11:34 +010019# Max year is only limited by the size of C int.
20SIZEOF_INT = sysconfig.get_config_var('SIZEOF_INT') or 4
21TIME_MAXYEAR = (1 << 8 * SIZEOF_INT - 1) - 1
22TIME_MINYEAR = -TIME_MAXYEAR - 1
Victor Stinner992c43f2015-03-27 17:12:45 +010023
Victor Stinner4bfb4602015-03-27 22:27:24 +010024SEC_TO_NS = 10 ** 9
Victor Stinner992c43f2015-03-27 17:12:45 +010025
26class _PyTime(enum.IntEnum):
27 # Round towards zero
28 ROUND_DOWN = 0
29 # Round away from zero
30 ROUND_UP = 1
31
32ALL_ROUNDING_METHODS = (_PyTime.ROUND_UP, _PyTime.ROUND_DOWN)
Florent Xiclunabceb5282011-11-01 14:11:34 +010033
34
Fred Drakebc561982001-05-22 17:02:02 +000035class TimeTestCase(unittest.TestCase):
Barry Warsawb0c22321996-12-06 23:30:07 +000036
Fred Drakebc561982001-05-22 17:02:02 +000037 def setUp(self):
38 self.t = time.time()
Barry Warsawb0c22321996-12-06 23:30:07 +000039
Fred Drakebc561982001-05-22 17:02:02 +000040 def test_data_attributes(self):
41 time.altzone
42 time.daylight
43 time.timezone
44 time.tzname
Barry Warsawb0c22321996-12-06 23:30:07 +000045
Victor Stinnerec895392012-04-29 02:41:27 +020046 def test_time(self):
47 time.time()
48 info = time.get_clock_info('time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040049 self.assertFalse(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +020050 self.assertTrue(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020051
Fred Drakebc561982001-05-22 17:02:02 +000052 def test_clock(self):
53 time.clock()
Barry Warsawb0c22321996-12-06 23:30:07 +000054
Victor Stinnerec895392012-04-29 02:41:27 +020055 info = time.get_clock_info('clock')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -040056 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +020057 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +020058
Victor Stinnere0be4232011-10-25 13:06:09 +020059 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
60 'need time.clock_gettime()')
61 def test_clock_realtime(self):
62 time.clock_gettime(time.CLOCK_REALTIME)
63
64 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
65 'need time.clock_gettime()')
66 @unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'),
67 'need time.CLOCK_MONOTONIC')
68 def test_clock_monotonic(self):
69 a = time.clock_gettime(time.CLOCK_MONOTONIC)
70 b = time.clock_gettime(time.CLOCK_MONOTONIC)
71 self.assertLessEqual(a, b)
72
73 @unittest.skipUnless(hasattr(time, 'clock_getres'),
74 'need time.clock_getres()')
75 def test_clock_getres(self):
76 res = time.clock_getres(time.CLOCK_REALTIME)
77 self.assertGreater(res, 0.0)
78 self.assertLessEqual(res, 1.0)
79
Victor Stinner30d79472012-04-03 00:45:07 +020080 @unittest.skipUnless(hasattr(time, 'clock_settime'),
81 'need time.clock_settime()')
82 def test_clock_settime(self):
83 t = time.clock_gettime(time.CLOCK_REALTIME)
84 try:
85 time.clock_settime(time.CLOCK_REALTIME, t)
86 except PermissionError:
87 pass
88
Victor Stinnerec895392012-04-29 02:41:27 +020089 if hasattr(time, 'CLOCK_MONOTONIC'):
90 self.assertRaises(OSError,
91 time.clock_settime, time.CLOCK_MONOTONIC, 0)
Victor Stinner30d79472012-04-03 00:45:07 +020092
Fred Drakebc561982001-05-22 17:02:02 +000093 def test_conversions(self):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +000094 self.assertEqual(time.ctime(self.t),
95 time.asctime(time.localtime(self.t)))
96 self.assertEqual(int(time.mktime(time.localtime(self.t))),
97 int(self.t))
Fred Drakebc561982001-05-22 17:02:02 +000098
99 def test_sleep(self):
Victor Stinner7f53a502011-07-05 22:00:25 +0200100 self.assertRaises(ValueError, time.sleep, -2)
101 self.assertRaises(ValueError, time.sleep, -1)
Fred Drakebc561982001-05-22 17:02:02 +0000102 time.sleep(1.2)
103
104 def test_strftime(self):
105 tt = time.gmtime(self.t)
106 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
107 'j', 'm', 'M', 'p', 'S',
108 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
109 format = ' %' + directive
110 try:
111 time.strftime(format, tt)
112 except ValueError:
113 self.fail('conversion specifier: %r failed.' % format)
114
Senthil Kumaran8f377a32011-04-06 12:54:06 +0800115 # Issue #10762: Guard against invalid/non-supported format string
116 # so that Python don't crash (Windows crashes when the format string
117 # input to [w]strftime is not kosher.
118 if sys.platform.startswith('win'):
119 with self.assertRaises(ValueError):
120 time.strftime('%f')
121
Florent Xicluna49ce0682011-11-01 12:56:14 +0100122 def _bounds_checking(self, func):
Brett Cannond1080a32004-03-02 04:38:10 +0000123 # Make sure that strftime() checks the bounds of the various parts
Florent Xicluna49ce0682011-11-01 12:56:14 +0100124 # of the time tuple (0 is valid for *all* values).
Brett Cannond1080a32004-03-02 04:38:10 +0000125
Victor Stinner73ea29c2011-01-08 01:56:31 +0000126 # The year field is tested by other test cases above
127
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000128 # Check month [1, 12] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100129 func((1900, 0, 1, 0, 0, 0, 0, 1, -1))
130 func((1900, 12, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000131 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000132 (1900, -1, 1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000133 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000134 (1900, 13, 1, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000135 # Check day of month [1, 31] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100136 func((1900, 1, 0, 0, 0, 0, 0, 1, -1))
137 func((1900, 1, 31, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000138 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000139 (1900, 1, -1, 0, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000140 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000141 (1900, 1, 32, 0, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000142 # Check hour [0, 23]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100143 func((1900, 1, 1, 23, 0, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000144 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000145 (1900, 1, 1, -1, 0, 0, 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, 24, 0, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000148 # Check minute [0, 59]
Florent Xicluna49ce0682011-11-01 12:56:14 +0100149 func((1900, 1, 1, 0, 59, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000150 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000151 (1900, 1, 1, 0, -1, 0, 0, 1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000152 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000153 (1900, 1, 1, 0, 60, 0, 0, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000154 # Check second [0, 61]
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000155 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000156 (1900, 1, 1, 0, 0, -1, 0, 1, -1))
157 # C99 only requires allowing for one leap second, but Python's docs say
158 # allow two leap seconds (0..61)
Florent Xicluna49ce0682011-11-01 12:56:14 +0100159 func((1900, 1, 1, 0, 0, 60, 0, 1, -1))
160 func((1900, 1, 1, 0, 0, 61, 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, 62, 0, 1, -1))
163 # No check for upper-bound day of week;
164 # value forced into range by a ``% 7`` calculation.
165 # Start check at -2 since gettmarg() increments value before taking
166 # modulo.
Florent Xicluna49ce0682011-11-01 12:56:14 +0100167 self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)),
168 func((1900, 1, 1, 0, 0, 0, +6, 1, -1)))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000169 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000170 (1900, 1, 1, 0, 0, 0, -2, 1, -1))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000171 # Check day of the year [1, 366] + zero support
Florent Xicluna49ce0682011-11-01 12:56:14 +0100172 func((1900, 1, 1, 0, 0, 0, 0, 0, -1))
173 func((1900, 1, 1, 0, 0, 0, 0, 366, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000174 self.assertRaises(ValueError, func,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000175 (1900, 1, 1, 0, 0, 0, 0, -1, -1))
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000176 self.assertRaises(ValueError, func,
Brett Cannond1080a32004-03-02 04:38:10 +0000177 (1900, 1, 1, 0, 0, 0, 0, 367, -1))
Brett Cannond1080a32004-03-02 04:38:10 +0000178
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000179 def test_strftime_bounding_check(self):
180 self._bounds_checking(lambda tup: time.strftime('', tup))
181
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000182 def test_default_values_for_zero(self):
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400183 # Make sure that using all zeros uses the proper default
184 # values. No test for daylight savings since strftime() does
185 # not change output based on its value and no test for year
186 # because systems vary in their support for year 0.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000187 expected = "2000 01 01 00 00 00 1 001"
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000188 with support.check_warnings():
Alexander Belopolsky03163ac2011-05-02 12:20:52 -0400189 result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000190 self.assertEqual(expected, result)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000191
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000192 def test_strptime(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000193 # Should be able to go round-trip from strftime to strptime without
Andrew Svetlov737fb892012-12-18 21:14:22 +0200194 # raising an exception.
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000195 tt = time.gmtime(self.t)
196 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
197 'j', 'm', 'M', 'p', 'S',
198 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000199 format = '%' + directive
200 strf_output = time.strftime(format, tt)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000201 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000202 time.strptime(strf_output, format)
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000203 except ValueError:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000204 self.fail("conversion specifier %r failed with '%s' input." %
205 (format, strf_output))
Guido van Rossum00efe7e2002-07-19 17:04:46 +0000206
Brett Cannon7f6b4f82009-03-30 21:30:26 +0000207 def test_strptime_bytes(self):
208 # Make sure only strings are accepted as arguments to strptime.
209 self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
210 self.assertRaises(TypeError, time.strptime, '2009', b'%Y')
211
Ezio Melotti0f389082013-04-04 02:09:20 +0300212 def test_strptime_exception_context(self):
213 # check that this doesn't chain exceptions needlessly (see #17572)
214 with self.assertRaises(ValueError) as e:
215 time.strptime('', '%D')
216 self.assertIs(e.exception.__suppress_context__, True)
Serhiy Storchakacdac3022013-11-24 18:15:37 +0200217 # additional check for IndexError branch (issue #19545)
218 with self.assertRaises(ValueError) as e:
219 time.strptime('19', '%Y %')
220 self.assertIs(e.exception.__suppress_context__, True)
Ezio Melotti0f389082013-04-04 02:09:20 +0300221
Fred Drakebc561982001-05-22 17:02:02 +0000222 def test_asctime(self):
223 time.asctime(time.gmtime(self.t))
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000224
225 # Max year is only limited by the size of C int.
Florent Xiclunabceb5282011-11-01 14:11:34 +0100226 for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
227 asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
228 self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
229 self.assertRaises(OverflowError, time.asctime,
230 (TIME_MAXYEAR + 1,) + (0,) * 8)
231 self.assertRaises(OverflowError, time.asctime,
232 (TIME_MINYEAR - 1,) + (0,) * 8)
Fred Drakebc561982001-05-22 17:02:02 +0000233 self.assertRaises(TypeError, time.asctime, 0)
Alexander Belopolskye2dc0822011-01-02 20:48:22 +0000234 self.assertRaises(TypeError, time.asctime, ())
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000235 self.assertRaises(TypeError, time.asctime, (0,) * 10)
Fred Drakebc561982001-05-22 17:02:02 +0000236
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000237 def test_asctime_bounding_check(self):
238 self._bounds_checking(time.asctime)
239
Georg Brandle10608c2011-01-02 22:33:43 +0000240 def test_ctime(self):
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000241 t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
242 self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
243 t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
244 self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000')
Victor Stinner1ac42612014-02-21 09:27:17 +0100245 for year in [-100, 100, 1000, 2000, 2050, 10000]:
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000246 try:
247 testval = time.mktime((year, 1, 10) + (0,)*6)
248 except (ValueError, OverflowError):
249 # If mktime fails, ctime will fail too. This may happen
250 # on some platforms.
251 pass
252 else:
253 self.assertEqual(time.ctime(testval)[20:], str(year))
Georg Brandle10608c2011-01-02 22:33:43 +0000254
Florent Xiclunae54371e2011-11-11 18:59:30 +0100255 @unittest.skipUnless(hasattr(time, "tzset"),
256 "time module has no attribute tzset")
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000257 def test_tzset(self):
Guido van Rossumd2b738e2003-03-15 12:01:52 +0000258
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000259 from os import environ
260
Tim Peters0eadaac2003-04-24 16:02:54 +0000261 # Epoch time of midnight Dec 25th 2002. Never DST in northern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000262 # hemisphere.
Tim Peters0eadaac2003-04-24 16:02:54 +0000263 xmas2002 = 1040774400.0
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000264
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000265 # These formats are correct for 2002, and possibly future years
266 # This format is the 'standard' as documented at:
267 # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
268 # They are also documented in the tzset(3) man page on most Unix
269 # systems.
Tim Peters0eadaac2003-04-24 16:02:54 +0000270 eastern = 'EST+05EDT,M4.1.0,M10.5.0'
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000271 victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
272 utc='UTC+0'
273
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000274 org_TZ = environ.get('TZ',None)
275 try:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000276 # Make sure we can switch to UTC time and results are correct
277 # Note that unknown timezones default to UTC.
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000278 # Note that altzone is undefined in UTC, as there is no DST
279 environ['TZ'] = eastern
280 time.tzset()
281 environ['TZ'] = utc
282 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000283 self.assertEqual(
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000284 time.gmtime(xmas2002), time.localtime(xmas2002)
285 )
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000286 self.assertEqual(time.daylight, 0)
287 self.assertEqual(time.timezone, 0)
288 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000289
290 # Make sure we can switch to US/Eastern
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000291 environ['TZ'] = eastern
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000292 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000293 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
294 self.assertEqual(time.tzname, ('EST', 'EDT'))
295 self.assertEqual(len(time.tzname), 2)
296 self.assertEqual(time.daylight, 1)
297 self.assertEqual(time.timezone, 18000)
298 self.assertEqual(time.altzone, 14400)
299 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
300 self.assertEqual(len(time.tzname), 2)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000301
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000302 # Now go to the southern hemisphere.
303 environ['TZ'] = victoria
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000304 time.tzset()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000305 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
Victor Stinner0cd47902011-12-08 00:32:51 +0100306
307 # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100308 # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
309 # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
310 # on some operating systems (e.g. FreeBSD), which is wrong. See for
311 # example this bug:
312 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
Victor Stinner0cd47902011-12-08 00:32:51 +0100313 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
Victor Stinner10a6ddb2011-12-10 14:37:53 +0100314 self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000315 self.assertEqual(len(time.tzname), 2)
316 self.assertEqual(time.daylight, 1)
317 self.assertEqual(time.timezone, -36000)
318 self.assertEqual(time.altzone, -39600)
319 self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000320
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000321 finally:
322 # Repair TZ environment variable in case any other tests
323 # rely on it.
324 if org_TZ is not None:
325 environ['TZ'] = org_TZ
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000326 elif 'TZ' in environ:
Guido van Rossumd11b62e2003-03-14 21:51:36 +0000327 del environ['TZ']
Neal Norwitz7f2588c2003-04-11 15:35:53 +0000328 time.tzset()
Tim Peters0eadaac2003-04-24 16:02:54 +0000329
Tim Peters1b6f7a92004-06-20 02:50:16 +0000330 def test_insane_timestamps(self):
331 # It's possible that some platform maps time_t to double,
332 # and that this test will fail there. This test should
333 # exempt such platforms (provided they return reasonable
334 # results!).
335 for func in time.ctime, time.gmtime, time.localtime:
336 for unreasonable in -1e200, 1e200:
Victor Stinner5d272cc2012-03-13 13:35:55 +0100337 self.assertRaises(OverflowError, func, unreasonable)
Fred Drakebc561982001-05-22 17:02:02 +0000338
Fred Drakef901abd2004-08-03 17:58:55 +0000339 def test_ctime_without_arg(self):
340 # Not sure how to check the values, since the clock could tick
341 # at any time. Make sure these are at least accepted and
342 # don't raise errors.
343 time.ctime()
344 time.ctime(None)
345
346 def test_gmtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000347 gt0 = time.gmtime()
348 gt1 = time.gmtime(None)
349 t0 = time.mktime(gt0)
350 t1 = time.mktime(gt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000351 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000352
353 def test_localtime_without_arg(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000354 lt0 = time.localtime()
355 lt1 = time.localtime(None)
356 t0 = time.mktime(lt0)
357 t1 = time.mktime(lt1)
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000358 self.assertAlmostEqual(t1, t0, delta=0.2)
Fred Drakef901abd2004-08-03 17:58:55 +0000359
Florent Xiclunae54371e2011-11-11 18:59:30 +0100360 def test_mktime(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100361 # Issue #1726687
362 for t in (-2, -1, 0, 1):
Victor Stinner8c8b4e02014-02-21 23:54:32 +0100363 if sys.platform.startswith('aix') and t == -1:
364 # Issue #11188, #19748: mktime() returns -1 on error. On Linux,
365 # the tm_wday field is used as a sentinel () to detect if -1 is
366 # really an error or a valid timestamp. On AIX, tm_wday is
367 # unchanged even on success and so cannot be used as a
368 # sentinel.
369 continue
Florent Xiclunabceb5282011-11-01 14:11:34 +0100370 try:
371 tt = time.localtime(t)
Victor Stinner2cbae982012-01-27 00:50:33 +0100372 except (OverflowError, OSError):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100373 pass
374 else:
375 self.assertEqual(time.mktime(tt), t)
Florent Xiclunae54371e2011-11-11 18:59:30 +0100376
377 # Issue #13309: passing extreme values to mktime() or localtime()
378 # borks the glibc's internal timezone data.
379 @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
380 "disabled because of a bug in glibc. Issue #13309")
381 def test_mktime_error(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100382 # It may not be possible to reliably make mktime return error
383 # on all platfom. This will make sure that no other exception
384 # than OverflowError is raised for an extreme value.
Florent Xiclunae54371e2011-11-11 18:59:30 +0100385 tt = time.gmtime(self.t)
386 tzname = time.strftime('%Z', tt)
387 self.assertNotEqual(tzname, 'LMT')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100388 try:
389 time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
390 except OverflowError:
391 pass
Florent Xiclunae54371e2011-11-11 18:59:30 +0100392 self.assertEqual(time.strftime('%Z', tt), tzname)
Florent Xiclunabceb5282011-11-01 14:11:34 +0100393
Victor Stinnerec895392012-04-29 02:41:27 +0200394 @unittest.skipUnless(hasattr(time, 'monotonic'),
395 'need time.monotonic')
396 def test_monotonic(self):
Victor Stinner6c861812013-11-23 00:15:27 +0100397 # monotonic() should not go backward
398 times = [time.monotonic() for n in range(100)]
399 t1 = times[0]
400 for t2 in times[1:]:
401 self.assertGreaterEqual(t2, t1, "times=%s" % times)
402 t1 = t2
403
404 # monotonic() includes time elapsed during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200405 t1 = time.monotonic()
Victor Stinnera9c99a62013-07-03 23:07:37 +0200406 time.sleep(0.5)
Victor Stinnerec895392012-04-29 02:41:27 +0200407 t2 = time.monotonic()
Victor Stinner2dd254d2012-01-20 02:24:18 +0100408 dt = t2 - t1
Victor Stinner8b302012012-02-07 23:29:46 +0100409 self.assertGreater(t2, t1)
Zachary Ware487aedb2014-01-02 09:41:10 -0600410 # Issue #20101: On some Windows machines, dt may be slightly low
411 self.assertTrue(0.45 <= dt <= 1.0, dt)
Antoine Pitrou391166f2012-01-18 22:35:21 +0100412
Victor Stinner6c861812013-11-23 00:15:27 +0100413 # monotonic() is a monotonic but non adjustable clock
Victor Stinnerec895392012-04-29 02:41:27 +0200414 info = time.get_clock_info('monotonic')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400415 self.assertTrue(info.monotonic)
Victor Stinner6222d762012-06-12 23:04:11 +0200416 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200417
418 def test_perf_counter(self):
419 time.perf_counter()
420
421 def test_process_time(self):
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200422 # process_time() should not include time spend during a sleep
Victor Stinnerec895392012-04-29 02:41:27 +0200423 start = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200424 time.sleep(0.100)
Victor Stinnerec895392012-04-29 02:41:27 +0200425 stop = time.process_time()
Victor Stinner0dec1bf2012-06-01 22:45:23 +0200426 # use 20 ms because process_time() has usually a resolution of 15 ms
427 # on Windows
428 self.assertLess(stop - start, 0.020)
Victor Stinnerec895392012-04-29 02:41:27 +0200429
430 info = time.get_clock_info('process_time')
Benjamin Peterson1c5ae552012-05-01 11:14:32 -0400431 self.assertTrue(info.monotonic)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200432 self.assertFalse(info.adjustable)
Victor Stinnerec895392012-04-29 02:41:27 +0200433
Victor Stinnerec895392012-04-29 02:41:27 +0200434 @unittest.skipUnless(hasattr(time, 'monotonic'),
435 'need time.monotonic')
436 @unittest.skipUnless(hasattr(time, 'clock_settime'),
437 'need time.clock_settime')
438 def test_monotonic_settime(self):
439 t1 = time.monotonic()
440 realtime = time.clock_gettime(time.CLOCK_REALTIME)
441 # jump backward with an offset of 1 hour
Victor Stinner071eca32012-03-15 01:17:09 +0100442 try:
Victor Stinnerec895392012-04-29 02:41:27 +0200443 time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
444 except PermissionError as err:
445 self.skipTest(err)
446 t2 = time.monotonic()
447 time.clock_settime(time.CLOCK_REALTIME, realtime)
448 # monotonic must not be affected by system clock updates
Victor Stinner071eca32012-03-15 01:17:09 +0100449 self.assertGreaterEqual(t2, t1)
450
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100451 def test_localtime_failure(self):
452 # Issue #13847: check for localtime() failure
Victor Stinner53d36452012-01-27 01:03:25 +0100453 invalid_time_t = None
454 for time_t in (-1, 2**30, 2**33, 2**60):
455 try:
456 time.localtime(time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100457 except OverflowError:
458 self.skipTest("need 64-bit time_t")
Victor Stinner53d36452012-01-27 01:03:25 +0100459 except OSError:
460 invalid_time_t = time_t
461 break
462 if invalid_time_t is None:
463 self.skipTest("unable to find an invalid time_t value")
464
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100465 self.assertRaises(OSError, time.localtime, invalid_time_t)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100466 self.assertRaises(OSError, time.ctime, invalid_time_t)
Victor Stinnerb94b2662012-01-18 01:50:21 +0100467
Victor Stinnerec895392012-04-29 02:41:27 +0200468 def test_get_clock_info(self):
469 clocks = ['clock', 'perf_counter', 'process_time', 'time']
470 if hasattr(time, 'monotonic'):
471 clocks.append('monotonic')
472
473 for name in clocks:
474 info = time.get_clock_info(name)
475 #self.assertIsInstance(info, dict)
476 self.assertIsInstance(info.implementation, str)
477 self.assertNotEqual(info.implementation, '')
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400478 self.assertIsInstance(info.monotonic, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200479 self.assertIsInstance(info.resolution, float)
480 # 0.0 < resolution <= 1.0
481 self.assertGreater(info.resolution, 0.0)
482 self.assertLessEqual(info.resolution, 1.0)
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200483 self.assertIsInstance(info.adjustable, bool)
Victor Stinnerec895392012-04-29 02:41:27 +0200484
485 self.assertRaises(ValueError, time.get_clock_info, 'xxx')
486
487
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000488class TestLocale(unittest.TestCase):
489 def setUp(self):
490 self.oldloc = locale.setlocale(locale.LC_ALL)
Fred Drake2e2be372001-09-20 21:33:42 +0000491
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000492 def tearDown(self):
493 locale.setlocale(locale.LC_ALL, self.oldloc)
494
Martin v. Löwisa6a9c4d2009-05-30 06:15:30 +0000495 def test_bug_3061(self):
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000496 try:
497 tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
498 except locale.Error:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600499 self.skipTest('could not set locale.LC_ALL to fr_FR')
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000500 # This should not cause an exception
501 time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
502
Victor Stinner73ea29c2011-01-08 01:56:31 +0000503
Victor Stinner73ea29c2011-01-08 01:56:31 +0000504class _TestAsctimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100505 _format = '%d'
506
Victor Stinner73ea29c2011-01-08 01:56:31 +0000507 def yearstr(self, y):
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000508 return time.asctime((y,) + (0,) * 8).split()[-1]
Alexander Belopolskya6867252011-01-05 23:00:47 +0000509
Victor Stinner73ea29c2011-01-08 01:56:31 +0000510 def test_large_year(self):
Victor Stinner73691322011-01-08 02:00:24 +0000511 # Check that it doesn't crash for year > 9999
Victor Stinner73ea29c2011-01-08 01:56:31 +0000512 self.assertEqual(self.yearstr(12345), '12345')
513 self.assertEqual(self.yearstr(123456789), '123456789')
514
515class _TestStrftimeYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100516
517 # Issue 13305: For years < 1000, the value is not always
518 # padded to 4 digits across platforms. The C standard
519 # assumes year >= 1900, so it does not specify the number
520 # of digits.
521
522 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
523 _format = '%04d'
524 else:
525 _format = '%d'
526
Victor Stinner73ea29c2011-01-08 01:56:31 +0000527 def yearstr(self, y):
Florent Xicluna49ce0682011-11-01 12:56:14 +0100528 return time.strftime('%Y', (y,) + (0,) * 8)
529
530 def test_4dyear(self):
531 # Check that we can return the zero padded value.
532 if self._format == '%04d':
533 self.test_year('%04d')
534 else:
535 def year4d(y):
536 return time.strftime('%4Y', (y,) + (0,) * 8)
537 self.test_year('%04d', func=year4d)
538
Florent Xiclunabceb5282011-11-01 14:11:34 +0100539 def skip_if_not_supported(y):
540 msg = "strftime() is limited to [1; 9999] with Visual Studio"
541 # Check that it doesn't crash for year > 9999
542 try:
543 time.strftime('%Y', (y,) + (0,) * 8)
544 except ValueError:
545 cond = False
546 else:
547 cond = True
548 return unittest.skipUnless(cond, msg)
549
550 @skip_if_not_supported(10000)
551 def test_large_year(self):
552 return super().test_large_year()
553
554 @skip_if_not_supported(0)
555 def test_negative(self):
556 return super().test_negative()
557
558 del skip_if_not_supported
559
560
Ezio Melotti3836d702013-04-11 20:29:42 +0300561class _Test4dYear:
Florent Xicluna49ce0682011-11-01 12:56:14 +0100562 _format = '%d'
563
564 def test_year(self, fmt=None, func=None):
565 fmt = fmt or self._format
566 func = func or self.yearstr
567 self.assertEqual(func(1), fmt % 1)
568 self.assertEqual(func(68), fmt % 68)
569 self.assertEqual(func(69), fmt % 69)
570 self.assertEqual(func(99), fmt % 99)
571 self.assertEqual(func(999), fmt % 999)
572 self.assertEqual(func(9999), fmt % 9999)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000573
574 def test_large_year(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100575 self.assertEqual(self.yearstr(12345), '12345')
Victor Stinner13ed2ea2011-03-21 02:11:01 +0100576 self.assertEqual(self.yearstr(123456789), '123456789')
Florent Xiclunabceb5282011-11-01 14:11:34 +0100577 self.assertEqual(self.yearstr(TIME_MAXYEAR), str(TIME_MAXYEAR))
578 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000579
Victor Stinner301f1212011-01-08 03:06:52 +0000580 def test_negative(self):
Florent Xiclunabceb5282011-11-01 14:11:34 +0100581 self.assertEqual(self.yearstr(-1), self._format % -1)
Victor Stinner301f1212011-01-08 03:06:52 +0000582 self.assertEqual(self.yearstr(-1234), '-1234')
583 self.assertEqual(self.yearstr(-123456), '-123456')
Florent Xiclunad1bd7f72011-11-01 23:42:05 +0100584 self.assertEqual(self.yearstr(-123456789), str(-123456789))
585 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
Florent Xicluna2fbc1852011-11-02 08:13:43 +0100586 self.assertEqual(self.yearstr(TIME_MINYEAR + 1900), str(TIME_MINYEAR + 1900))
587 # Issue #13312: it may return wrong value for year < TIME_MINYEAR + 1900
588 # Skip the value test, but check that no error is raised
589 self.yearstr(TIME_MINYEAR)
Florent Xiclunae2a732e2011-11-02 01:28:17 +0100590 # self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
Florent Xiclunabceb5282011-11-01 14:11:34 +0100591 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
Victor Stinner301f1212011-01-08 03:06:52 +0000592
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +0000593
Ezio Melotti3836d702013-04-11 20:29:42 +0300594class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner73ea29c2011-01-08 01:56:31 +0000595 pass
596
Ezio Melotti3836d702013-04-11 20:29:42 +0300597class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
Victor Stinner301f1212011-01-08 03:06:52 +0000598 pass
Victor Stinner73ea29c2011-01-08 01:56:31 +0000599
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000600
Victor Stinner643cd682012-03-02 22:54:03 +0100601class TestPytime(unittest.TestCase):
Victor Stinner5d272cc2012-03-13 13:35:55 +0100602 def setUp(self):
603 self.invalid_values = (
604 -(2 ** 100), 2 ** 100,
605 -(2.0 ** 100.0), 2.0 ** 100.0,
606 )
607
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200608 @support.cpython_only
Victor Stinner5d272cc2012-03-13 13:35:55 +0100609 def test_time_t(self):
610 from _testcapi import pytime_object_to_time_t
Victor Stinner3c1b3792014-02-17 00:02:43 +0100611 for obj, time_t, rnd in (
612 # Round towards zero
Victor Stinner992c43f2015-03-27 17:12:45 +0100613 (0, 0, _PyTime.ROUND_DOWN),
614 (-1, -1, _PyTime.ROUND_DOWN),
615 (-1.0, -1, _PyTime.ROUND_DOWN),
616 (-1.9, -1, _PyTime.ROUND_DOWN),
617 (1.0, 1, _PyTime.ROUND_DOWN),
618 (1.9, 1, _PyTime.ROUND_DOWN),
Victor Stinner3c1b3792014-02-17 00:02:43 +0100619 # Round away from zero
Victor Stinner992c43f2015-03-27 17:12:45 +0100620 (0, 0, _PyTime.ROUND_UP),
621 (-1, -1, _PyTime.ROUND_UP),
622 (-1.0, -1, _PyTime.ROUND_UP),
623 (-1.9, -2, _PyTime.ROUND_UP),
624 (1.0, 1, _PyTime.ROUND_UP),
625 (1.9, 2, _PyTime.ROUND_UP),
Victor Stinner5d272cc2012-03-13 13:35:55 +0100626 ):
Victor Stinner3c1b3792014-02-17 00:02:43 +0100627 self.assertEqual(pytime_object_to_time_t(obj, rnd), time_t)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100628
Victor Stinner992c43f2015-03-27 17:12:45 +0100629 rnd = _PyTime.ROUND_DOWN
Victor Stinner5d272cc2012-03-13 13:35:55 +0100630 for invalid in self.invalid_values:
Victor Stinner3c1b3792014-02-17 00:02:43 +0100631 self.assertRaises(OverflowError,
632 pytime_object_to_time_t, invalid, rnd)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100633
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200634 @support.cpython_only
Victor Stinner5d272cc2012-03-13 13:35:55 +0100635 def test_timeval(self):
636 from _testcapi import pytime_object_to_timeval
Victor Stinner3c1b3792014-02-17 00:02:43 +0100637 for obj, timeval, rnd in (
638 # Round towards zero
Victor Stinner992c43f2015-03-27 17:12:45 +0100639 (0, (0, 0), _PyTime.ROUND_DOWN),
640 (-1, (-1, 0), _PyTime.ROUND_DOWN),
641 (-1.0, (-1, 0), _PyTime.ROUND_DOWN),
642 (1e-6, (0, 1), _PyTime.ROUND_DOWN),
643 (1e-7, (0, 0), _PyTime.ROUND_DOWN),
644 (-1e-6, (-1, 999999), _PyTime.ROUND_DOWN),
645 (-1e-7, (-1, 999999), _PyTime.ROUND_DOWN),
646 (-1.2, (-2, 800000), _PyTime.ROUND_DOWN),
647 (0.9999999, (0, 999999), _PyTime.ROUND_DOWN),
648 (0.0000041, (0, 4), _PyTime.ROUND_DOWN),
649 (1.1234560, (1, 123456), _PyTime.ROUND_DOWN),
650 (1.1234569, (1, 123456), _PyTime.ROUND_DOWN),
651 (-0.0000040, (-1, 999996), _PyTime.ROUND_DOWN),
652 (-0.0000041, (-1, 999995), _PyTime.ROUND_DOWN),
653 (-1.1234560, (-2, 876544), _PyTime.ROUND_DOWN),
654 (-1.1234561, (-2, 876543), _PyTime.ROUND_DOWN),
Victor Stinner3c1b3792014-02-17 00:02:43 +0100655 # Round away from zero
Victor Stinner992c43f2015-03-27 17:12:45 +0100656 (0, (0, 0), _PyTime.ROUND_UP),
657 (-1, (-1, 0), _PyTime.ROUND_UP),
658 (-1.0, (-1, 0), _PyTime.ROUND_UP),
659 (1e-6, (0, 1), _PyTime.ROUND_UP),
660 (1e-7, (0, 1), _PyTime.ROUND_UP),
661 (-1e-6, (-1, 999999), _PyTime.ROUND_UP),
662 (-1e-7, (-1, 999999), _PyTime.ROUND_UP),
663 (-1.2, (-2, 800000), _PyTime.ROUND_UP),
664 (0.9999999, (1, 0), _PyTime.ROUND_UP),
665 (0.0000041, (0, 5), _PyTime.ROUND_UP),
666 (1.1234560, (1, 123457), _PyTime.ROUND_UP),
667 (1.1234569, (1, 123457), _PyTime.ROUND_UP),
668 (-0.0000040, (-1, 999996), _PyTime.ROUND_UP),
669 (-0.0000041, (-1, 999995), _PyTime.ROUND_UP),
670 (-1.1234560, (-2, 876544), _PyTime.ROUND_UP),
671 (-1.1234561, (-2, 876543), _PyTime.ROUND_UP),
Victor Stinner5d272cc2012-03-13 13:35:55 +0100672 ):
Victor Stinner3c1b3792014-02-17 00:02:43 +0100673 with self.subTest(obj=obj, round=rnd, timeval=timeval):
674 self.assertEqual(pytime_object_to_timeval(obj, rnd), timeval)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100675
Victor Stinner992c43f2015-03-27 17:12:45 +0100676 rnd = _PyTime.ROUND_DOWN
Victor Stinner5d272cc2012-03-13 13:35:55 +0100677 for invalid in self.invalid_values:
Victor Stinner3c1b3792014-02-17 00:02:43 +0100678 self.assertRaises(OverflowError,
679 pytime_object_to_timeval, invalid, rnd)
Victor Stinner5d272cc2012-03-13 13:35:55 +0100680
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +0200681 @support.cpython_only
Victor Stinner643cd682012-03-02 22:54:03 +0100682 def test_timespec(self):
683 from _testcapi import pytime_object_to_timespec
Victor Stinner3c1b3792014-02-17 00:02:43 +0100684 for obj, timespec, rnd in (
685 # Round towards zero
Victor Stinner992c43f2015-03-27 17:12:45 +0100686 (0, (0, 0), _PyTime.ROUND_DOWN),
687 (-1, (-1, 0), _PyTime.ROUND_DOWN),
688 (-1.0, (-1, 0), _PyTime.ROUND_DOWN),
689 (1e-9, (0, 1), _PyTime.ROUND_DOWN),
690 (1e-10, (0, 0), _PyTime.ROUND_DOWN),
691 (-1e-9, (-1, 999999999), _PyTime.ROUND_DOWN),
692 (-1e-10, (-1, 999999999), _PyTime.ROUND_DOWN),
693 (-1.2, (-2, 800000000), _PyTime.ROUND_DOWN),
694 (0.9999999999, (0, 999999999), _PyTime.ROUND_DOWN),
695 (1.1234567890, (1, 123456789), _PyTime.ROUND_DOWN),
696 (1.1234567899, (1, 123456789), _PyTime.ROUND_DOWN),
697 (-1.1234567890, (-2, 876543211), _PyTime.ROUND_DOWN),
698 (-1.1234567891, (-2, 876543210), _PyTime.ROUND_DOWN),
Victor Stinner3c1b3792014-02-17 00:02:43 +0100699 # Round away from zero
Victor Stinner992c43f2015-03-27 17:12:45 +0100700 (0, (0, 0), _PyTime.ROUND_UP),
701 (-1, (-1, 0), _PyTime.ROUND_UP),
702 (-1.0, (-1, 0), _PyTime.ROUND_UP),
703 (1e-9, (0, 1), _PyTime.ROUND_UP),
704 (1e-10, (0, 1), _PyTime.ROUND_UP),
705 (-1e-9, (-1, 999999999), _PyTime.ROUND_UP),
706 (-1e-10, (-1, 999999999), _PyTime.ROUND_UP),
707 (-1.2, (-2, 800000000), _PyTime.ROUND_UP),
708 (0.9999999999, (1, 0), _PyTime.ROUND_UP),
709 (1.1234567890, (1, 123456790), _PyTime.ROUND_UP),
710 (1.1234567899, (1, 123456790), _PyTime.ROUND_UP),
711 (-1.1234567890, (-2, 876543211), _PyTime.ROUND_UP),
712 (-1.1234567891, (-2, 876543210), _PyTime.ROUND_UP),
Victor Stinner643cd682012-03-02 22:54:03 +0100713 ):
Victor Stinner3c1b3792014-02-17 00:02:43 +0100714 with self.subTest(obj=obj, round=rnd, timespec=timespec):
715 self.assertEqual(pytime_object_to_timespec(obj, rnd), timespec)
Victor Stinner643cd682012-03-02 22:54:03 +0100716
Victor Stinner992c43f2015-03-27 17:12:45 +0100717 rnd = _PyTime.ROUND_DOWN
Victor Stinner5d272cc2012-03-13 13:35:55 +0100718 for invalid in self.invalid_values:
Victor Stinner3c1b3792014-02-17 00:02:43 +0100719 self.assertRaises(OverflowError,
720 pytime_object_to_timespec, invalid, rnd)
Victor Stinner643cd682012-03-02 22:54:03 +0100721
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400722 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
723 def test_localtime_timezone(self):
Victor Stinner643cd682012-03-02 22:54:03 +0100724
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400725 # Get the localtime and examine it for the offset and zone.
726 lt = time.localtime()
727 self.assertTrue(hasattr(lt, "tm_gmtoff"))
728 self.assertTrue(hasattr(lt, "tm_zone"))
729
730 # See if the offset and zone are similar to the module
731 # attributes.
732 if lt.tm_gmtoff is None:
733 self.assertTrue(not hasattr(time, "timezone"))
734 else:
735 self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
736 if lt.tm_zone is None:
737 self.assertTrue(not hasattr(time, "tzname"))
738 else:
739 self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
740
741 # Try and make UNIX times from the localtime and a 9-tuple
742 # created from the localtime. Test to see that the times are
743 # the same.
744 t = time.mktime(lt); t9 = time.mktime(lt[:9])
745 self.assertEqual(t, t9)
746
747 # Make localtimes from the UNIX times and compare them to
748 # the original localtime, thus making a round trip.
749 new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
750 self.assertEqual(new_lt, lt)
751 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
752 self.assertEqual(new_lt.tm_zone, lt.tm_zone)
753 self.assertEqual(new_lt9, lt)
754 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
755 self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
756
757 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
758 def test_strptime_timezone(self):
759 t = time.strptime("UTC", "%Z")
760 self.assertEqual(t.tm_zone, 'UTC')
761 t = time.strptime("+0500", "%z")
762 self.assertEqual(t.tm_gmtoff, 5 * 3600)
763
764 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
765 def test_short_times(self):
766
767 import pickle
768
769 # Load a short time structure using pickle.
770 st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
771 lt = pickle.loads(st)
772 self.assertIs(lt.tm_gmtoff, None)
773 self.assertIs(lt.tm_zone, None)
Victor Stinner643cd682012-03-02 22:54:03 +0100774
Fred Drake2e2be372001-09-20 21:33:42 +0000775
Victor Stinner34dc0f42015-03-27 18:19:03 +0100776@unittest.skipUnless(_testcapi is not None,
777 'need the _testcapi module')
Victor Stinner992c43f2015-03-27 17:12:45 +0100778class TestPyTime_t(unittest.TestCase):
779 def test_FromSecondsObject(self):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100780 from _testcapi import PyTime_FromSecondsObject
Victor Stinner992c43f2015-03-27 17:12:45 +0100781
782 # Conversion giving the same result for all rounding methods
783 for rnd in ALL_ROUNDING_METHODS:
784 for obj, ts in (
785 # integers
786 (0, 0),
787 (1, SEC_TO_NS),
788 (-3, -3 * SEC_TO_NS),
789
790 # float: subseconds
791 (0.0, 0),
792 (1e-9, 1),
793 (1e-6, 10 ** 3),
794 (1e-3, 10 ** 6),
795
796 # float: seconds
797 (2.0, 2 * SEC_TO_NS),
798 (123.0, 123 * SEC_TO_NS),
799 (-7.0, -7 * SEC_TO_NS),
800
801 # nanosecond are kept for value <= 2^23 seconds
802 (2**22 - 1e-9, 4194303999999999),
803 (2**22, 4194304000000000),
804 (2**22 + 1e-9, 4194304000000001),
805 (2**23 - 1e-9, 8388607999999999),
806 (2**23, 8388608000000000),
807
808 # start loosing precision for value > 2^23 seconds
809 (2**23 + 1e-9, 8388608000000002),
810
811 # nanoseconds are lost for value > 2^23 seconds
812 (2**24 - 1e-9, 16777215999999998),
813 (2**24, 16777216000000000),
814 (2**24 + 1e-9, 16777216000000000),
815 (2**25 - 1e-9, 33554432000000000),
816 (2**25 , 33554432000000000),
817 (2**25 + 1e-9, 33554432000000000),
818
Victor Stinner4bfb4602015-03-27 22:27:24 +0100819 # close to 2^63 nanoseconds (_PyTime_t limit)
Victor Stinner992c43f2015-03-27 17:12:45 +0100820 (9223372036, 9223372036 * SEC_TO_NS),
821 (9223372036.0, 9223372036 * SEC_TO_NS),
822 (-9223372036, -9223372036 * SEC_TO_NS),
823 (-9223372036.0, -9223372036 * SEC_TO_NS),
824 ):
825 with self.subTest(obj=obj, round=rnd, timestamp=ts):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100826 self.assertEqual(PyTime_FromSecondsObject(obj, rnd), ts)
Victor Stinner992c43f2015-03-27 17:12:45 +0100827
828 with self.subTest(round=rnd):
829 with self.assertRaises(OverflowError):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100830 PyTime_FromSecondsObject(9223372037, rnd)
831 PyTime_FromSecondsObject(9223372037.0, rnd)
832 PyTime_FromSecondsObject(-9223372037, rnd)
833 PyTime_FromSecondsObject(-9223372037.0, rnd)
Victor Stinner992c43f2015-03-27 17:12:45 +0100834
835 # Conversion giving different results depending on the rounding method
836 UP = _PyTime.ROUND_UP
837 DOWN = _PyTime.ROUND_DOWN
838 for obj, ts, rnd in (
839 # close to zero
840 ( 1e-10, 1, UP),
841 ( 1e-10, 0, DOWN),
842 (-1e-10, 0, DOWN),
843 (-1e-10, -1, UP),
844
845 # test rounding of the last nanosecond
846 ( 1.1234567899, 1123456790, UP),
847 ( 1.1234567899, 1123456789, DOWN),
848 (-1.1234567899, -1123456789, DOWN),
849 (-1.1234567899, -1123456790, UP),
850
851 # close to 1 second
852 ( 0.9999999999, 1000000000, UP),
853 ( 0.9999999999, 999999999, DOWN),
854 (-0.9999999999, -999999999, DOWN),
855 (-0.9999999999, -1000000000, UP),
856 ):
857 with self.subTest(obj=obj, round=rnd, timestamp=ts):
Victor Stinner4bfb4602015-03-27 22:27:24 +0100858 self.assertEqual(PyTime_FromSecondsObject(obj, rnd), ts)
859
860 def test_AsSecondsDouble(self):
861 from _testcapi import PyTime_AsSecondsDouble
862
863 for nanoseconds, seconds in (
864 # near 1 nanosecond
865 ( 0, 0.0),
866 ( 1, 1e-9),
867 (-1, -1e-9),
868
869 # near 1 second
870 (SEC_TO_NS + 1, 1.0 + 1e-9),
871 (SEC_TO_NS, 1.0),
872 (SEC_TO_NS - 1, 1.0 - 1e-9),
873
874 # a few seconds
875 (123 * SEC_TO_NS, 123.0),
876 (-567 * SEC_TO_NS, -567.0),
877
878 # nanosecond are kept for value <= 2^23 seconds
879 (4194303999999999, 2**22 - 1e-9),
880 (4194304000000000, 2**22),
881 (4194304000000001, 2**22 + 1e-9),
882
883 # start loosing precision for value > 2^23 seconds
884 (8388608000000002, 2**23 + 1e-9),
885
886 # nanoseconds are lost for value > 2^23 seconds
887 (16777215999999998, 2**24 - 1e-9),
888 (16777215999999999, 2**24 - 1e-9),
889 (16777216000000000, 2**24 ),
890 (16777216000000001, 2**24 ),
891 (16777216000000002, 2**24 + 2e-9),
892
893 (33554432000000000, 2**25 ),
894 (33554432000000002, 2**25 ),
895 (33554432000000004, 2**25 + 4e-9),
896
897 # close to 2^63 nanoseconds (_PyTime_t limit)
898 (9223372036 * SEC_TO_NS, 9223372036.0),
899 (-9223372036 * SEC_TO_NS, -9223372036.0),
900 ):
901 with self.subTest(nanoseconds=nanoseconds, seconds=seconds):
902 self.assertEqual(PyTime_AsSecondsDouble(nanoseconds),
903 seconds)
Victor Stinner992c43f2015-03-27 17:12:45 +0100904
Victor Stinner95e9cef2015-03-28 01:26:47 +0100905 def test_timeval(self):
906 from _testcapi import PyTime_AsTimeval
907 for rnd in ALL_ROUNDING_METHODS:
908 for ns, tv in (
909 # microseconds
910 (0, (0, 0)),
911 (1000, (0, 1)),
912 (-1000, (-1, 999999)),
913
914 # seconds
915 (2 * SEC_TO_NS, (2, 0)),
916 (-3 * SEC_TO_NS, (-3, 0)),
917
918 # seconds + nanoseconds
919 (1234567000, (1, 234567)),
920 (-1234567000, (-2, 765433)),
921 ):
922 with self.subTest(nanoseconds=ns, timeval=tv, round=rnd):
923 self.assertEqual(PyTime_AsTimeval(ns, rnd), tv)
924
925 UP = _PyTime.ROUND_UP
926 DOWN = _PyTime.ROUND_DOWN
927 for ns, tv, rnd in (
928 # nanoseconds
929 (1, (0, 1), UP),
930 (1, (0, 0), DOWN),
931 (-1, (0, 0), DOWN),
932 (-1, (-1, 999999), UP),
933
934 # seconds + nanoseconds
935 (1234567001, (1, 234568), UP),
936 (1234567001, (1, 234567), DOWN),
937 (-1234567001, (-2, 765433), DOWN),
938 (-1234567001, (-2, 765432), UP),
939 ):
940 with self.subTest(nanoseconds=ns, timeval=tv, round=rnd):
941 self.assertEqual(PyTime_AsTimeval(ns, rnd), tv)
942
Victor Stinner34dc0f42015-03-27 18:19:03 +0100943 @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec'),
944 'need _testcapi.PyTime_AsTimespec')
945 def test_timespec(self):
946 from _testcapi import PyTime_AsTimespec
947 for ns, ts in (
948 # nanoseconds
949 (0, (0, 0)),
950 (1, (0, 1)),
951 (-1, (-1, 999999999)),
952
953 # seconds
954 (2 * SEC_TO_NS, (2, 0)),
955 (-3 * SEC_TO_NS, (-3, 0)),
956
957 # seconds + nanoseconds
958 (1234567890, (1, 234567890)),
959 (-1234567890, (-2, 765432110)),
960 ):
961 with self.subTest(nanoseconds=ns, timespec=ts):
962 self.assertEqual(PyTime_AsTimespec(ns), ts)
963
Victor Stinner992c43f2015-03-27 17:12:45 +0100964
Fred Drake2e2be372001-09-20 21:33:42 +0000965if __name__ == "__main__":
Ezio Melotti3836d702013-04-11 20:29:42 +0300966 unittest.main()