| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180 |
- from __future__ import annotations
- import ast
- import threading
- from pathlib import Path
- import pytest
- from hth_sdk import Control, HTH, HTHError, Result, State
- from hth_sdk.replay import write_sample_replay
- from hth_sdk.sim import SCENARIO_NAMES
- def _ctrl(fans=20, heaters=10, doors=None) -> Control:
- return Control(
- fans=[fans] * 4,
- heaters=[heaters] * 4,
- doors=doors or {"x": 0, "y": 0, "z": 0},
- )
- def test_public_surface_is_tiny():
- import hth_sdk
- assert len(hth_sdk.__all__) <= 6
- assert set(hth_sdk.__all__) == {"HTH", "State", "Control", "Result", "HTHError"}
- def test_sync_read_and_set():
- with HTH.mock(scenario="normal", seed=1, speed=50) as hth:
- state = hth.read()
- assert isinstance(state, State)
- assert len(state.temperatures_c) == 27
- assert len(state.temperature_valid) == 27
- assert state.temperatures_c[26] is None
- assert state.temperature_valid[26] is False
- assert state.control.fans
- result = hth.set(_ctrl())
- assert isinstance(result, Result)
- assert result.ok is True
- assert result.sent is True
- assert "UNCONFIRMED" not in (result.warning or "")
- assert result.meta.get("command_id")
- again = hth.read()
- assert again.fans_percent[0] == 20
- assert again.meta.get("snapshot_seq")
- def test_watch_and_auto_lease():
- with HTH.mock(scenario="normal", seed=2, speed=40) as hth:
- n = 0
- for state in hth.watch(period=0.01, count=3):
- n += 1
- r = hth.set(_ctrl(fans=15 + n, heaters=5))
- assert r.ok
- assert n == 3
- def test_safe_and_resume():
- with HTH.mock(scenario="normal", seed=1, speed=40) as hth:
- safe = hth.safe()
- assert safe.ok
- state = hth.read()
- assert state.ready is False
- with pytest.raises(HTHError) as ei:
- hth.set(_ctrl())
- assert ei.value.code == "NOT_READY"
- res = hth.resume(_ctrl(fans=12, heaters=0))
- assert res.ok
- assert hth.read().ready is True
- def test_replay_readonly(tmp_path):
- path = write_sample_replay(tmp_path / "r.jsonl")
- with HTH.replay(path) as hth:
- state = hth.read()
- assert len(state.temperatures_c) == 27
- with pytest.raises(HTHError) as ei:
- hth.set(_ctrl())
- assert ei.value.code == "READ_ONLY"
- assert ei.value.recoverable is False
- def test_scenarios_run():
- for name in SCENARIO_NAMES:
- with HTH.mock(scenario=name, seed=1, speed=80) as hth:
- st = hth.read()
- assert isinstance(st, State)
- if name == "sensor_stale":
- assert st.fresh is False
- if name == "safe_mode":
- assert st.ready is False
- def test_stale_fail_closed():
- with HTH.mock(scenario="sensor_stale", seed=1, speed=20) as hth:
- with pytest.raises(HTHError) as ei:
- hth.set(_ctrl())
- assert ei.value.code == "STALE"
- def test_same_policy_mock_and_replay(tmp_path):
- def policy(hth: HTH) -> list[float | None]:
- out = []
- for state in hth.watch(period=0.01, count=2):
- valid = [t for t in state.temperatures_c if t is not None]
- heat = 20 if valid and max(valid) < 40 else 0
- if state.ready and state.fresh:
- hth.set(_ctrl(heaters=heat))
- out.append(max(valid) if valid else None)
- return out
- with HTH.mock(scenario="normal", seed=1, speed=40) as mock:
- mock_vals = policy(mock)
- path = write_sample_replay(tmp_path / "p.jsonl")
- with HTH.replay(path) as replay:
- replay_state = replay.read()
- assert len(replay_state.temperatures_c) == 27
- with pytest.raises(HTHError):
- replay.set(_ctrl())
- assert mock_vals
- def test_error_model():
- err = HTHError("x", code="STALE", recoverable=True)
- assert err.code == "STALE"
- assert err.message == "x"
- assert err.recoverable is True
- def test_no_thread_leak():
- before = {t.name for t in threading.enumerate()}
- with HTH.mock(seed=1, speed=30) as hth:
- hth.read()
- hth.set(_ctrl())
- leftover = [t for t in threading.enumerate() if t.name == "hth-facade-loop" and t.is_alive()]
- assert leftover == []
- _ = before
- def test_quickstart_is_clean():
- root = Path(__file__).resolve().parents[1]
- qs = (root / "examples" / "quickstart.py").read_text(encoding="utf-8")
- banned = (
- "grpc",
- "protobuf",
- "unix socket",
- "lease",
- "epoch",
- "command id",
- "snapshot seq",
- "control revision",
- "ttl",
- "capability hash",
- "unconfirmed",
- )
- low = qs.lower()
- for word in banned:
- assert word not in low, word
- tree = ast.parse(qs)
- for node in ast.walk(tree):
- if isinstance(node, ast.ImportFrom) and node.module:
- assert not node.module.startswith("hth_sdk.advanced")
- assert "grpc" not in node.module
- assert "generated" not in node.module
- core = [ln for ln in qs.splitlines() if ln.strip() and not ln.strip().startswith("#")]
- assert len(core) <= 15
- def test_thermal_repeatable():
- def run():
- with HTH.mock(scenario="coupled_4chamber", seed=7, speed=50, mode="step") as hth:
- hth.set(_ctrl(heaters=40, fans=10))
- for _ in hth.watch(period=0.01, count=4):
- pass
- return hth.read().temperatures_c[:4]
- a = run()
- b = run()
- assert a == b
|