Debian Codegraph @

Lib/test/test_time.py

raw
1 from test import support
2 from test.support import warnings_helper
3 import decimal
4 import enum
5 import math
6 import platform
7 import sys
8 import sysconfig
9 import time
10 import threading
11 import unittest
12 try:
13 import _testcapi
14 except ImportError:
15 _testcapi = None
16 try:
17 import _testinternalcapi
18 except ImportError:
19 _testinternalcapi = None
20
21 from test.support import skip_if_buggy_ucrt_strfptime, SuppressCrashReport
22
23 # Max year is only limited by the size of C int.
24 SIZEOF_INT = sysconfig.get_config_var('SIZEOF_INT') or 4
25 TIME_MAXYEAR = (1 << 8 * SIZEOF_INT - 1) - 1
26 TIME_MINYEAR = -TIME_MAXYEAR - 1 + 1900
27
28 SEC_TO_US = 10 ** 6
29 US_TO_NS = 10 ** 3
30 MS_TO_NS = 10 ** 6
31 SEC_TO_NS = 10 ** 9
32 NS_TO_SEC = 10 ** 9
33
34 class _PyTime(enum.IntEnum):
35 # Round towards minus infinity (-inf)
36 ROUND_FLOOR = 0
37 # Round towards infinity (+inf)
38 ROUND_CEILING = 1
39 # Round to nearest with ties going to nearest even integer
40 ROUND_HALF_EVEN = 2
41 # Round away from zero
42 ROUND_UP = 3
43
44 # _PyTime_t is int64_t
45 PyTime_MIN = -2 ** 63
46 PyTime_MAX = 2 ** 63 - 1
47
48 # Rounding modes supported by PyTime
49 ROUNDING_MODES = (
50 # (PyTime rounding method, decimal rounding method)
51 (_PyTime.ROUND_FLOOR, decimal.ROUND_FLOOR),
52 (_PyTime.ROUND_CEILING, decimal.ROUND_CEILING),
53 (_PyTime.ROUND_HALF_EVEN, decimal.ROUND_HALF_EVEN),
54 (_PyTime.ROUND_UP, decimal.ROUND_UP),
55 )
56
57
58 class TimeTestCase(unittest.TestCase):
59
60 def setUp(self):
61 self.t = time.time()
62
63 def test_data_attributes(self):
64 time.altzone
65 time.daylight
66 time.timezone
67 time.tzname
68
69 def test_time(self):
70 time.time()
71 info = time.get_clock_info('time')
72 self.assertFalse(info.monotonic)
73 self.assertTrue(info.adjustable)
74
75 def test_time_ns_type(self):
76 def check_ns(sec, ns):
77 self.assertIsInstance(ns, int)
78
79 sec_ns = int(sec * 1e9)
80 # tolerate a difference of 50 ms
81 self.assertLess((sec_ns - ns), 50 ** 6, (sec, ns))
82
83 check_ns(time.time(),
84 time.time_ns())
85 check_ns(time.monotonic(),
86 time.monotonic_ns())
87 check_ns(time.perf_counter(),
88 time.perf_counter_ns())
89 check_ns(time.process_time(),
90 time.process_time_ns())
91
92 if hasattr(time, 'thread_time'):
93 check_ns(time.thread_time(),
94 time.thread_time_ns())
95
96 if hasattr(time, 'clock_gettime'):
97 check_ns(time.clock_gettime(time.CLOCK_REALTIME),
98 time.clock_gettime_ns(time.CLOCK_REALTIME))
99
100 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
101 'need time.clock_gettime()')
102 def test_clock_realtime(self):
103 t = time.clock_gettime(time.CLOCK_REALTIME)
104 self.assertIsInstance(t, float)
105
106 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
107 'need time.clock_gettime()')
108 @unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'),
109 'need time.CLOCK_MONOTONIC')
110 def test_clock_monotonic(self):
111 a = time.clock_gettime(time.CLOCK_MONOTONIC)
112 b = time.clock_gettime(time.CLOCK_MONOTONIC)
113 self.assertLessEqual(a, b)
114
115 @unittest.skipUnless(hasattr(time, 'pthread_getcpuclockid'),
116 'need time.pthread_getcpuclockid()')
117 @unittest.skipUnless(hasattr(time, 'clock_gettime'),
118 'need time.clock_gettime()')
119 def test_pthread_getcpuclockid(self):
120 clk_id = time.pthread_getcpuclockid(threading.get_ident())
121 self.assertTrue(type(clk_id) is int)
122 # when in 32-bit mode AIX only returns the predefined constant
123 if platform.system() == "AIX" and (sys.maxsize.bit_length() <= 32):
124 self.assertEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
125 # Solaris returns CLOCK_THREAD_CPUTIME_ID when current thread is given
126 elif sys.platform.startswith("sunos"):
127 self.assertEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
128 else:
129 self.assertNotEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
130 t1 = time.clock_gettime(clk_id)
131 t2 = time.clock_gettime(clk_id)
132 self.assertLessEqual(t1, t2)
133
134 @unittest.skipUnless(hasattr(time, 'clock_getres'),
135 'need time.clock_getres()')
136 def test_clock_getres(self):
137 res = time.clock_getres(time.CLOCK_REALTIME)
138 self.assertGreater(res, 0.0)
139 self.assertLessEqual(res, 1.0)
140
141 @unittest.skipUnless(hasattr(time, 'clock_settime'),
142 'need time.clock_settime()')
143 def test_clock_settime(self):
144 t = time.clock_gettime(time.CLOCK_REALTIME)
145 try:
146 time.clock_settime(time.CLOCK_REALTIME, t)
147 except PermissionError:
148 pass
149
150 if hasattr(time, 'CLOCK_MONOTONIC'):
151 self.assertRaises(OSError,
152 time.clock_settime, time.CLOCK_MONOTONIC, 0)
153
154 def test_conversions(self):
155 self.assertEqual(time.ctime(self.t),
156 time.asctime(time.localtime(self.t)))
157 self.assertEqual(int(time.mktime(time.localtime(self.t))),
158 int(self.t))
159
160 def test_sleep_exceptions(self):
161 self.assertRaises(TypeError, time.sleep, [])
162 self.assertRaises(TypeError, time.sleep, "a")
163 self.assertRaises(TypeError, time.sleep, complex(0, 0))
164
165 self.assertRaises(ValueError, time.sleep, -2)
166 self.assertRaises(ValueError, time.sleep, -1)
167 self.assertRaises(ValueError, time.sleep, -0.1)
168
169 def test_sleep(self):
170 for value in [-0.0, 0, 0.0, 1e-100, 1e-9, 1e-6, 1, 1.2]:
171 with self.subTest(value=value):
172 time.sleep(value)
173
174 def test_epoch(self):
175 # bpo-43869: Make sure that Python use the same Epoch on all platforms:
176 # January 1, 1970, 00:00:00 (UTC).
177 epoch = time.gmtime(0)
178 # Only test the date and time, ignore other gmtime() members
179 self.assertEqual(tuple(epoch)[:6], (1970, 1, 1, 0, 0, 0), epoch)
180
181 def test_strftime(self):
182 tt = time.gmtime(self.t)
183 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
184 'j', 'm', 'M', 'p', 'S',
185 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
186 format = ' %' + directive
187 try:
188 time.strftime(format, tt)
189 except ValueError:
190 self.fail('conversion specifier: %r failed.' % format)
191
192 self.assertRaises(TypeError, time.strftime, b'%S', tt)
193
194 def test_strftime_invalid_format(self):
195 tt = time.gmtime(self.t)
196 with SuppressCrashReport():
197 for i in range(1, 128):
198 format = ' %' + chr(i)
199 with self.subTest(format=format):
200 try:
201 time.strftime(format, tt)
202 except ValueError as exc:
203 self.assertEqual(str(exc), 'Invalid format string')
204
205 def test_strftime_special(self):
206 tt = time.gmtime(self.t)
207 s1 = time.strftime('%c', tt)
208 s2 = time.strftime('%B', tt)
209 # gh-52551, gh-78662: Unicode strings should pass through strftime,
210 # independently from locale.
211 self.assertEqual(time.strftime('\U0001f40d', tt), '\U0001f40d')
212 self.assertEqual(time.strftime('\U0001f4bb%c\U0001f40d%B', tt), f'\U0001f4bb{s1}\U0001f40d{s2}')
213 self.assertEqual(time.strftime('%c\U0001f4bb%B\U0001f40d', tt), f'{s1}\U0001f4bb{s2}\U0001f40d')
214 # Lone surrogates should pass through.
215 self.assertEqual(time.strftime('\ud83d', tt), '\ud83d')
216 self.assertEqual(time.strftime('\udc0d', tt), '\udc0d')
217 self.assertEqual(time.strftime('\ud83d%c\udc0d%B', tt), f'\ud83d{s1}\udc0d{s2}')
218 self.assertEqual(time.strftime('%c\ud83d%B\udc0d', tt), f'{s1}\ud83d{s2}\udc0d')
219 self.assertEqual(time.strftime('%c\udc0d%B\ud83d', tt), f'{s1}\udc0d{s2}\ud83d')
220 # Surrogate pairs should not recombine.
221 self.assertEqual(time.strftime('\ud83d\udc0d', tt), '\ud83d\udc0d')
222 self.assertEqual(time.strftime('%c\ud83d\udc0d%B', tt), f'{s1}\ud83d\udc0d{s2}')
223 # Surrogate-escaped bytes should not recombine.
224 self.assertEqual(time.strftime('\udcf0\udc9f\udc90\udc8d', tt), '\udcf0\udc9f\udc90\udc8d')
225 self.assertEqual(time.strftime('%c\udcf0\udc9f\udc90\udc8d%B', tt), f'{s1}\udcf0\udc9f\udc90\udc8d{s2}')
226 # gh-124531: The null character should not terminate the format string.
227 self.assertEqual(time.strftime('\0', tt), '\0')
228 self.assertEqual(time.strftime('\0'*1000, tt), '\0'*1000)
229 self.assertEqual(time.strftime('\0%c\0%B', tt), f'\0{s1}\0{s2}')
230 self.assertEqual(time.strftime('%c\0%B\0', tt), f'{s1}\0{s2}\0')
231
232 def _bounds_checking(self, func):
233 # Make sure that strftime() checks the bounds of the various parts
234 # of the time tuple (0 is valid for *all* values).
235
236 # The year field is tested by other test cases above
237
238 # Check month [1, 12] + zero support
239 func((1900, 0, 1, 0, 0, 0, 0, 1, -1))
240 func((1900, 12, 1, 0, 0, 0, 0, 1, -1))
241 self.assertRaises(ValueError, func,
242 (1900, -1, 1, 0, 0, 0, 0, 1, -1))
243 self.assertRaises(ValueError, func,
244 (1900, 13, 1, 0, 0, 0, 0, 1, -1))
245 # Check day of month [1, 31] + zero support
246 func((1900, 1, 0, 0, 0, 0, 0, 1, -1))
247 func((1900, 1, 31, 0, 0, 0, 0, 1, -1))
248 self.assertRaises(ValueError, func,
249 (1900, 1, -1, 0, 0, 0, 0, 1, -1))
250 self.assertRaises(ValueError, func,
251 (1900, 1, 32, 0, 0, 0, 0, 1, -1))
252 # Check hour [0, 23]
253 func((1900, 1, 1, 23, 0, 0, 0, 1, -1))
254 self.assertRaises(ValueError, func,
255 (1900, 1, 1, -1, 0, 0, 0, 1, -1))
256 self.assertRaises(ValueError, func,
257 (1900, 1, 1, 24, 0, 0, 0, 1, -1))
258 # Check minute [0, 59]
259 func((1900, 1, 1, 0, 59, 0, 0, 1, -1))
260 self.assertRaises(ValueError, func,
261 (1900, 1, 1, 0, -1, 0, 0, 1, -1))
262 self.assertRaises(ValueError, func,
263 (1900, 1, 1, 0, 60, 0, 0, 1, -1))
264 # Check second [0, 61]
265 self.assertRaises(ValueError, func,
266 (1900, 1, 1, 0, 0, -1, 0, 1, -1))
267 # C99 only requires allowing for one leap second, but Python's docs say
268 # allow two leap seconds (0..61)
269 func((1900, 1, 1, 0, 0, 60, 0, 1, -1))
270 func((1900, 1, 1, 0, 0, 61, 0, 1, -1))
271 self.assertRaises(ValueError, func,
272 (1900, 1, 1, 0, 0, 62, 0, 1, -1))
273 # No check for upper-bound day of week;
274 # value forced into range by a ``% 7`` calculation.
275 # Start check at -2 since gettmarg() increments value before taking
276 # modulo.
277 self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)),
278 func((1900, 1, 1, 0, 0, 0, +6, 1, -1)))
279 self.assertRaises(ValueError, func,
280 (1900, 1, 1, 0, 0, 0, -2, 1, -1))
281 # Check day of the year [1, 366] + zero support
282 func((1900, 1, 1, 0, 0, 0, 0, 0, -1))
283 func((1900, 1, 1, 0, 0, 0, 0, 366, -1))
284 self.assertRaises(ValueError, func,
285 (1900, 1, 1, 0, 0, 0, 0, -1, -1))
286 self.assertRaises(ValueError, func,
287 (1900, 1, 1, 0, 0, 0, 0, 367, -1))
288
289 def test_strftime_bounding_check(self):
290 self._bounds_checking(lambda tup: time.strftime('', tup))
291
292 def test_strftime_format_check(self):
293 # Test that strftime does not crash on invalid format strings
294 # that may trigger a buffer overread. When not triggered,
295 # strftime may succeed or raise ValueError depending on
296 # the platform.
297 for x in [ '', 'A', '%A', '%AA' ]:
298 for y in range(0x0, 0x10):
299 for z in [ '%', 'A%', 'AA%', '%A%', 'A%A%', '%#' ]:
300 try:
301 time.strftime(x * y + z)
302 except ValueError:
303 pass
304
305 def test_default_values_for_zero(self):
306 # Make sure that using all zeros uses the proper default
307 # values. No test for daylight savings since strftime() does
308 # not change output based on its value and no test for year
309 # because systems vary in their support for year 0.
310 expected = "2000 01 01 00 00 00 1 001"
311 with warnings_helper.check_warnings():
312 result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
313 self.assertEqual(expected, result)
314
315 @skip_if_buggy_ucrt_strfptime
316 def test_strptime(self):
317 # Should be able to go round-trip from strftime to strptime without
318 # raising an exception.
319 tt = time.gmtime(self.t)
320 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
321 'j', 'm', 'M', 'p', 'S',
322 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
323 format = '%' + directive
324 if directive == 'd':
325 format += ',%Y' # Avoid GH-70647.
326 strf_output = time.strftime(format, tt)
327 try:
328 time.strptime(strf_output, format)
329 except ValueError:
330 self.fail("conversion specifier %r failed with '%s' input." %
331 (format, strf_output))
332
333 def test_strptime_bytes(self):
334 # Make sure only strings are accepted as arguments to strptime.
335 self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
336 self.assertRaises(TypeError, time.strptime, '2009', b'%Y')
337
338 def test_strptime_exception_context(self):
339 # check that this doesn't chain exceptions needlessly (see #17572)
340 with self.assertRaises(ValueError) as e:
341 time.strptime('', '%D')
342 self.assertTrue(e.exception.__suppress_context__)
343 # additional check for stray % branch
344 with self.assertRaises(ValueError) as e:
345 time.strptime('%', '%')
346 self.assertTrue(e.exception.__suppress_context__)
347
348 def test_strptime_leap_year(self):
349 # GH-70647: warns if parsing a format with a day and no year.
350 with self.assertWarnsRegex(DeprecationWarning,
351 r'.*day of month without a year.*'):
352 time.strptime('02-07 18:28', '%m-%d %H:%M')
353
354 def test_asctime(self):
355 time.asctime(time.gmtime(self.t))
356
357 # Max year is only limited by the size of C int.
358 for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
359 asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
360 self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
361 self.assertRaises(OverflowError, time.asctime,
362 (TIME_MAXYEAR + 1,) + (0,) * 8)
363 self.assertRaises(OverflowError, time.asctime,
364 (TIME_MINYEAR - 1,) + (0,) * 8)
365 self.assertRaises(TypeError, time.asctime, 0)
366 self.assertRaises(TypeError, time.asctime, ())
367 self.assertRaises(TypeError, time.asctime, (0,) * 10)
368
369 def test_asctime_bounding_check(self):
370 self._bounds_checking(time.asctime)
371
372 @unittest.skipIf(
373 support.is_emscripten, "musl libc issue on Emscripten, bpo-46390"
374 )
375 def test_ctime(self):
376 t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
377 self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
378 t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
379 self.assertEqual(time.ctime(t), 'Sat Jan 1 00:00:00 2000')
380 for year in [-100, 100, 1000, 2000, 2050, 10000]:
381 try:
382 testval = time.mktime((year, 1, 10) + (0,)*6)
383 except (ValueError, OverflowError):
384 # If mktime fails, ctime will fail too. This may happen
385 # on some platforms.
386 pass
387 else:
388 self.assertEqual(time.ctime(testval)[20:], str(year))
389
390 @unittest.skipUnless(hasattr(time, "tzset"),
391 "time module has no attribute tzset")
392 def test_tzset(self):
393
394 from os import environ
395
396 # Epoch time of midnight Dec 25th 2002. Never DST in northern
397 # hemisphere.
398 xmas2002 = 1040774400.0
399
400 # These formats are correct for 2002, and possibly future years
401 # This format is the 'standard' as documented at:
402 # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
403 # They are also documented in the tzset(3) man page on most Unix
404 # systems.
405 eastern = 'EST+05EDT,M4.1.0,M10.5.0'
406 victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
407 utc='UTC+0'
408
409 org_TZ = environ.get('TZ',None)
410 try:
411 # Make sure we can switch to UTC time and results are correct
412 # Note that unknown timezones default to UTC.
413 # Note that altzone is undefined in UTC, as there is no DST
414 environ['TZ'] = eastern
415 time.tzset()
416 environ['TZ'] = utc
417 time.tzset()
418 self.assertEqual(
419 time.gmtime(xmas2002), time.localtime(xmas2002)
420 )
421 self.assertEqual(time.daylight, 0)
422 self.assertEqual(time.timezone, 0)
423 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
424
425 # Make sure we can switch to US/Eastern
426 environ['TZ'] = eastern
427 time.tzset()
428 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
429 self.assertEqual(time.tzname, ('EST', 'EDT'))
430 self.assertEqual(len(time.tzname), 2)
431 self.assertEqual(time.daylight, 1)
432 self.assertEqual(time.timezone, 18000)
433 self.assertEqual(time.altzone, 14400)
434 self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
435 self.assertEqual(len(time.tzname), 2)
436
437 # Now go to the southern hemisphere.
438 environ['TZ'] = victoria
439 time.tzset()
440 self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
441
442 # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
443 # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
444 # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
445 # on some operating systems (e.g. FreeBSD), which is wrong. See for
446 # example this bug:
447 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
448 self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
449 self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
450 self.assertEqual(len(time.tzname), 2)
451 self.assertEqual(time.daylight, 1)
452 self.assertEqual(time.timezone, -36000)
453 self.assertEqual(time.altzone, -39600)
454 self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
455
456 finally:
457 # Repair TZ environment variable in case any other tests
458 # rely on it.
459 if org_TZ is not None:
460 environ['TZ'] = org_TZ
461 elif 'TZ' in environ:
462 del environ['TZ']
463 time.tzset()
464
465 def test_insane_timestamps(self):
466 # It's possible that some platform maps time_t to double,
467 # and that this test will fail there. This test should
468 # exempt such platforms (provided they return reasonable
469 # results!).
470 for func in time.ctime, time.gmtime, time.localtime:
471 for unreasonable in -1e200, 1e200:
472 self.assertRaises(OverflowError, func, unreasonable)
473
474 def test_ctime_without_arg(self):
475 # Not sure how to check the values, since the clock could tick
476 # at any time. Make sure these are at least accepted and
477 # don't raise errors.
478 time.ctime()
479 time.ctime(None)
480
481 def test_gmtime_without_arg(self):
482 gt0 = time.gmtime()
483 gt1 = time.gmtime(None)
484 t0 = time.mktime(gt0)
485 t1 = time.mktime(gt1)
486 self.assertAlmostEqual(t1, t0, delta=0.2)
487
488 def test_localtime_without_arg(self):
489 lt0 = time.localtime()
490 lt1 = time.localtime(None)
491 t0 = time.mktime(lt0)
492 t1 = time.mktime(lt1)
493 self.assertAlmostEqual(t1, t0, delta=0.2)
494
495 def test_mktime(self):
496 # Issue #1726687
497 for t in (-2, -1, 0, 1):
498 try:
499 tt = time.localtime(t)
500 except (OverflowError, OSError):
501 pass
502 else:
503 self.assertEqual(time.mktime(tt), t)
504
505 # Issue #13309: passing extreme values to mktime() or localtime()
506 # borks the glibc's internal timezone data.
507 @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
508 "disabled because of a bug in glibc. Issue #13309")
509 def test_mktime_error(self):
510 # It may not be possible to reliably make mktime return an error
511 # on all platforms. This will make sure that no other exception
512 # than OverflowError is raised for an extreme value.
513 tt = time.gmtime(self.t)
514 tzname = time.strftime('%Z', tt)
515 self.assertNotEqual(tzname, 'LMT')
516 try:
517 time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
518 except OverflowError:
519 pass
520 self.assertEqual(time.strftime('%Z', tt), tzname)
521
522 def test_monotonic(self):
523 # monotonic() should not go backward
524 times = [time.monotonic() for n in range(100)]
525 t1 = times[0]
526 for t2 in times[1:]:
527 self.assertGreaterEqual(t2, t1, "times=%s" % times)
528 t1 = t2
529
530 # monotonic() includes time elapsed during a sleep
531 t1 = time.monotonic()
532 time.sleep(0.5)
533 t2 = time.monotonic()
534 dt = t2 - t1
535 self.assertGreater(t2, t1)
536 # bpo-20101: tolerate a difference of 50 ms because of bad timer
537 # resolution on Windows
538 self.assertTrue(0.450 <= dt)
539
540 # monotonic() is a monotonic but non adjustable clock
541 info = time.get_clock_info('monotonic')
542 self.assertTrue(info.monotonic)
543 self.assertFalse(info.adjustable)
544
545 def test_perf_counter(self):
546 time.perf_counter()
547
548 @unittest.skipIf(
549 support.is_wasi, "process_time not available on WASI"
550 )
551 def test_process_time(self):
552 # process_time() should not include time spend during a sleep
553 start = time.process_time()
554 time.sleep(0.100)
555 stop = time.process_time()
556 # use 20 ms because process_time() has usually a resolution of 15 ms
557 # on Windows
558 self.assertLess(stop - start, 0.020)
559
560 info = time.get_clock_info('process_time')
561 self.assertTrue(info.monotonic)
562 self.assertFalse(info.adjustable)
563
564 def test_thread_time(self):
565 if not hasattr(time, 'thread_time'):
566 if sys.platform.startswith(('linux', 'android', 'win')):
567 self.fail("time.thread_time() should be available on %r"
568 % (sys.platform,))
569 else:
570 self.skipTest("need time.thread_time")
571
572 # thread_time() should not include time spend during a sleep
573 start = time.thread_time()
574 time.sleep(0.200)
575 stop = time.thread_time()
576 # gh-143528: use 100 ms to support slow CI
577 self.assertLess(stop - start, 0.100)
578
579 info = time.get_clock_info('thread_time')
580 self.assertTrue(info.monotonic)
581 self.assertFalse(info.adjustable)
582
583 @unittest.skipUnless(hasattr(time, 'clock_settime'),
584 'need time.clock_settime')
585 def test_monotonic_settime(self):
586 t1 = time.monotonic()
587 realtime = time.clock_gettime(time.CLOCK_REALTIME)
588 # jump backward with an offset of 1 hour
589 try:
590 time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
591 except PermissionError as err:
592 self.skipTest(err)
593 t2 = time.monotonic()
594 time.clock_settime(time.CLOCK_REALTIME, realtime)
595 # monotonic must not be affected by system clock updates
596 self.assertGreaterEqual(t2, t1)
597
598 def test_localtime_failure(self):
599 # Issue #13847: check for localtime() failure
600 invalid_time_t = None
601 for time_t in (-1, 2**30, 2**33, 2**60):
602 try:
603 time.localtime(time_t)
604 except OverflowError:
605 self.skipTest("need 64-bit time_t")
606 except OSError:
607 invalid_time_t = time_t
608 break
609 if invalid_time_t is None:
610 self.skipTest("unable to find an invalid time_t value")
611
612 self.assertRaises(OSError, time.localtime, invalid_time_t)
613 self.assertRaises(OSError, time.ctime, invalid_time_t)
614
615 # Issue #26669: check for localtime() failure
616 self.assertRaises(ValueError, time.localtime, float("nan"))
617 self.assertRaises(ValueError, time.ctime, float("nan"))
618
619 def test_get_clock_info(self):
620 clocks = [
621 'monotonic',
622 'perf_counter',
623 'process_time',
624 'time',
625 ]
626 if hasattr(time, 'thread_time'):
627 clocks.append('thread_time')
628
629 for name in clocks:
630 with self.subTest(name=name):
631 info = time.get_clock_info(name)
632
633 self.assertIsInstance(info.implementation, str)
634 self.assertNotEqual(info.implementation, '')
635 self.assertIsInstance(info.monotonic, bool)
636 self.assertIsInstance(info.resolution, float)
637 # 0.0 < resolution <= 1.0
638 self.assertGreater(info.resolution, 0.0)
639 self.assertLessEqual(info.resolution, 1.0)
640 self.assertIsInstance(info.adjustable, bool)
641
642 self.assertRaises(ValueError, time.get_clock_info, 'xxx')
643
644
645 class TestLocale(unittest.TestCase):
646 @support.run_with_locale('LC_ALL', 'fr_FR', '')
647 def test_bug_3061(self):
648 # This should not cause an exception
649 time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
650
651
652 class _TestAsctimeYear:
653 _format = '%d'
654
655 def yearstr(self, y):
656 return time.asctime((y,) + (0,) * 8).split()[-1]
657
658 def test_large_year(self):
659 # Check that it doesn't crash for year > 9999
660 self.assertEqual(self.yearstr(12345), '12345')
661 self.assertEqual(self.yearstr(123456789), '123456789')
662
663 class _TestStrftimeYear:
664
665 # Issue 13305: For years < 1000, the value is not always
666 # padded to 4 digits across platforms. The C standard
667 # assumes year >= 1900, so it does not specify the number
668 # of digits.
669
670 if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
671 _format = '%04d'
672 else:
673 _format = '%d'
674
675 def yearstr(self, y):
676 return time.strftime('%Y', (y,) + (0,) * 8)
677
678 @unittest.skipUnless(
679 support.has_strftime_extensions, "requires strftime extension"
680 )
681 def test_4dyear(self):
682 # Check that we can return the zero padded value.
683 if self._format == '%04d':
684 self.test_year('%04d')
685 else:
686 def year4d(y):
687 return time.strftime('%4Y', (y,) + (0,) * 8)
688 self.test_year('%04d', func=year4d)
689
690 def skip_if_not_supported(y):
691 msg = f"strftime() does not support year {y} on this platform"
692 try:
693 time.strftime('%Y', (y,) + (0,) * 8)
694 except ValueError:
695 cond = False
696 else:
697 cond = True
698 return unittest.skipUnless(cond, msg)
699
700 @skip_if_not_supported(10000)
701 def test_large_year(self):
702 return super().test_large_year()
703
704 @skip_if_not_supported(0)
705 def test_negative(self):
706 return super().test_negative()
707
708 del skip_if_not_supported
709
710
711 class _Test4dYear:
712 _format = '%d'
713
714 def test_year(self, fmt=None, func=None):
715 fmt = fmt or self._format
716 func = func or self.yearstr
717 self.assertEqual(func(1), fmt % 1)
718 self.assertEqual(func(68), fmt % 68)
719 self.assertEqual(func(69), fmt % 69)
720 self.assertEqual(func(99), fmt % 99)
721 self.assertEqual(func(999), fmt % 999)
722 self.assertEqual(func(9999), fmt % 9999)
723
724 def test_large_year(self):
725 self.assertEqual(self.yearstr(12345).lstrip('+'), '12345')
726 self.assertEqual(self.yearstr(123456789).lstrip('+'), '123456789')
727 self.assertEqual(self.yearstr(TIME_MAXYEAR).lstrip('+'), str(TIME_MAXYEAR))
728 self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
729
730 def test_negative(self):
731 self.assertEqual(self.yearstr(-1), self._format % -1)
732 self.assertEqual(self.yearstr(-1234), '-1234')
733 self.assertEqual(self.yearstr(-123456), '-123456')
734 self.assertEqual(self.yearstr(-123456789), str(-123456789))
735 self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
736 self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
737 # Modules/timemodule.c checks for underflow
738 self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
739 with self.assertRaises(OverflowError):
740 self.yearstr(-TIME_MAXYEAR - 1)
741
742
743 class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
744 pass
745
746 class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
747 pass
748
749
750 class TestPytime(unittest.TestCase):
751 @skip_if_buggy_ucrt_strfptime
752 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
753 @unittest.skipIf(
754 support.is_emscripten, "musl libc issue on Emscripten, bpo-46390"
755 )
756 def test_localtime_timezone(self):
757
758 # Get the localtime and examine it for the offset and zone.
759 lt = time.localtime()
760 self.assertTrue(hasattr(lt, "tm_gmtoff"))
761 self.assertTrue(hasattr(lt, "tm_zone"))
762
763 # See if the offset and zone are similar to the module
764 # attributes.
765 if lt.tm_gmtoff is None:
766 self.assertTrue(not hasattr(time, "timezone"))
767 else:
768 self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
769 if lt.tm_zone is None:
770 self.assertTrue(not hasattr(time, "tzname"))
771 else:
772 self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
773
774 # Try and make UNIX times from the localtime and a 9-tuple
775 # created from the localtime. Test to see that the times are
776 # the same.
777 t = time.mktime(lt); t9 = time.mktime(lt[:9])
778 self.assertEqual(t, t9)
779
780 # Make localtimes from the UNIX times and compare them to
781 # the original localtime, thus making a round trip.
782 new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
783 self.assertEqual(new_lt, lt)
784 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
785 self.assertEqual(new_lt.tm_zone, lt.tm_zone)
786 self.assertEqual(new_lt9, lt)
787 self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
788 self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
789
790 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
791 def test_strptime_timezone(self):
792 t = time.strptime("UTC", "%Z")
793 self.assertEqual(t.tm_zone, 'UTC')
794 t = time.strptime("+0500", "%z")
795 self.assertEqual(t.tm_gmtoff, 5 * 3600)
796
797 @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
798 def test_short_times(self):
799
800 import pickle
801
802 # Load a short time structure using pickle.
803 st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
804 lt = pickle.loads(st)
805 self.assertIs(lt.tm_gmtoff, None)
806 self.assertIs(lt.tm_zone, None)
807
808
809 @unittest.skipIf(_testcapi is None, 'need the _testinternalcapi module')
810 @unittest.skipIf(_testinternalcapi is None, 'need the _testinternalcapi module')
811 class CPyTimeTestCase:
812 """
813 Base class to test the C _PyTime_t API.
814 """
815 OVERFLOW_SECONDS = None
816
817 def setUp(self):
818 from _testinternalcapi import SIZEOF_TIME_T
819 bits = SIZEOF_TIME_T * 8 - 1
820 self.time_t_min = -2 ** bits
821 self.time_t_max = 2 ** bits - 1
822
823 def time_t_filter(self, seconds):
824 return (self.time_t_min <= seconds <= self.time_t_max)
825
826 def _rounding_values(self, use_float):
827 "Build timestamps used to test rounding."
828
829 units = [1, US_TO_NS, MS_TO_NS, SEC_TO_NS]
830 if use_float:
831 # picoseconds are only tested to pytime_converter accepting floats
832 units.append(1e-3)
833
834 values = (
835 # small values
836 1, 2, 5, 7, 123, 456, 1234,
837 # 10^k - 1
838 9,
839 99,
840 999,
841 9999,
842 99999,
843 999999,
844 # test half even rounding near 0.5, 1.5, 2.5, 3.5, 4.5
845 499, 500, 501,
846 1499, 1500, 1501,
847 2500,
848 3500,
849 4500,
850 )
851
852 ns_timestamps = [0]
853 for unit in units:
854 for value in values:
855 ns = value * unit
856 ns_timestamps.extend((-ns, ns))
857 for pow2 in (0, 5, 10, 15, 22, 23, 24, 30, 33):
858 ns = (2 ** pow2) * SEC_TO_NS
859 ns_timestamps.extend((
860 -ns-1, -ns, -ns+1,
861 ns-1, ns, ns+1
862 ))
863 for seconds in (_testcapi.INT_MIN, _testcapi.INT_MAX):
864 ns_timestamps.append(seconds * SEC_TO_NS)
865 if use_float:
866 # numbers with an exact representation in IEEE 754 (base 2)
867 for pow2 in (3, 7, 10, 15):
868 ns = 2.0 ** (-pow2)
869 ns_timestamps.extend((-ns, ns))
870
871 # seconds close to _PyTime_t type limit
872 ns = (2 ** 63 // SEC_TO_NS) * SEC_TO_NS
873 ns_timestamps.extend((-ns, ns))
874
875 return ns_timestamps
876
877 def _check_rounding(self, pytime_converter, expected_func,
878 use_float, unit_to_sec, value_filter=None):
879
880 def convert_values(ns_timestamps):
881 if use_float:
882 unit_to_ns = SEC_TO_NS / float(unit_to_sec)
883 values = [ns / unit_to_ns for ns in ns_timestamps]
884 else:
885 unit_to_ns = SEC_TO_NS // unit_to_sec
886 values = [ns // unit_to_ns for ns in ns_timestamps]
887
888 if value_filter:
889 values = filter(value_filter, values)
890
891 # remove duplicates and sort
892 return sorted(set(values))
893
894 # test rounding
895 ns_timestamps = self._rounding_values(use_float)
896 valid_values = convert_values(ns_timestamps)
897 for time_rnd, decimal_rnd in ROUNDING_MODES:
898 with decimal.localcontext() as context:
899 context.rounding = decimal_rnd
900
901 for value in valid_values:
902 debug_info = {'value': value, 'rounding': decimal_rnd}
903 try:
904 result = pytime_converter(value, time_rnd)
905 expected = expected_func(value)
906 except Exception:
907 self.fail("Error on timestamp conversion: %s" % debug_info)
908 self.assertEqual(result,
909 expected,
910 debug_info)
911
912 # test overflow
913 ns = self.OVERFLOW_SECONDS * SEC_TO_NS
914 ns_timestamps = (-ns, ns)
915 overflow_values = convert_values(ns_timestamps)
916 for time_rnd, _ in ROUNDING_MODES :
917 for value in overflow_values:
918 debug_info = {'value': value, 'rounding': time_rnd}
919 with self.assertRaises(OverflowError, msg=debug_info):
920 pytime_converter(value, time_rnd)
921
922 def check_int_rounding(self, pytime_converter, expected_func,
923 unit_to_sec=1, value_filter=None):
924 self._check_rounding(pytime_converter, expected_func,
925 False, unit_to_sec, value_filter)
926
927 def check_float_rounding(self, pytime_converter, expected_func,
928 unit_to_sec=1, value_filter=None):
929 self._check_rounding(pytime_converter, expected_func,
930 True, unit_to_sec, value_filter)
931
932 def decimal_round(self, x):
933 d = decimal.Decimal(x)
934 d = d.quantize(1)
935 return int(d)
936
937
938 class TestCPyTime(CPyTimeTestCase, unittest.TestCase):
939 """
940 Test the C _PyTime_t API.
941 """
942 # _PyTime_t is a 64-bit signed integer
943 OVERFLOW_SECONDS = math.ceil((2**63 + 1) / SEC_TO_NS)
944
945 def test_FromSeconds(self):
946 from _testinternalcapi import _PyTime_FromSeconds
947
948 # _PyTime_FromSeconds() expects a C int, reject values out of range
949 def c_int_filter(secs):
950 return (_testcapi.INT_MIN <= secs <= _testcapi.INT_MAX)
951
952 self.check_int_rounding(lambda secs, rnd: _PyTime_FromSeconds(secs),
953 lambda secs: secs * SEC_TO_NS,
954 value_filter=c_int_filter)
955
956 # test nan
957 for time_rnd, _ in ROUNDING_MODES:
958 with self.assertRaises(TypeError):
959 _PyTime_FromSeconds(float('nan'))
960
961 def test_FromSecondsObject(self):
962 from _testinternalcapi import _PyTime_FromSecondsObject
963
964 self.check_int_rounding(
965 _PyTime_FromSecondsObject,
966 lambda secs: secs * SEC_TO_NS)
967
968 self.check_float_rounding(
969 _PyTime_FromSecondsObject,
970 lambda ns: self.decimal_round(ns * SEC_TO_NS))
971
972 # test nan
973 for time_rnd, _ in ROUNDING_MODES:
974 with self.assertRaises(ValueError):
975 _PyTime_FromSecondsObject(float('nan'), time_rnd)
976
977 def test_AsSecondsDouble(self):
978 from _testcapi import PyTime_AsSecondsDouble
979
980 def float_converter(ns):
981 if abs(ns) % SEC_TO_NS == 0:
982 return float(ns // SEC_TO_NS)
983 else:
984 return float(ns) / SEC_TO_NS
985
986 self.check_int_rounding(lambda ns, rnd: PyTime_AsSecondsDouble(ns),
987 float_converter,
988 NS_TO_SEC)
989
990 def create_decimal_converter(self, denominator):
991 denom = decimal.Decimal(denominator)
992
993 def converter(value):
994 d = decimal.Decimal(value) / denom
995 return self.decimal_round(d)
996
997 return converter
998
999 def test_AsTimeval(self):
1000 from _testinternalcapi import _PyTime_AsTimeval
1001
1002 us_converter = self.create_decimal_converter(US_TO_NS)
1003
1004 def timeval_converter(ns):
1005 us = us_converter(ns)
1006 return divmod(us, SEC_TO_US)
1007
1008 if sys.platform == 'win32':
1009 from _testcapi import LONG_MIN, LONG_MAX
1010
1011 # On Windows, timeval.tv_sec type is a C long
1012 def seconds_filter(secs):
1013 return LONG_MIN <= secs <= LONG_MAX
1014 else:
1015 seconds_filter = self.time_t_filter
1016
1017 self.check_int_rounding(_PyTime_AsTimeval,
1018 timeval_converter,
1019 NS_TO_SEC,
1020 value_filter=seconds_filter)
1021
1022 @unittest.skipUnless(hasattr(_testinternalcapi, '_PyTime_AsTimespec'),
1023 'need _testinternalcapi._PyTime_AsTimespec')
1024 def test_AsTimespec(self):
1025 from _testinternalcapi import _PyTime_AsTimespec
1026
1027 def timespec_converter(ns):
1028 return divmod(ns, SEC_TO_NS)
1029
1030 self.check_int_rounding(lambda ns, rnd: _PyTime_AsTimespec(ns),
1031 timespec_converter,
1032 NS_TO_SEC,
1033 value_filter=self.time_t_filter)
1034
1035 @unittest.skipUnless(hasattr(_testinternalcapi, '_PyTime_AsTimeval_clamp'),
1036 'need _testinternalcapi._PyTime_AsTimeval_clamp')
1037 def test_AsTimeval_clamp(self):
1038 from _testinternalcapi import _PyTime_AsTimeval_clamp
1039
1040 if sys.platform == 'win32':
1041 from _testcapi import LONG_MIN, LONG_MAX
1042 tv_sec_max = LONG_MAX
1043 tv_sec_min = LONG_MIN
1044 else:
1045 tv_sec_max = self.time_t_max
1046 tv_sec_min = self.time_t_min
1047
1048 for t in (PyTime_MIN, PyTime_MAX):
1049 ts = _PyTime_AsTimeval_clamp(t, _PyTime.ROUND_CEILING)
1050 with decimal.localcontext() as context:
1051 context.rounding = decimal.ROUND_CEILING
1052 us = self.decimal_round(decimal.Decimal(t) / US_TO_NS)
1053 tv_sec, tv_usec = divmod(us, SEC_TO_US)
1054 if tv_sec_max < tv_sec:
1055 tv_sec = tv_sec_max
1056 tv_usec = 0
1057 elif tv_sec < tv_sec_min:
1058 tv_sec = tv_sec_min
1059 tv_usec = 0
1060 self.assertEqual(ts, (tv_sec, tv_usec))
1061
1062 @unittest.skipUnless(hasattr(_testinternalcapi, '_PyTime_AsTimespec_clamp'),
1063 'need _testinternalcapi._PyTime_AsTimespec_clamp')
1064 def test_AsTimespec_clamp(self):
1065 from _testinternalcapi import _PyTime_AsTimespec_clamp
1066
1067 for t in (PyTime_MIN, PyTime_MAX):
1068 ts = _PyTime_AsTimespec_clamp(t)
1069 tv_sec, tv_nsec = divmod(t, NS_TO_SEC)
1070 if self.time_t_max < tv_sec:
1071 tv_sec = self.time_t_max
1072 tv_nsec = 0
1073 elif tv_sec < self.time_t_min:
1074 tv_sec = self.time_t_min
1075 tv_nsec = 0
1076 self.assertEqual(ts, (tv_sec, tv_nsec))
1077
1078 def test_AsMilliseconds(self):
1079 from _testinternalcapi import _PyTime_AsMilliseconds
1080
1081 self.check_int_rounding(_PyTime_AsMilliseconds,
1082 self.create_decimal_converter(MS_TO_NS),
1083 NS_TO_SEC)
1084
1085 def test_AsMicroseconds(self):
1086 from _testinternalcapi import _PyTime_AsMicroseconds
1087
1088 self.check_int_rounding(_PyTime_AsMicroseconds,
1089 self.create_decimal_converter(US_TO_NS),
1090 NS_TO_SEC)
1091
1092
1093 class TestOldPyTime(CPyTimeTestCase, unittest.TestCase):
1094 """
1095 Test the old C _PyTime_t API: _PyTime_ObjectToXXX() functions.
1096 """
1097
1098 # time_t is a 32-bit or 64-bit signed integer
1099 OVERFLOW_SECONDS = 2 ** 64
1100
1101 def test_object_to_time_t(self):
1102 from _testinternalcapi import _PyTime_ObjectToTime_t
1103
1104 self.check_int_rounding(_PyTime_ObjectToTime_t,
1105 lambda secs: secs,
1106 value_filter=self.time_t_filter)
1107
1108 self.check_float_rounding(_PyTime_ObjectToTime_t,
1109 self.decimal_round,
1110 value_filter=self.time_t_filter)
1111
1112 def create_converter(self, sec_to_unit):
1113 def converter(secs):
1114 floatpart, intpart = math.modf(secs)
1115 intpart = int(intpart)
1116 floatpart *= sec_to_unit
1117 floatpart = self.decimal_round(floatpart)
1118 if floatpart < 0:
1119 floatpart += sec_to_unit
1120 intpart -= 1
1121 elif floatpart >= sec_to_unit:
1122 floatpart -= sec_to_unit
1123 intpart += 1
1124 return (intpart, floatpart)
1125 return converter
1126
1127 def test_object_to_timeval(self):
1128 from _testinternalcapi import _PyTime_ObjectToTimeval
1129
1130 self.check_int_rounding(_PyTime_ObjectToTimeval,
1131 lambda secs: (secs, 0),
1132 value_filter=self.time_t_filter)
1133
1134 self.check_float_rounding(_PyTime_ObjectToTimeval,
1135 self.create_converter(SEC_TO_US),
1136 value_filter=self.time_t_filter)
1137
1138 # test nan
1139 for time_rnd, _ in ROUNDING_MODES:
1140 with self.assertRaises(ValueError):
1141 _PyTime_ObjectToTimeval(float('nan'), time_rnd)
1142
1143 def test_object_to_timespec(self):
1144 from _testinternalcapi import _PyTime_ObjectToTimespec
1145
1146 self.check_int_rounding(_PyTime_ObjectToTimespec,
1147 lambda secs: (secs, 0),
1148 value_filter=self.time_t_filter)
1149
1150 self.check_float_rounding(_PyTime_ObjectToTimespec,
1151 self.create_converter(SEC_TO_NS),
1152 value_filter=self.time_t_filter)
1153
1154 # test nan
1155 for time_rnd, _ in ROUNDING_MODES:
1156 with self.assertRaises(ValueError):
1157 _PyTime_ObjectToTimespec(float('nan'), time_rnd)
1158
1159 @unittest.skipUnless(sys.platform == "darwin", "test weak linking on macOS")
1160 class TestTimeWeaklinking(unittest.TestCase):
1161 # These test cases verify that weak linking support on macOS works
1162 # as expected. These cases only test new behaviour introduced by weak linking,
1163 # regular behaviour is tested by the normal test cases.
1164 #
1165 # See the section on Weak Linking in Mac/README.txt for more information.
1166 def test_clock_functions(self):
1167 import sysconfig
1168 import platform
1169
1170 config_vars = sysconfig.get_config_vars()
1171 var_name = "HAVE_CLOCK_GETTIME"
1172 if var_name not in config_vars or not config_vars[var_name]:
1173 raise unittest.SkipTest(f"{var_name} is not available")
1174
1175 mac_ver = tuple(int(x) for x in platform.mac_ver()[0].split("."))
1176
1177 clock_names = [
1178 "CLOCK_MONOTONIC", "clock_gettime", "clock_gettime_ns", "clock_settime",
1179 "clock_settime_ns", "clock_getres"]
1180
1181 if mac_ver >= (10, 12):
1182 for name in clock_names:
1183 self.assertTrue(hasattr(time, name), f"time.{name} is not available")
1184
1185 else:
1186 for name in clock_names:
1187 self.assertFalse(hasattr(time, name), f"time.{name} is available")
1188
1189
1190 if __name__ == "__main__":
1191 unittest.main()