from copy import deepcopy from dataclasses import FrozenInstanceError import json from pathlib import Path import pytest from labstand_contracts import ( ContractError, DetectionResult, ErrorMessage, Event, IPCRequest, IPCResponse, MAX_EVENT_BYTES, MAX_MESSAGE_BYTES, ) from labstand_contracts.validation import MAX_DEPTH EXAMPLES = Path(__file__).resolve().parents[1] / "examples" def example(name): return json.loads((EXAMPLES / name).read_text(encoding="utf-8")) @pytest.fixture def event(): return example("events.json")[0] @pytest.mark.parametrize("payload", example("events.json")) def test_shared_events_round_trip(payload): model = Event(payload) assert Event.from_json(model.to_json()).to_dict() == payload assert Event.from_json(json.dumps(payload)).identity == model.identity @pytest.mark.parametrize( ("model", "filename"), [(DetectionResult, "result.json"), (ErrorMessage, "error.json"), (IPCRequest, "request.json"), (IPCResponse, "response.json")], ) def test_shared_messages_round_trip(model, filename): payload = example(filename) assert model.from_json(model(payload).to_json()).to_dict() == payload @pytest.mark.parametrize( ("field", "value"), [ ("schema_version", 2), ("schema_version", True), ("sequence", True), ("sequence", 0), ("sequence", 1.0), ("monotonic_ms", -1), ("sim_epoch", -1), ("event_id", "not-a-uuid"), ("journal_generation", None), ("timestamp_sys", "2026-12-03T12:00:00+03:00"), ("timestamp_sys", "2026-12-03T12:00:00"), ("timestamp_sys", "2026-02-30T12:00:00Z"), ("timestamp_sys", "2026-12-03T12:00:00-00:00"), ("timestamp_sim", "2026-12-03T12:00:00+02:60"), ("timestamp_sim", "2026-12-03T12:00:00Z"), ("timestamp_sim", None), ("source", "radio"), ("event_type", "INVENTED"), ("origin", "windows"), ("stand_mode", "executing"), ("sim_epoch", None), ], ) def test_invalid_event_fields(event, field, value): event[field] = value with pytest.raises(ContractError): Event(event) @pytest.mark.parametrize("field", list(example("events.json")[0])) def test_every_envelope_field_is_required(event, field): del event[field] with pytest.raises(ContractError) as error: Event(event) assert error.value.code == "missing_field" @pytest.mark.parametrize( ("field", "value"), [("channel", True), ("channel", 3), ("uid", "2ef588f2"), ("uid", "A1CE8B0D"), ("role", "admin"), ("device", "turnstile"), ("result", "success"), ("attack_detected", True)], ) def test_invalid_rfid_details(event, field, value): event["details"][field] = value with pytest.raises(ContractError): Event(event) def test_unexpected_envelope_and_missing_details(event): event["classification"] = "normal" with pytest.raises(ContractError, match="unknown_field"): Event(event) del event["classification"] del event["details"]["uid"] with pytest.raises(ContractError, match="missing_field"): Event(event) def test_event_snapshot_is_immutable(event): model = Event(event) event["details"]["uid"] = "CE0385F2" exported = model.to_dict() exported["details"]["uid"] = "CE0385F2" assert model.to_dict()["details"]["uid"] == "2EF588F2" with pytest.raises(FrozenInstanceError): model._encoded = b"{}" def test_identity_does_not_depend_on_time_or_sequence(event): first = Event(event) event["sequence"] += 1 event["timestamp_sim"] = "2026-12-02T01:00:00+03:00" second = Event(event) assert first.identity == second.identity assert first.position != second.position event["journal_generation"] = "20000000-0000-4000-8000-000000000002" assert Event(event).position != second.position @pytest.mark.parametrize("raw", [ b"\xff", '{"schema_version":1,"schema_version":1}', '{"details":{"uid":"one","uid":"two"}}', '{"number":NaN}', '{"number":Infinity}', '{"number":1e999}', '{', '{}{}', '\ufeff{}', '"\\ud800"', '[' * 1500 + '0' + ']' * 1500, ]) def test_untrusted_json_is_rejected(raw): with pytest.raises(ContractError): Event.from_json(raw) def test_utf8_byte_limit_and_jsonl_framing(event): raw = Event(event).to_json() assert Event.from_json(raw + b"\n").identity == Event(event).identity assert Event.from_json(raw + b" " * (MAX_EVENT_BYTES - len(raw))) with pytest.raises(ContractError, match="limit_exceeded"): Event.from_json(raw + b" " * (MAX_EVENT_BYTES - len(raw) + 1)) with pytest.raises(ContractError, match="limit_exceeded"): Event.from_json('я' * (MAX_EVENT_BYTES // 2 + 1)) def test_object_limits_before_schema_validation(event): nested = {} for index in range(MAX_DEPTH + 1): nested = {"child": nested} for value in (nested, {"children": [0] * 2049}, {"text": "x" * 2049}): with pytest.raises(ContractError, match="limit_exceeded"): Event(value) event["details"]["reason"] = "secret\nvalue" with pytest.raises(ContractError) as error: Event(event) assert "secret" not in str(error.value) @pytest.mark.parametrize("classification", ["suspicious", "fault", "system", "normal"]) def test_result_classes(classification): payload = example("result.json") payload["classification"] = classification if classification != "fault": payload["fault"] = None assert DetectionResult(payload) def test_result_requires_consistent_fault_and_evidence(): payload = example("result.json") variants = [] for field, value in [("fault", None), ("event_ids", []), ("classification", "attack")]: candidate = deepcopy(payload) candidate[field] = value variants.append(candidate) duplicate = deepcopy(payload) duplicate["event_ids"] *= 2 variants.append(duplicate) inverted = deepcopy(payload) inverted["fault"]["last_seen_sys"] = "2026-12-02T09:30:00Z" variants.append(inverted) for candidate in variants: with pytest.raises(ContractError): DetectionResult(candidate) def test_windows_diagnostics_may_lack_simulated_time(): payload = example("events.json")[-1] assert Event(payload) payload["sim_epoch"] = 0 with pytest.raises(ContractError): Event(payload) def test_system_tag_and_unknown_radio_semantics(): payload = example("events.json")[4] assert Event(payload).to_dict()["stand_mode"] == "FROZEN" payload["origin"] = "windows" with pytest.raises(ContractError): Event(payload) payload = example("events.json")[2] payload["details"]["recognized"] = False with pytest.raises(ContractError): Event(payload) payload["details"]["result"] = "ignored" assert Event(payload) @pytest.mark.parametrize("source,event_type,details", [ ("lighting", "LIGHTING_CHANGED", {"action": "toggle", "enabled_before": False, "enabled_after": True}), ("access", "ACCESS_POINT", {"device": "gate", "action": "stop", "result": "executed", "hall_a0": 0}), ("pc", "PC_POWER", {"pc_id": 1, "reason": "button"}), ("pc", "PC_BOOT", {"pc_id": 2, "reason": "power_on"}), ("pc", "PC_SHUTDOWN", {"pc_id": 3, "reason": "user_request"}), ("pc", "PC_REBOOT", {"pc_id": 1, "reason": "button_long"}), ("os", "OS_BSOD", {"pc_id": 1, "reason": "killall"}), ("os", "OS_COMMAND", {"pc_id": 1, "usb_session_id": None, "command": "killallnet"}), ("os", "OS_APP_OPEN", {"pc_id": 1, "usb_session_id": None, "app": "terminal"}), ("os", "OS_APP_CLOSE", {"pc_id": 1, "usb_session_id": None, "app": "terminal"}), ("clock", "SIM_TIME_CHANGED", {"before": "2026-12-03T12:00:00+03:00", "after": "2026-12-02T12:00:00+03:00", "reason": "rewind"}), ("logger", "LOG_GAP", {"reason": "queue_overflow", "lost_count": None}), ("logger", "RETENTION_PRUNE", {"reason": "age", "removed_records": 10}), ("logger", "MANUAL_RESET", {"actor": "admin", "reason": "Учебный сброс", "old_generation": "20000000-0000-4000-8000-000000000001", "new_generation": "20000000-0000-4000-8000-000000000002"}), ("system", "POLICY_CHANGED", {"actor": "admin", "before": "access-1", "after": "access-2"}), ]) def test_other_event_families(event, source, event_type, details): event.update(source=source, event_type=event_type, details=details) assert Event.from_json(Event(event).to_json()).to_dict() == event @pytest.mark.parametrize("event_type", ["FREEZE_BEGIN", "FREEZE_READY", "FREEZE_END", "FREEZE_FAILED"]) def test_freeze_events(event, event_type): event.update(source="clock", event_type=event_type, details={ "freeze_id": event["correlation_id"], "reason": "encoder", "participants": ["esp32", "okna96"], }) assert Event(event) event["details"]["participants"].append("esp32") with pytest.raises(ContractError, match="duplicate_value"): Event(event) def test_ipc_pair_and_error_response(): request = IPCRequest(example("request.json")) payload = example("response.json") assert IPCResponse(payload).matches(request) payload["request_id"] = "30000000-0000-4000-8000-000000000002" assert not IPCResponse(payload).matches(request) payload.update(status="error", result=None, error=example("error.json")) assert IPCResponse(payload) payload["result"] = {"accepted": 1} with pytest.raises(ContractError, match="invalid_response"): IPCResponse(payload) @pytest.mark.parametrize("operation", ["shell.execute", "gpio.write", "sql.execute", "rules.apply"]) def test_unsupported_operations_are_rejected(operation): payload = example("request.json") payload["operation"] = operation with pytest.raises(ContractError): IPCRequest(payload) def test_ipc_queries_and_nested_validation(): payload = example("request.json") payload.update(operation="events.query", payload={"limit": 100, "cursor": None, "event_type": None}) assert IPCRequest(payload) payload["payload"]["limit"] = 101 with pytest.raises(ContractError): IPCRequest(payload) nested = example("request.json") nested["payload"]["events"][0]["details"]["channel"] = 3 with pytest.raises(ContractError): IPCRequest(nested) nested = example("request.json") nested["payload"]["events"] *= 33 with pytest.raises(ContractError): IPCRequest(nested) with pytest.raises(ContractError, match="limit_exceeded"): IPCRequest.from_json(b" " * (MAX_MESSAGE_BYTES + 1)) def test_results_query_reply_and_health(): payload = example("response.json") payload.update(operation="results.query", result={"items": [example("result.json")], "next_cursor": None}) assert IPCResponse(payload) payload["result"]["items"][0]["fault"] = None with pytest.raises(ContractError): IPCResponse(payload) request = example("request.json") request.update(operation="health.get", payload={}) assert IPCRequest(request) request["payload"]["sql"] = "DROP TABLE events" with pytest.raises(ContractError, match="unknown_field"): IPCRequest(request)