From f5fe9af07a5507b6266a25e497c88e54854e8783 Mon Sep 17 00:00:00 2001 From: Torben Nehmer Date: Fri, 4 Dec 2026 03:39:36 +0100 Subject: [PATCH] Add fact time intervals with strict point parsing FactTime validates and compares intervals in UTC; dates cover the whole UTC day. parse_point/format_point accept only strict forms. Co-Authored-By: Claude Sonnet 5.5 --- src/chemenu/domain/source.py | 106 ++++++++++++++++++++ tests/domain/test_fact_time.py | 174 +++++++++++++++++++++++++++++++++ 2 files changed, 280 insertions(+) create mode 100644 src/chemenu/domain/source.py create mode 100644 tests/domain/test_fact_time.py diff --git a/src/chemenu/domain/source.py b/src/chemenu/domain/source.py new file mode 100644 index 0000000..ce3fcd2 --- /dev/null +++ b/src/chemenu/domain/source.py @@ -0,0 +1,106 @@ +"""Sources: dating basis, authority and fact time.""" + +import re +from dataclasses import dataclass +from datetime import UTC, date, datetime, time, timedelta +from enum import StrEnum + +from chemenu.domain.errors import FactTimeError + + +class DatingBasis(StrEnum): + """Where the fact time of a source comes from.""" + + CAPTURED = "captured" + RECEIVED = "received" + EMAIL_HEADER = "email_header" + GIT_COMMIT = "git_commit" + HTML_METADATA = "html_metadata" + EXIF = "exif" + FILENAME = "filename" + CONTENT = "content" + DOCUMENT_METADATA = "document_metadata" + OPERATOR = "operator" + + +class Authority(StrEnum): + """How authoritative a source is. Enum order is the scale; no comparisons.""" + + OFFICIAL = "official" + ORGANIZATION = "organization" + THIRD_PARTY = "third_party" + HEARSAY = "hearsay" + + +class AuthorityForm(StrEnum): + """Whether the source was written or spoken.""" + + WRITTEN = "written" + ORAL = "oral" + + +_DATE = r"[0-9]{4}-[0-9]{2}-[0-9]{2}" +_POINT_RE = re.compile( + rf"{_DATE}(?:T(?:[01][0-9]|2[0-3]):[0-9]{{2}}(?::[0-9]{{2}}(?:\.[0-9]{{1,6}})?)?" + r"(?:Z|[+-](?:[01][0-9]|2[0-3]):[0-5][0-9]))?" +) + + +def parse_point(text: str) -> date | datetime: + """Parse a date (`YYYY-MM-DD`) or an ISO datetime with `T` and time zone.""" + if _POINT_RE.fullmatch(text) is None: + raise FactTimeError(f"invalid point in time: {text!r}") + try: + if "T" not in text: + return date.fromisoformat(text) + return datetime.fromisoformat(text) + except (ValueError, OverflowError) as exc: + raise FactTimeError(f"invalid point in time: {text!r}") from exc + + +def format_point(point: date | datetime) -> str: + """Inverse of `parse_point`.""" + if not isinstance(point, datetime): + return point.isoformat() + offset = _offset(point) + if offset.total_seconds() % 60 != 0: + raise FactTimeError(f"unsupported UTC offset: {offset}") + return point.isoformat() + + +def _offset(point: datetime) -> timedelta: + offset = point.utcoffset() + if offset is None: + raise FactTimeError("naive datetime is not allowed") + return offset + + +def _to_utc(point: date | datetime, *, end: bool) -> datetime: + """Bound of a point in UTC; a date covers the whole UTC day.""" + if isinstance(point, datetime): + _offset(point) + try: + return point.astimezone(UTC) + except OverflowError as exc: + raise FactTimeError("point in time not representable in UTC") from exc + return datetime.combine(point, time.max if end else time.min, tzinfo=UTC) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class FactTime: + """Interval in which a source's facts hold; `earliest` may be unknown.""" + + earliest: date | datetime | None + latest: date | datetime + basis: DatingBasis + + def __post_init__(self) -> None: + end = _to_utc(self.latest, end=True) + if self.earliest is not None and _to_utc(self.earliest, end=False) > end: + raise FactTimeError("fact time starts after it ends") + + def precedes(self, other: FactTime) -> bool: + """True if this ends strictly before `other` starts.""" + if other.earliest is None: + return False + return _to_utc(self.latest, end=True) < _to_utc(other.earliest, end=False) diff --git a/tests/domain/test_fact_time.py b/tests/domain/test_fact_time.py new file mode 100644 index 0000000..7e941c4 --- /dev/null +++ b/tests/domain/test_fact_time.py @@ -0,0 +1,174 @@ +from datetime import UTC, date, datetime, timedelta, timezone + +import pytest + +from chemenu.domain.errors import FactTimeError +from chemenu.domain.source import ( + Authority, + AuthorityForm, + DatingBasis, + FactTime, + format_point, + parse_point, +) + + +def _ft(earliest: date | datetime | None, latest: date | datetime) -> FactTime: + return FactTime(earliest=earliest, latest=latest, basis=DatingBasis.CAPTURED) + + +def test_enum_values() -> None: + assert DatingBasis.EMAIL_HEADER == "email_header" + assert Authority.THIRD_PARTY == "third_party" + assert AuthorityForm.ORAL == "oral" + + +@pytest.mark.parametrize( + "text", + [ + "2026-11-28", + "2026-11-28T14:32:00+01:00", + "2026-11-28T14:32:00+00:00", + "2026-11-28T14:32:00.123456-05:30", + "2026-11-28T14:32:00.5+01:00", + ], +) +def test_points_round_trip(text: str) -> None: + point = parse_point(text) + again = parse_point(format_point(point)) + assert again == point + assert type(again) is type(point) + if isinstance(point, datetime): + assert isinstance(again, datetime) + assert again.utcoffset() == point.utcoffset() + + +def test_points_z_and_missing_seconds() -> None: + z = parse_point("2026-11-28T14:32:00Z") + assert isinstance(z, datetime) + assert z.utcoffset() == timedelta(0) + short = parse_point("2026-11-28T14:32+01:00") + assert isinstance(short, datetime) + assert short.second == 0 + assert parse_point("2026-11-28") == date(2026, 11, 28) + assert not isinstance(parse_point("2026-11-28"), datetime) + + +@pytest.mark.parametrize( + "text", + [ + "", + "20261128", + "2026-W48-6", + "2026-11-28 14:32:00+01:00", + " 2026-11-28", + "2026-11-28 ", + "2026-11-28T14:32:00+01:00\n", + "2026-11-28t14:32:00+01:00", + "2026-11-28T14:32:00z", + chr(0xFF12) + "026-11-28", + "2026-02-30", + "2026-13-01", + "2026-11-28T24:00:00+01:00", + "2026-11-28T14:32:00", + "2026-11-28T14:32:00.1234567+01:00", + "2026-11-28T14:32:00+01:00:30", + "2026-11-28T14:32:00+0100", + "2026-11-28T14:32:00+01:99", + "2026-11-28T14:32:00+24:00", + ], +) +def test_invalid_point_raises(text: str) -> None: + with pytest.raises(FactTimeError): + parse_point(text) + + +def test_naive_datetime_raises() -> None: + naive = datetime(2026, 11, 28, 14, 32) + with pytest.raises(FactTimeError): + format_point(naive) + with pytest.raises(FactTimeError): + _ft(naive, date(2026, 12, 1)) + with pytest.raises(FactTimeError): + _ft(None, naive) + + +def test_exotic_offset_raises() -> None: + tz = timezone(timedelta(hours=1, seconds=30)) + with pytest.raises(FactTimeError): + format_point(datetime(2026, 1, 1, tzinfo=tz)) + + +def test_utc_overflow_raises() -> None: + tz = timezone(timedelta(hours=1)) + with pytest.raises(FactTimeError): + _ft(None, datetime.min.replace(tzinfo=tz)) + with pytest.raises(FactTimeError): + _ft(None, datetime.max.replace(tzinfo=timezone(-timedelta(hours=1)))) + + +def test_reversed_interval_raises() -> None: + with pytest.raises(FactTimeError): + _ft(date(2026, 12, 2), date(2026, 12, 1)) + a = datetime(2026, 11, 28, 14, 0, tzinfo=UTC) + with pytest.raises(FactTimeError): + _ft(a, a - timedelta(microseconds=1)) + # same instant in different zones is valid + _ft(a, a.astimezone(timezone(timedelta(hours=2)))) + # equal dates, and date start with datetime end on same UTC day + _ft(date(2026, 12, 1), date(2026, 12, 1)) + _ft(date(2026, 12, 1), datetime(2026, 12, 1, 0, 0, tzinfo=UTC)) + # a date means its UTC day: 00:30 in Berlin still belongs to the day before + with pytest.raises(FactTimeError): + _ft(date(2026, 11, 28), datetime(2026, 11, 28, 0, 30, tzinfo=timezone(timedelta(hours=1)))) + # stored as given + tz = timezone(timedelta(hours=1)) + end = datetime(2026, 12, 1, 10, tzinfo=tz) + kept = _ft(None, end).latest + assert isinstance(kept, datetime) + assert kept.utcoffset() == timedelta(hours=1) + + +def test_precedes() -> None: + a = _ft(None, date(2026, 11, 28)) + b = _ft(date(2026, 11, 29), date(2026, 12, 1)) + assert a.precedes(b) + assert not b.precedes(a) + # touching: end 23:59:59.999999 vs start next day 00:00 is strictly before + assert a.precedes(_ft(date(2026, 11, 29), date(2026, 11, 29))) + # same day: not strictly before + assert not a.precedes(_ft(date(2026, 11, 28), date(2026, 11, 28))) + t = datetime(2026, 11, 28, 12, tzinfo=UTC) + assert _ft(None, t).precedes(_ft(t + timedelta(seconds=1), t + timedelta(days=1))) + assert not _ft(None, t).precedes(_ft(t, t)) + # date.max / date.min do not overflow + assert not _ft(None, date.max).precedes(_ft(date.max, date.max)) + assert _ft(date.min, date.min).precedes(_ft(date.max, date.max)) + + +def test_overlap_is_unordered() -> None: + a = _ft(date(2026, 11, 1), date(2026, 11, 20)) + b = _ft(date(2026, 11, 10), date(2026, 11, 30)) + assert not a.precedes(b) + assert not b.precedes(a) + + +def test_unknown_start_never_follows() -> None: + a = _ft(date(2020, 1, 1), date(2020, 1, 2)) + b = _ft(None, date(2030, 1, 1)) + assert not a.precedes(b) + assert not b.precedes(b) + + +def test_date_covers_utc_day() -> None: + day = date(2026, 11, 28) + first = datetime(2026, 11, 28, 0, 0, tzinfo=UTC) + last = datetime(2026, 11, 28, 23, 59, 59, 999999, tzinfo=UTC) + before = _ft(None, first - timedelta(microseconds=1)) + after = _ft(last + timedelta(microseconds=1), last + timedelta(days=1)) + # as start: 00:00 UTC + assert before.precedes(_ft(day, day)) + assert not _ft(None, first).precedes(_ft(day, day)) + # as end: 23:59:59.999999 UTC + assert _ft(day, day).precedes(after) + assert not _ft(day, day).precedes(_ft(last, last + timedelta(days=1)))