test_time.py 42 KB

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