"""Event identity: serial + key + timestamp, so a stale or foreign id fails loudly.""" from __future__ import annotations import datetime import os import sys import pytest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from sfm.device_access.errors import BadRequest, EventNotFound, StaleEvent # noqa: E402 from sfm.device_access.events import ( # noqa: E402 iso_of, make_event_id, parse_event_id, stamp_of, ) KEY = bytes.fromhex("055d4a81") WHEN = datetime.datetime(2025, 5, 31, 13, 59, 1) def test_an_event_id_round_trips(): eid = make_event_id("um20147", KEY, stamp_of(WHEN)) assert eid == "UM20147:055d4a81:20250531135901" assert parse_event_id(eid, "UM20147") == (KEY, "20250531135901") def test_an_unknown_timestamp_round_trips_as_none(): eid = make_event_id("BE18193", bytes.fromhex("01110000"), None) assert eid == "BE18193:01110000:-" assert parse_event_id(eid, "be18193") == (bytes.fromhex("01110000"), None) def test_an_id_from_another_unit_is_refused(): # UM12947 and UM20147 both have an event 055d4a81 with pytest.raises(BadRequest, match="UM12947"): parse_event_id("UM12947:055d4a81:20250531135901", "UM20147") @pytest.mark.parametrize("bad", ["", "UM20147", "UM20147:055d4a81", "UM20147:zz:20250531135901", "UM20147:055d4a:20250531135901", "UM20147:055d4a81:2025"]) def test_a_malformed_id_is_refused(bad): with pytest.raises(BadRequest): parse_event_id(bad, "UM20147") def test_iso_and_stamp_of_none_are_none(): assert iso_of(None) is None and stamp_of(None) is None assert iso_of(WHEN) == "2025-05-31T13:59:01" def test_the_new_errors_have_their_statuses(): assert (EventNotFound.http_status, StaleEvent.http_status) == (404, 409)