diff --git a/src/akkudoktoreos/core/databaseabc.py b/src/akkudoktoreos/core/databaseabc.py index ea5e95b3..a71a4ce3 100644 --- a/src/akkudoktoreos/core/databaseabc.py +++ b/src/akkudoktoreos/core/databaseabc.py @@ -299,7 +299,7 @@ class DatabaseTimestamp(str): Must always be in UTC and lexicographically sortable. Example: - "20241027T123456[Z]" # 2024-10-27 12:34:56 + "20241027T123456Z" # 2024-10-27 12:34:56 UTC """ __slots__ = () @@ -309,9 +309,16 @@ class DatabaseTimestamp(str): if dt is None or dt.tz is None: raise ValueError("Timezone-aware datetime required") - return cls(dt.in_timezone("UTC").format("YYYYMMDDTHHmmss[Z]")) + # Same result as format("YYYYMMDDTHHmmss[Z]") for 4-digit years, without + # pendulum's format-token parser (called for every record access). + utc = dt.in_timezone("UTC") + return cls( + f"{utc.year:04d}{utc.month:02d}{utc.day:02d}" + f"T{utc.hour:02d}{utc.minute:02d}{utc.second:02d}Z" + ) def to_datetime(self) -> DateTime: + # to_datetime() parses the canonical form directly (ISO 8601 instant fast path). return to_datetime(self, in_timezone="UTC") diff --git a/src/akkudoktoreos/utils/datetimeutil.py b/src/akkudoktoreos/utils/datetimeutil.py index 2e93956a..22ff814a 100644 --- a/src/akkudoktoreos/utils/datetimeutil.py +++ b/src/akkudoktoreos/utils/datetimeutil.py @@ -851,6 +851,63 @@ def to_time( raise ValueError(f"Invalid time value: {value!r} of type: {type(value)}") from e +# ISO 8601 date-times that name one instant: an explicit "Z" or UTC offset, e.g. +# "2024-10-13T15:30:00Z", "2024-10-13T15:30:00.250+02:00", or the basic form +# "20241013T153000Z" of database timestamps. +_ISO_INSTANT_EXTENDED = re.compile( + r"(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(Z|[+-]\d{2}:\d{2})", + re.ASCII, +) +_ISO_INSTANT_BASIC = re.compile(r"(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(Z)", re.ASCII) + + +def _parse_iso_instant(value: str) -> Optional[pendulum.DateTime]: + """Parse an ISO 8601 date-time with an explicit UTC designator or offset. + + These strings match none of the formats that `to_datetime` tries first (each is + combined with a timezone name), so they used to reach `pendulum.parse` only after + every format had failed. Parsing them directly gives the same instant at a + fraction of the cost; this path carries most string conversions in EOS, such as + database timestamps and API date-times. + + Args: + value: The date-time string. + + Returns: + The parsed date-time in the given offset, or None if `value` has another form + or an out-of-range field, so the caller can fall back to the generic parser. + """ + match = _ISO_INSTANT_EXTENDED.fullmatch(value) or _ISO_INSTANT_BASIC.fullmatch(value) + if match is None: + return None + year, month, day, hour, minute, second = (int(match.group(i)) for i in range(1, 7)) + fraction = match.group(7) if match.re is _ISO_INSTANT_EXTENDED else None + offset = match.group(match.re.groups) + tzinfo: Timezone | pendulum.FixedTimezone + if offset == "Z": + tzinfo = UTC + else: + offset_minutes = int(offset[1:3]) * 60 + int(offset[4:6]) + if offset_minutes >= 24 * 60: + return None + tzinfo = pendulum.FixedTimezone((-1 if offset[0] == "-" else 1) * offset_minutes * 60) + try: + # pendulum.datetime() is the factory pendulum.parse() uses, so the result also + # keeps the fold attribute that the generic path returns. + return pendulum.datetime( + year, + month, + day, + hour, + minute, + second, + int(fraction.ljust(6, "0")) if fraction else 0, + tz=tzinfo, + ) + except ValueError: + return None + + @overload def to_datetime( date_input: Optional[Any] = None, @@ -963,6 +1020,10 @@ def to_datetime( dt = dt.end_of("day") else: dt = dt.start_of("day") + elif ( + isinstance(date_input, str) and (iso_instant := _parse_iso_instant(date_input)) is not None + ): + dt = iso_instant elif isinstance(date_input, str): # Convert to timezone aware datetime dt = None diff --git a/tests/test_config.py b/tests/test_config.py index c345b5ca..8e38bb4b 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,6 +1,7 @@ import json import tempfile from pathlib import Path +from types import SimpleNamespace from typing import Any from unittest.mock import Mock, patch @@ -1042,3 +1043,15 @@ class TestConfigSetup: with pytest.raises(RuntimeError, match="before its settings are loaded"): coreabc.get_config(init=True) + + def test_access_after_settings_are_loaded_returns_config_in_setup( + self, uncreated_config, monkeypatch + ): + """During creation the configuration is returned once its settings are loaded.""" + from akkudoktoreos.core import coreabc + + config_in_setup = SimpleNamespace(_initialized=True) + monkeypatch.setattr(coreabc, "_config_eos_setup_running", True) + monkeypatch.setitem(ConfigEOS._instances, ConfigEOS, config_in_setup) + + assert coreabc.get_config(init=True) is config_in_setup diff --git a/tests/test_databaseabc.py b/tests/test_databaseabc.py index 4e32dfdc..a9b3febf 100644 --- a/tests/test_databaseabc.py +++ b/tests/test_databaseabc.py @@ -361,6 +361,39 @@ async def seq_sparse(): return s, now +# --------------------------------------------------------------------------- +# DatabaseTimestamp +# --------------------------------------------------------------------------- + + +class TestDatabaseTimestamp: + @pytest.mark.parametrize( + ("local", "timezone", "expected"), + [ + # 02:30:59 occurs twice on the day DST ends. + ("2024-10-27T02:30:59+02:00", "Europe/Berlin", "20241027T003059Z"), + ("2024-10-27T02:30:59+01:00", "Europe/Berlin", "20241027T013059Z"), + ("2026-01-01T00:00:00+14:00", "Pacific/Kiritimati", "20251231T100000Z"), + ("2026-01-01T23:59:59-12:00", "Etc/GMT+12", "20260102T115959Z"), + ], + ) + def test_round_trip(self, local: str, timezone: str, expected: str) -> None: + dt = to_datetime(local, in_timezone=timezone) + db_ts = DatabaseTimestamp.from_datetime(dt.add(microseconds=999)) + + assert db_ts == expected + assert db_ts == dt.in_timezone("UTC").format("YYYYMMDDTHHmmss[Z]") + parsed = db_ts.to_datetime() + # Compare in UTC: an inter-zone comparison is never equal for the + # second (fold=1) occurrence of an ambiguous local time. + assert parsed == dt.in_timezone("UTC") + assert parsed.timezone_name == "UTC" + + def test_naive_datetime_rejected(self) -> None: + with pytest.raises(ValueError): + DatabaseTimestamp.from_datetime(DateTime(2024, 1, 1)) + + # --------------------------------------------------------------------------- # Core mixin tests # --------------------------------------------------------------------------- diff --git a/tests/test_datetimeutil.py b/tests/test_datetimeutil.py index bacb351b..06a06a7d 100644 --- a/tests/test_datetimeutil.py +++ b/tests/test_datetimeutil.py @@ -963,6 +963,49 @@ def test_to_datetime_explicit_offset_preserves_instant( assert actual.timezone_name == "Europe/Berlin" +@pytest.mark.parametrize("in_timezone", ["UTC", "Europe/Berlin", "Pacific/Kiritimati", "Etc/GMT+12"]) +@pytest.mark.parametrize( + "value", + [ + "2024-10-27T00:30:00Z", # 02:30 CEST in Berlin, first occurrence + "2024-10-27T01:30:00Z", # 02:30 CET in Berlin, second occurrence + "2024-10-27T02:30:00.25+01:00", + "2025-12-31T23:59:59.999999-12:00", + "2026-01-01T00:00:00+14:00", + "2024-06-15T12:00:00+05:45", + "20241027T013000Z", # basic form of database timestamps + ], +) +def test_to_datetime_iso_instant_matches_generic_parser(value: str, in_timezone: str) -> None: + """ISO 8601 instants skip the format search and still match pendulum.parse, fold included.""" + expected = cast(pendulum.DateTime, pendulum.parse(value)).in_timezone(in_timezone) + + actual = to_datetime(value, in_timezone=in_timezone) + naive = to_datetime(value, in_timezone=in_timezone, to_naiv=True) + + assert actual.isoformat() == expected.isoformat() + assert actual.fold == expected.fold + assert actual.timezone_name == in_timezone + assert naive.isoformat() == expected.naive().isoformat() + assert naive.fold == expected.naive().fold + + +@pytest.mark.parametrize( + "value", + [ + "2024-13-01T00:00:00Z", + "2024-02-30T12:00:00+01:00", + "20241327T000000Z", + "2024-01-01T00:00:00+24:00", + ], + ids=["month-13", "february-30", "basic-month-13", "offset-24h"], +) +def test_to_datetime_iso_instant_out_of_range_raises(value: str) -> None: + """An ISO 8601 instant with an out-of-range field is still rejected.""" + with pytest.raises(ValueError): + to_datetime(value, in_timezone="UTC") + + @pytest.mark.parametrize( "value", [1768517100, 1768517100.123456, "1768517100.123456"],