portfolio-optimiser/tests/test_notify.py

71 lines
2.8 KiB
Python

"""S5.2 — Varsling: unit/contract tests for ``notify.py`` (Notifier protocol + notifiers).
Detach-seam (RED-when-detached) twins live in ``tests/test_notify_loadbearing.py``. Tests may
import MAF-tainted modules freely (``verdicts``) — only ``notify.py`` itself must stay MAF-free.
"""
from __future__ import annotations
import io
import json
from portfolio_optimiser.notify import ConsoleNotifier, FileNotifier, Notifier, _verdict_payload
from portfolio_optimiser.verdicts import ProposalFeatures, Verdict, capture_verdict, verdict_to_dict
def _verdict() -> Verdict:
return capture_verdict(
ProposalFeatures(
affected_codes=frozenset({"05.2", "03.1"}),
measure_type="scope_reduction",
claimed_saving_nok=200_000.0,
description="LED retrofit",
),
"approved",
"feasible within range",
)
def test_plain_callable_satisfies_notifier() -> None:
"""The seam promise: any plain callable satisfies the runtime-checkable ``Notifier`` protocol,
so ``run_project(notify=lambda v: ...)`` stays valid — a structural superset of
``Callable[[Verdict], None]``, not a new ABC (needs ``@runtime_checkable``)."""
assert isinstance(lambda v: None, Notifier)
def test_console_emits_id_and_decision() -> None:
"""ConsoleNotifier writes the verdict id + decision to the injected stream (never a URL)."""
stream = io.StringIO()
verdict = _verdict()
ConsoleNotifier(stream=stream)(verdict)
out = stream.getvalue()
assert verdict.id in out
assert verdict.decision in out
def test_payload_matches_verdict_to_dict_oracle() -> None:
"""DRIFT-ORACLE: the duck-typed ``_verdict_payload`` reproduces ``verdict_to_dict``'s exact
NESTED shape (verdicts.py:124-139) without importing it at runtime — the test imports both
(tests may pull MAF freely) and pins them equal, so a ``Verdict`` shape change goes RED here
instead of silently diverging the notified payload."""
verdict = _verdict()
assert _verdict_payload(verdict) == verdict_to_dict(verdict)
def test_file_notifier_byte_deterministic(tmp_path) -> None:
"""FileNotifier appends one JSONL line per verdict — two writes of the same verdict are
byte-identical, LF-terminated, nested per the oracle shape, and carry no wall-clock key."""
path = tmp_path / "sub" / "notify.jsonl"
verdict = _verdict()
notifier = FileNotifier(str(path))
notifier(verdict)
first = path.read_bytes()
notifier(verdict)
second = path.read_bytes()
assert second == first * 2 # identical appended line bytes
line = first.decode("utf-8")
assert line.endswith("\n")
payload = json.loads(line)
assert payload["id"] == verdict.id
assert payload["proposal_features"]["affected_codes"] == ["03.1", "05.2"]
assert not any(k in payload for k in ("date", "timestamp", "created", "ts"))