from __future__ import annotations import ast import sys import threading import time 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 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_demo_is_mock_alias(): assert HTH.demo is not None with HTH.demo() as hth: state = hth.read() assert isinstance(state, State) assert state.max_temperature_c is not None result = hth.set(fan=20, heater=30, door=0) assert isinstance(result, Result) assert result.ok is True assert result.sent is True 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 all(state.temperature_valid) assert all(t is not None for t in state.temperatures_c) assert state.control is None assert state.control_known is False result = hth.set(fan=20, heater=30, door=0) assert result.ok is True assert result.sent is True assert not (result.ok and not result.sent) again = hth.read() assert again.control_known is True assert again.fans_percent == [20, 20, 20, 20] assert again.heaters_percent == [30, 30, 30, 30] assert again.doors_close_percent == {"x": 0, "y": 0, "z": 0} def test_vector_length_is_strict(): with HTH.demo() as hth: with pytest.raises(HTHError) as extra: hth.set(fans=[1, 2, 3, 4, 5], heaters=[0, 0, 0, 0], doors={"x": 0, "y": 0, "z": 0}) assert extra.value.code == "LENGTH" with pytest.raises(HTHError) as missing: hth.set(fans=[1, 2, 3], heaters=[0, 0, 0, 0], doors={"x": 0, "y": 0, "z": 0}) assert missing.value.code == "LENGTH" with pytest.raises(HTHError) as door: hth.set(fan=10, heater=0, doors={"x": 0, "y": 0, "q": 1}) assert door.value.code == "DOOR_NAME" def test_out_of_range_and_explicit_clamp(): with HTH.demo() as hth: with pytest.raises(HTHError) as ei: hth.set(fan=120, heater=0, door=0) assert ei.value.code == "OUT_OF_RANGE" result = hth.set(fan=120, heater=-3, door=0, allow_clamp=True) assert result.ok assert "0..100" in result.warning state = hth.read() assert state.fans_percent == [100, 100, 100, 100] assert state.heaters_percent == [0, 0, 0, 0] 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(fan=15 + n, heater=5, door=0) assert r.ok assert state.max_temperature_c is not None 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(fan=10, heater=0, door=0) assert ei.value.code == "NOT_READY" res = hth.resume(fan=12, heater=0, door=0) assert res.ok assert hth.read().ready is True def test_replay_readonly_and_default_path(): with HTH.replay() as hth: state = hth.read() assert len(state.temperatures_c) == 27 with pytest.raises(HTHError) as ei: hth.set(fan=10, heater=0, door=0) assert ei.value.code == "READ_ONLY" assert ei.value.recoverable is False assert ei.value.suggestion def test_replay_missing_file(tmp_path): with pytest.raises(HTHError) as ei: HTH.replay(tmp_path / "missing.jsonl") assert ei.value.code == "REPLAY_NOT_FOUND" assert ei.value.suggestion 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 == "normal": assert None not in st.temperatures_c if name == "sensor_invalid": assert any(t is None for t in st.temperatures_c) 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(fan=10, heater=0, door=0) assert ei.value.code == "STALE" def test_disconnect_recover_full_cycle(): with HTH.mock(scenario="disconnect_recover", seed=1, speed=2) as hth: first = hth.read() assert first.ready is True assert first.fresh is True epoch0 = first.meta["device_epoch"] time.sleep(0.15) mid = hth.read() assert mid.ready is False assert mid.fresh is False assert mid.meta["device_epoch"] != epoch0 assert mid.control is None time.sleep(0.2) last = hth.read() assert last.ready is True assert last.fresh is True assert last.meta["snapshot_seq"] > mid.meta["snapshot_seq"] 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): heat = 20 if (state.max_temperature_c or 99) < 40 else 0 if state.ready and state.fresh: hth.set(fan=20, heater=heat, door=0) out.append(state.max_temperature_c) 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(fan=10, heater=0, door=0) 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 assert err.suggestion def test_unknown_scenario_is_hth_error(): with pytest.raises(HTHError) as ei: HTH.mock(scenario="no-such-world") assert ei.value.code == "UNKNOWN_SCENARIO" def test_windows_connect_is_hth_error(): if sys.platform != "win32": pytest.skip("Windows-only connect refusal") with pytest.raises(HTHError) as ei: HTH.connect() assert ei.value.code == "CONNECT_UNSUPPORTED" assert ei.value.suggestion def test_no_thread_leak(): with HTH.demo(seed=1, speed=30) as hth: hth.read() hth.set(fan=10, heater=0, door=0) hth.close() hth.close() leftover = [t for t in threading.enumerate() if t.name == "hth-facade-loop" and t.is_alive()] assert leftover == [] 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", "command id", "snapshot_seq", "snapshot seq", "control_revision", "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) <= 10 assert "HTH.demo()" in qs assert "max_temperature_c" in qs assert "Control" not in qs def test_thermal_repeatable(): def run(): with HTH.mock(scenario="coupled_4chamber", seed=7, speed=50, mode="step") as hth: hth.set(fan=10, heater=40, door=0) for _ in hth.watch(period=0.01, count=4): pass return hth.read().temperatures_c[:4] assert run() == run() def test_control_object_and_bad_mix(): with HTH.demo() as hth: ctl = Control(fans=[10, 11, 12, 13], heaters=[1, 2, 3, 4], doors={"x": 5, "y": 6, "z": 7}) result = hth.set(ctl) assert result.ok state = hth.read() assert state.fans_percent == [10, 11, 12, 13] assert state.heaters_percent == [1, 2, 3, 4] assert state.doors_close_percent == {"x": 5, "y": 6, "z": 7} assert state.control_known is True payload = state.to_dict() assert payload["fans_percent"] == [10, 11, 12, 13] assert state.mean_temperature_c is not None with pytest.raises(HTHError) as mixed: hth.set(ctl, fan=1) assert mixed.value.code == "BAD_CONTROL" with pytest.raises(HTHError) as incomplete: hth.set(fan=1) assert incomplete.value.code == "BAD_CONTROL" with pytest.raises(HTHError) as both: hth.set(fan=1, fans=[1, 2, 3, 4], heater=0, door=0) assert both.value.code == "BAD_CONTROL" def test_closed_handle_is_hth_error(): hth = HTH.demo() hth.read() hth.close() with pytest.raises(HTHError) as ei: hth.read() assert ei.value.code == "CLOSED" assert ei.value.recoverable is False def test_replay_invalid_jsonl(tmp_path): bad = tmp_path / "bad.jsonl" bad.write_text("{not-json\n", encoding="utf-8") with pytest.raises(HTHError) as ei: HTH.replay(bad) assert ei.value.code == "REPLAY_INVALID" assert ei.value.suggestion def test_connect_without_daemon(): if sys.platform == "win32": with pytest.raises(HTHError) as ei: HTH.connect() assert ei.value.code == "CONNECT_UNSUPPORTED" return with pytest.raises(HTHError) as ei: HTH.connect(observe="/tmp/hth-missing-obs.sock", control="/tmp/hth-missing-ctl.sock") assert ei.value.code in {"DAEMON_NOT_RUNNING", "LIVE_DEPENDENCY", "SOCKET_PERMISSION", "CONNECT_UNSUPPORTED"} assert ei.value.suggestion