test_facade.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. from __future__ import annotations
  2. import ast
  3. import sys
  4. import threading
  5. import time
  6. from pathlib import Path
  7. import pytest
  8. from hth_sdk import Control, HTH, HTHError, Result, State
  9. from hth_sdk.replay import write_sample_replay
  10. from hth_sdk.sim import SCENARIO_NAMES
  11. def test_public_surface_is_tiny():
  12. import hth_sdk
  13. assert len(hth_sdk.__all__) <= 6
  14. assert set(hth_sdk.__all__) == {"HTH", "State", "Control", "Result", "HTHError"}
  15. def test_demo_is_mock_alias():
  16. assert HTH.demo is not None
  17. with HTH.demo() as hth:
  18. state = hth.read()
  19. assert isinstance(state, State)
  20. assert state.max_temperature_c is not None
  21. result = hth.set(fan=20, heater=30, door=0)
  22. assert isinstance(result, Result)
  23. assert result.ok is True
  24. assert result.sent is True
  25. def test_sync_read_and_set():
  26. with HTH.mock(scenario="normal", seed=1, speed=50) as hth:
  27. state = hth.read()
  28. assert isinstance(state, State)
  29. assert len(state.temperatures_c) == 27
  30. assert len(state.temperature_valid) == 27
  31. assert all(state.temperature_valid)
  32. assert all(t is not None for t in state.temperatures_c)
  33. assert state.control is None
  34. assert state.control_known is False
  35. result = hth.set(fan=20, heater=30, door=0)
  36. assert result.ok is True
  37. assert result.sent is True
  38. assert not (result.ok and not result.sent)
  39. again = hth.read()
  40. assert again.control_known is True
  41. assert again.fans_percent == [20, 20, 20, 20]
  42. assert again.heaters_percent == [30, 30, 30, 30]
  43. assert again.doors_close_percent == {"x": 0, "y": 0, "z": 0}
  44. def test_vector_length_is_strict():
  45. with HTH.demo() as hth:
  46. with pytest.raises(HTHError) as extra:
  47. hth.set(fans=[1, 2, 3, 4, 5], heaters=[0, 0, 0, 0], doors={"x": 0, "y": 0, "z": 0})
  48. assert extra.value.code == "LENGTH"
  49. with pytest.raises(HTHError) as missing:
  50. hth.set(fans=[1, 2, 3], heaters=[0, 0, 0, 0], doors={"x": 0, "y": 0, "z": 0})
  51. assert missing.value.code == "LENGTH"
  52. with pytest.raises(HTHError) as door:
  53. hth.set(fan=10, heater=0, doors={"x": 0, "y": 0, "q": 1})
  54. assert door.value.code == "DOOR_NAME"
  55. def test_out_of_range_and_explicit_clamp():
  56. with HTH.demo() as hth:
  57. with pytest.raises(HTHError) as ei:
  58. hth.set(fan=120, heater=0, door=0)
  59. assert ei.value.code == "OUT_OF_RANGE"
  60. result = hth.set(fan=120, heater=-3, door=0, allow_clamp=True)
  61. assert result.ok
  62. assert "0..100" in result.warning
  63. state = hth.read()
  64. assert state.fans_percent == [100, 100, 100, 100]
  65. assert state.heaters_percent == [0, 0, 0, 0]
  66. def test_watch_and_auto_lease():
  67. with HTH.mock(scenario="normal", seed=2, speed=40) as hth:
  68. n = 0
  69. for state in hth.watch(period=0.01, count=3):
  70. n += 1
  71. r = hth.set(fan=15 + n, heater=5, door=0)
  72. assert r.ok
  73. assert state.max_temperature_c is not None
  74. assert n == 3
  75. def test_safe_and_resume():
  76. with HTH.mock(scenario="normal", seed=1, speed=40) as hth:
  77. safe = hth.safe()
  78. assert safe.ok
  79. state = hth.read()
  80. assert state.ready is False
  81. with pytest.raises(HTHError) as ei:
  82. hth.set(fan=10, heater=0, door=0)
  83. assert ei.value.code == "NOT_READY"
  84. res = hth.resume(fan=12, heater=0, door=0)
  85. assert res.ok
  86. assert hth.read().ready is True
  87. def test_replay_readonly_and_default_path():
  88. with HTH.replay() as hth:
  89. state = hth.read()
  90. assert len(state.temperatures_c) == 27
  91. with pytest.raises(HTHError) as ei:
  92. hth.set(fan=10, heater=0, door=0)
  93. assert ei.value.code == "READ_ONLY"
  94. assert ei.value.recoverable is False
  95. assert ei.value.suggestion
  96. def test_replay_missing_file(tmp_path):
  97. with pytest.raises(HTHError) as ei:
  98. HTH.replay(tmp_path / "missing.jsonl")
  99. assert ei.value.code == "REPLAY_NOT_FOUND"
  100. assert ei.value.suggestion
  101. def test_scenarios_run():
  102. for name in SCENARIO_NAMES:
  103. with HTH.mock(scenario=name, seed=1, speed=80) as hth:
  104. st = hth.read()
  105. assert isinstance(st, State)
  106. if name == "normal":
  107. assert None not in st.temperatures_c
  108. if name == "sensor_invalid":
  109. assert any(t is None for t in st.temperatures_c)
  110. if name == "sensor_stale":
  111. assert st.fresh is False
  112. if name == "safe_mode":
  113. assert st.ready is False
  114. def test_stale_fail_closed():
  115. with HTH.mock(scenario="sensor_stale", seed=1, speed=20) as hth:
  116. with pytest.raises(HTHError) as ei:
  117. hth.set(fan=10, heater=0, door=0)
  118. assert ei.value.code == "STALE"
  119. def test_disconnect_recover_full_cycle():
  120. with HTH.mock(scenario="disconnect_recover", seed=1, speed=2) as hth:
  121. first = hth.read()
  122. assert first.ready is True
  123. assert first.fresh is True
  124. epoch0 = first.meta["device_epoch"]
  125. time.sleep(0.15)
  126. mid = hth.read()
  127. assert mid.ready is False
  128. assert mid.fresh is False
  129. assert mid.meta["device_epoch"] != epoch0
  130. assert mid.control is None
  131. time.sleep(0.2)
  132. last = hth.read()
  133. assert last.ready is True
  134. assert last.fresh is True
  135. assert last.meta["snapshot_seq"] > mid.meta["snapshot_seq"]
  136. def test_same_policy_mock_and_replay(tmp_path):
  137. def policy(hth: HTH) -> list[float | None]:
  138. out = []
  139. for state in hth.watch(period=0.01, count=2):
  140. heat = 20 if (state.max_temperature_c or 99) < 40 else 0
  141. if state.ready and state.fresh:
  142. hth.set(fan=20, heater=heat, door=0)
  143. out.append(state.max_temperature_c)
  144. return out
  145. with HTH.mock(scenario="normal", seed=1, speed=40) as mock:
  146. mock_vals = policy(mock)
  147. path = write_sample_replay(tmp_path / "p.jsonl")
  148. with HTH.replay(path) as replay:
  149. replay_state = replay.read()
  150. assert len(replay_state.temperatures_c) == 27
  151. with pytest.raises(HTHError):
  152. replay.set(fan=10, heater=0, door=0)
  153. assert mock_vals
  154. def test_error_model():
  155. err = HTHError("x", code="STALE", recoverable=True)
  156. assert err.code == "STALE"
  157. assert err.message == "x"
  158. assert err.recoverable is True
  159. assert err.suggestion
  160. def test_unknown_scenario_is_hth_error():
  161. with pytest.raises(HTHError) as ei:
  162. HTH.mock(scenario="no-such-world")
  163. assert ei.value.code == "UNKNOWN_SCENARIO"
  164. def test_windows_connect_is_hth_error():
  165. if sys.platform != "win32":
  166. pytest.skip("Windows-only connect refusal")
  167. with pytest.raises(HTHError) as ei:
  168. HTH.connect()
  169. assert ei.value.code == "CONNECT_UNSUPPORTED"
  170. assert ei.value.suggestion
  171. def test_no_thread_leak():
  172. with HTH.demo(seed=1, speed=30) as hth:
  173. hth.read()
  174. hth.set(fan=10, heater=0, door=0)
  175. hth.close()
  176. hth.close()
  177. leftover = [t for t in threading.enumerate() if t.name == "hth-facade-loop" and t.is_alive()]
  178. assert leftover == []
  179. def test_quickstart_is_clean():
  180. root = Path(__file__).resolve().parents[1]
  181. qs = (root / "examples" / "quickstart.py").read_text(encoding="utf-8")
  182. banned = (
  183. "grpc",
  184. "protobuf",
  185. "unix socket",
  186. "lease",
  187. "epoch",
  188. "command_id",
  189. "command id",
  190. "snapshot_seq",
  191. "snapshot seq",
  192. "control_revision",
  193. "control revision",
  194. "ttl",
  195. "capability hash",
  196. "unconfirmed",
  197. )
  198. low = qs.lower()
  199. for word in banned:
  200. assert word not in low, word
  201. tree = ast.parse(qs)
  202. for node in ast.walk(tree):
  203. if isinstance(node, ast.ImportFrom) and node.module:
  204. assert not node.module.startswith("hth_sdk.advanced")
  205. assert "grpc" not in node.module
  206. assert "generated" not in node.module
  207. core = [ln for ln in qs.splitlines() if ln.strip() and not ln.strip().startswith("#")]
  208. assert len(core) <= 10
  209. assert "HTH.demo()" in qs
  210. assert "max_temperature_c" in qs
  211. assert "Control" not in qs
  212. def test_thermal_repeatable():
  213. def run():
  214. with HTH.mock(scenario="coupled_4chamber", seed=7, speed=50, mode="step") as hth:
  215. hth.set(fan=10, heater=40, door=0)
  216. for _ in hth.watch(period=0.01, count=4):
  217. pass
  218. return hth.read().temperatures_c[:4]
  219. assert run() == run()
  220. def test_control_object_and_bad_mix():
  221. with HTH.demo() as hth:
  222. ctl = Control(fans=[10, 11, 12, 13], heaters=[1, 2, 3, 4], doors={"x": 5, "y": 6, "z": 7})
  223. result = hth.set(ctl)
  224. assert result.ok
  225. state = hth.read()
  226. assert state.fans_percent == [10, 11, 12, 13]
  227. assert state.heaters_percent == [1, 2, 3, 4]
  228. assert state.doors_close_percent == {"x": 5, "y": 6, "z": 7}
  229. assert state.control_known is True
  230. payload = state.to_dict()
  231. assert payload["fans_percent"] == [10, 11, 12, 13]
  232. assert state.mean_temperature_c is not None
  233. with pytest.raises(HTHError) as mixed:
  234. hth.set(ctl, fan=1)
  235. assert mixed.value.code == "BAD_CONTROL"
  236. with pytest.raises(HTHError) as incomplete:
  237. hth.set(fan=1)
  238. assert incomplete.value.code == "BAD_CONTROL"
  239. with pytest.raises(HTHError) as both:
  240. hth.set(fan=1, fans=[1, 2, 3, 4], heater=0, door=0)
  241. assert both.value.code == "BAD_CONTROL"
  242. def test_closed_handle_is_hth_error():
  243. hth = HTH.demo()
  244. hth.read()
  245. hth.close()
  246. with pytest.raises(HTHError) as ei:
  247. hth.read()
  248. assert ei.value.code == "CLOSED"
  249. assert ei.value.recoverable is False
  250. def test_replay_invalid_jsonl(tmp_path):
  251. bad = tmp_path / "bad.jsonl"
  252. bad.write_text("{not-json\n", encoding="utf-8")
  253. with pytest.raises(HTHError) as ei:
  254. HTH.replay(bad)
  255. assert ei.value.code == "REPLAY_INVALID"
  256. assert ei.value.suggestion
  257. def test_connect_without_daemon():
  258. if sys.platform == "win32":
  259. with pytest.raises(HTHError) as ei:
  260. HTH.connect()
  261. assert ei.value.code == "CONNECT_UNSUPPORTED"
  262. return
  263. with pytest.raises(HTHError) as ei:
  264. HTH.connect(observe="/tmp/hth-missing-obs.sock", control="/tmp/hth-missing-ctl.sock")
  265. assert ei.value.code in {"DAEMON_NOT_RUNNING", "LIVE_DEPENDENCY", "SOCKET_PERMISSION", "CONNECT_UNSUPPORTED"}
  266. assert ei.value.suggestion