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