test_facade.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. from __future__ import annotations
  2. import ast
  3. import threading
  4. from pathlib import Path
  5. import pytest
  6. from hth_sdk import Control, HTH, HTHError, Result, State
  7. from hth_sdk.replay import write_sample_replay
  8. from hth_sdk.sim import SCENARIO_NAMES
  9. def _ctrl(fans=20, heaters=10, doors=None) -> Control:
  10. return Control(
  11. fans=[fans] * 4,
  12. heaters=[heaters] * 4,
  13. doors=doors or {"x": 0, "y": 0, "z": 0},
  14. )
  15. def test_public_surface_is_tiny():
  16. import hth_sdk
  17. assert len(hth_sdk.__all__) <= 6
  18. assert set(hth_sdk.__all__) == {"HTH", "State", "Control", "Result", "HTHError"}
  19. def test_sync_read_and_set():
  20. with HTH.mock(scenario="normal", seed=1, speed=50) as hth:
  21. state = hth.read()
  22. assert isinstance(state, State)
  23. assert len(state.temperatures_c) == 27
  24. assert len(state.temperature_valid) == 27
  25. assert state.temperatures_c[26] is None
  26. assert state.temperature_valid[26] is False
  27. assert state.control.fans
  28. result = hth.set(_ctrl())
  29. assert isinstance(result, Result)
  30. assert result.ok is True
  31. assert result.sent is True
  32. assert "UNCONFIRMED" not in (result.warning or "")
  33. assert result.meta.get("command_id")
  34. again = hth.read()
  35. assert again.fans_percent[0] == 20
  36. assert again.meta.get("snapshot_seq")
  37. def test_watch_and_auto_lease():
  38. with HTH.mock(scenario="normal", seed=2, speed=40) as hth:
  39. n = 0
  40. for state in hth.watch(period=0.01, count=3):
  41. n += 1
  42. r = hth.set(_ctrl(fans=15 + n, heaters=5))
  43. assert r.ok
  44. assert n == 3
  45. def test_safe_and_resume():
  46. with HTH.mock(scenario="normal", seed=1, speed=40) as hth:
  47. safe = hth.safe()
  48. assert safe.ok
  49. state = hth.read()
  50. assert state.ready is False
  51. with pytest.raises(HTHError) as ei:
  52. hth.set(_ctrl())
  53. assert ei.value.code == "NOT_READY"
  54. res = hth.resume(_ctrl(fans=12, heaters=0))
  55. assert res.ok
  56. assert hth.read().ready is True
  57. def test_replay_readonly(tmp_path):
  58. path = write_sample_replay(tmp_path / "r.jsonl")
  59. with HTH.replay(path) as hth:
  60. state = hth.read()
  61. assert len(state.temperatures_c) == 27
  62. with pytest.raises(HTHError) as ei:
  63. hth.set(_ctrl())
  64. assert ei.value.code == "READ_ONLY"
  65. assert ei.value.recoverable is False
  66. def test_scenarios_run():
  67. for name in SCENARIO_NAMES:
  68. with HTH.mock(scenario=name, seed=1, speed=80) as hth:
  69. st = hth.read()
  70. assert isinstance(st, State)
  71. if name == "sensor_stale":
  72. assert st.fresh is False
  73. if name == "safe_mode":
  74. assert st.ready is False
  75. def test_stale_fail_closed():
  76. with HTH.mock(scenario="sensor_stale", seed=1, speed=20) as hth:
  77. with pytest.raises(HTHError) as ei:
  78. hth.set(_ctrl())
  79. assert ei.value.code == "STALE"
  80. def test_same_policy_mock_and_replay(tmp_path):
  81. def policy(hth: HTH) -> list[float | None]:
  82. out = []
  83. for state in hth.watch(period=0.01, count=2):
  84. valid = [t for t in state.temperatures_c if t is not None]
  85. heat = 20 if valid and max(valid) < 40 else 0
  86. if state.ready and state.fresh:
  87. hth.set(_ctrl(heaters=heat))
  88. out.append(max(valid) if valid else None)
  89. return out
  90. with HTH.mock(scenario="normal", seed=1, speed=40) as mock:
  91. mock_vals = policy(mock)
  92. path = write_sample_replay(tmp_path / "p.jsonl")
  93. with HTH.replay(path) as replay:
  94. replay_state = replay.read()
  95. assert len(replay_state.temperatures_c) == 27
  96. with pytest.raises(HTHError):
  97. replay.set(_ctrl())
  98. assert mock_vals
  99. def test_error_model():
  100. err = HTHError("x", code="STALE", recoverable=True)
  101. assert err.code == "STALE"
  102. assert err.message == "x"
  103. assert err.recoverable is True
  104. def test_no_thread_leak():
  105. before = {t.name for t in threading.enumerate()}
  106. with HTH.mock(seed=1, speed=30) as hth:
  107. hth.read()
  108. hth.set(_ctrl())
  109. leftover = [t for t in threading.enumerate() if t.name == "hth-facade-loop" and t.is_alive()]
  110. assert leftover == []
  111. _ = before
  112. def test_quickstart_is_clean():
  113. root = Path(__file__).resolve().parents[1]
  114. qs = (root / "examples" / "quickstart.py").read_text(encoding="utf-8")
  115. banned = (
  116. "grpc",
  117. "protobuf",
  118. "unix socket",
  119. "lease",
  120. "epoch",
  121. "command id",
  122. "snapshot seq",
  123. "control revision",
  124. "ttl",
  125. "capability hash",
  126. "unconfirmed",
  127. )
  128. low = qs.lower()
  129. for word in banned:
  130. assert word not in low, word
  131. tree = ast.parse(qs)
  132. for node in ast.walk(tree):
  133. if isinstance(node, ast.ImportFrom) and node.module:
  134. assert not node.module.startswith("hth_sdk.advanced")
  135. assert "grpc" not in node.module
  136. assert "generated" not in node.module
  137. core = [ln for ln in qs.splitlines() if ln.strip() and not ln.strip().startswith("#")]
  138. assert len(core) <= 15
  139. def test_thermal_repeatable():
  140. def run():
  141. with HTH.mock(scenario="coupled_4chamber", seed=7, speed=50, mode="step") as hth:
  142. hth.set(_ctrl(heaters=40, fans=10))
  143. for _ in hth.watch(period=0.01, count=4):
  144. pass
  145. return hth.read().temperatures_c[:4]
  146. a = run()
  147. b = run()
  148. assert a == b