Files
RustPython/extra_tests/snippets/stdlib_time.py
T
youknowdot 87aedfb7c5 Preserve Windows time conversion error classes (#9022)
* Cover Windows time conversion error classes

Require OSError with EINVAL for representable timestamps rejected by the Windows C runtime, while preserving OverflowError for float(2**63). This initial regression-only commit intentionally exposes the current Windows error mapping before the implementation follows.

AI assistance covered source comparison, regression design, and automated Linux baseline/reference controls. Native Windows results are pending. No human validation is claimed.

Assisted-by: Codex:model-version-unavailable

* Record native Windows time conversion outcomes

The first hosted regression run failed on CPython 3.14.7 as well as RustPython because a presumed-invalid CRT timestamp succeeded. Add bounded diagnostics before the unchanged assertions to capture full version/build metadata and every conversion result, including negative half-day controls. No implementation or canonical test changes are included.

The existing time snippet still passes the repository pytest runner on Linux CPython 3.14.7 and the current RustPython baseline. Native diagnostic results remain pending.

Assisted-by: Codex:model-version-unavailable

* Use the observed UCRT rejection boundary in time regression

Hosted Windows diagnostics show that CPython 3.14.7 and RustPython both accept gmtime(-1) and gmtime(-43200), while -86400 is rejected by all three converters. Correct only the newly added shared negative test value. CPython raises OSError(errno 22) for every selected rejected value, while the RustPython baseline raises OverflowError. Canonical tests and the recorded diagnostics remain unchanged.

The existing snippet passes both Linux reference and baseline controls. Assisted source investigation and automated verification used no manual validation.

Assisted-by: Codex:model-version-unavailable

* Preserve Windows CRT time conversion errors

Return CRT errno failures from the Windows calendar helpers and translate them to Python OSError. Adapt the datetime caller while retaining its Unix behavior. Use an exclusive signed float upper bound so float(2**63) still raises OverflowError before reaching the CRT.

Keep Windows negative-time FILETIME fallback and time64 ABI changes outside this Python 3.14 extraction. Existing datetime local-error coverage is retained and a UTC error control is added for the observed rejected timestamp -86400.

Hosted native diagnostics prove CPython 3.14.7 raises OSError(errno 22) where the baseline raises OverflowError. Windows-GNU host_env check and warnings-denied Clippy pass. Selected canonical datetime and complete time/datetime snippet Linux controls pass, with six existing baseline canonical skips. Fixed native Windows verification remains pending CI.

AI assistance covered source comparison, implementation, regression design, and automated verification. No manual validation is claimed.

Assisted-by: Codex:model-version-unavailable
2026-10-10 00:41:40 +09:00

180 lines
6.0 KiB
Python

import sys
import time
if sys.platform == "win32":
# Record the native runtime before evaluating the range regression below.
print("Windows time runtime:", sys.version, sys.implementation, sys.flags)
print("Windows time word size:", sys.maxsize)
if hasattr(sys, "getwindowsversion"):
print("Windows version:", sys.getwindowsversion())
try:
import sysconfig
build_keys = (
"Py_DEBUG",
"Py_GIL_DISABLED",
"Py_ENABLE_SHARED",
"SIZEOF_TIME_T",
"CC",
"CFLAGS",
)
print(
"Windows time build:",
dict(zip(build_keys, sysconfig.get_config_vars(*build_keys))),
)
except Exception as error:
print("Windows time build unavailable:", type(error).__name__, str(error))
for converter in (time.gmtime, time.localtime, time.ctime):
for timestamp in (
0,
-1,
-43200,
-43201,
-86400,
2**40,
2**63 - 1,
-(2**63),
-float(2**63),
float(2**63),
):
try:
result = converter(timestamp)
except Exception as error:
print(
"Windows time result:",
converter.__name__,
repr(timestamp),
type(error).__name__,
str(error),
getattr(error, "errno", None),
getattr(error, "winerror", None),
)
else:
print(
"Windows time result:",
converter.__name__,
repr(timestamp),
"success",
repr(result),
)
if sys.platform != "wasi":
for converter in (time.gmtime, time.localtime, time.ctime):
# 2**63 is outside signed time_t even though its maximum rounds up to
# that value when represented as a float.
try:
converter(float(2**63))
except OverflowError:
pass
else:
raise AssertionError("out-of-range timestamp did not raise OverflowError")
if sys.platform == "win32":
import errno
for converter in (time.gmtime, time.localtime, time.ctime):
# Python 3.14 preserves UCRT conversion failures as OSError. Use a
# negative timestamp below gmtime's near-epoch allowance in UCRT.
for timestamp in (-86400, 2**40, 2**63 - 1, -(2**63), -float(2**63)):
try:
converter(timestamp)
except OSError as error:
assert error.errno == errno.EINVAL, (converter, timestamp, error)
else:
raise AssertionError("UCRT timestamp failure did not raise OSError")
x = time.gmtime(1000)
assert x.tm_year == 1970
assert x.tm_min == 16
assert x.tm_sec == 40
assert x.tm_isdst == 0
s = time.strftime("%Y-%m-%d-%H-%M-%S", x)
# print(s)
assert s == "1970-01-01-00-16-40"
if sys.platform != "wasi":
# _strptime depends on time.tzname, which is not available on WASI yet.
x2 = time.strptime(s, "%Y-%m-%d-%H-%M-%S")
assert x2.tm_min == 16
# TODO: WASI currently does not raise OverflowError for some out-of-range
# struct_time values in asctime() and strftime().
# Re-enable this regression on WASI once the non-Unix time conversion path is fixed.
# Regression test for RustPython issue #4938:
# struct_time field overflow should raise OverflowError (matching CPython),
# not TypeError. Covers mktime, asctime, and strftime.
I32_MAX_PLUS_1 = 2147483648
overflow_cases = [
(I32_MAX_PLUS_1, 1, 1, 0, 0, 0, 0, 0, 0), # i32 overflow in year
(2024, I32_MAX_PLUS_1, 1, 0, 0, 0, 0, 0, 0), # i32 overflow in month
(2024, 1, I32_MAX_PLUS_1, 0, 0, 0, 0, 0, 0), # i32 overflow in mday
(2024, 1, 1, 0, 0, I32_MAX_PLUS_1, 0, 0, 0), # i32 overflow in sec
(88888888888,) * 9, # multi-field i32 overflow
]
for case in overflow_cases:
for func_name, call in [
("mktime", lambda c=case: time.mktime(c)),
("asctime", lambda c=case: time.asctime(c)),
("strftime", lambda c=case: time.strftime("%Y", c)),
]:
try:
call()
except OverflowError:
pass # expected, matches CPython
except TypeError as e:
raise AssertionError(
f"{func_name}({case}) raised TypeError (should be OverflowError): {e}"
) from e
else:
raise AssertionError(
f"{func_name}({case}) did not raise — expected OverflowError"
)
s = time.asctime(x)
assert s == "Thu Jan 1 00:16:40 1970"
# Monotonic and performance clocks should advance with elapsed time.
monotonic_before = time.monotonic()
monotonic_ns = time.monotonic_ns()
monotonic_after = time.monotonic()
assert isinstance(monotonic_before, float)
assert isinstance(monotonic_ns, int)
assert monotonic_before <= monotonic_ns / 1_000_000_000 <= monotonic_after
perf_before = time.perf_counter()
perf_ns = time.perf_counter_ns()
perf_after = time.perf_counter()
assert isinstance(perf_before, float)
assert isinstance(perf_ns, int)
assert perf_before <= perf_ns / 1_000_000_000 <= perf_after
monotonic_start = time.monotonic()
perf_start = time.perf_counter()
time.sleep(0.02)
monotonic_elapsed = time.monotonic() - monotonic_start
perf_elapsed = time.perf_counter() - perf_start
assert monotonic_elapsed >= 0.01
assert perf_elapsed >= 0.01
# The optional second argument fills the fields that are not part of the
# sequence.
fields = (2024, 1, 2, 3, 4, 5, 6, 7, 0)
assert time.struct_time(fields).tm_zone is None
assert time.struct_time(fields, {"tm_zone": "UTC"}).tm_zone == "UTC"
assert time.struct_time(fields, {"tm_gmtoff": 60}).tm_gmtoff == 60
try:
time.struct_time(fields, ["tm_zone", "UTC"])
except TypeError:
pass
else:
assert False, "struct_time accepted a non-dict second argument"