test_devices.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. """Device boundary tests use subprocess stubs only; no BMC/network is contacted."""
  2. import asyncio
  3. import json
  4. import os
  5. from pathlib import Path
  6. import sys
  7. import tempfile
  8. import unittest
  9. from unittest.mock import patch
  10. from stl_backend.devices import DeviceError, HardwareDevice, JsonLineBridge, ManualActionRequired, SimulatedDevice
  11. BRIDGE = r'''
  12. import json,sys,time
  13. state="off"
  14. for line in sys.stdin:
  15. r=json.loads(line); op=r["operation"]
  16. if op=="wait": time.sleep(5)
  17. if op=="bad": print(json.dumps({"id":"wrong","ok":True,"result":{}}),flush=True); continue
  18. if op=="supply_set": state="unknown"; result={"accepted":True}
  19. elif op=="supply_read": result={"state":state}
  20. elif op=="set_target": result={"confirmed_target_c":r["arguments"]["target_c"]}
  21. elif op=="read_telemetry": result={"air_c":70.5,"dimms":[],"quality":"valid","board_state":"running"}
  22. else: result={"echo":op}
  23. print(json.dumps({"id":r["id"],"ok":True,"result":result}),flush=True)
  24. '''
  25. class DeviceTests(unittest.IsolatedAsyncioTestCase):
  26. async def asyncSetUp(self):
  27. self.tmp = tempfile.TemporaryDirectory()
  28. self.root = Path(self.tmp.name)
  29. self.bridge_config = {"argv": [sys.executable, "-u", "-c", BRIDGE], "timeout_s": 1}
  30. async def asyncTearDown(self):
  31. self.tmp.cleanup()
  32. async def test_bridge_id_mismatch_resets_process(self):
  33. bridge = JsonLineBridge(self.bridge_config)
  34. try:
  35. with self.assertRaisesRegex(DeviceError, "ID"):
  36. await bridge.call("bad")
  37. self.assertIsNone(bridge._proc)
  38. self.assertEqual(await bridge.call("hello"), {"echo": "hello"})
  39. finally:
  40. await bridge.close()
  41. async def test_bridge_timeout_kills_process_and_next_request_is_fresh(self):
  42. bridge = JsonLineBridge({**self.bridge_config, "timeout_s": 2})
  43. try:
  44. # Exercise an in-flight request timeout, not interpreter startup speed.
  45. self.assertEqual(await bridge.call("hello"), {"echo": "hello"})
  46. bridge.timeout = 0.1
  47. with self.assertRaisesRegex(DeviceError, "超时"):
  48. await bridge.call("wait")
  49. self.assertIsNone(bridge._proc)
  50. bridge.timeout = 2
  51. self.assertEqual(await bridge.call("hello"), {"echo": "hello"})
  52. finally:
  53. await bridge.close()
  54. async def test_bridge_cancel_does_not_leave_old_response(self):
  55. bridge = JsonLineBridge(self.bridge_config)
  56. task = asyncio.create_task(bridge.call("wait"))
  57. try:
  58. await asyncio.sleep(0.05)
  59. task.cancel()
  60. with self.assertRaises(asyncio.CancelledError):
  61. await task
  62. self.assertIsNone(bridge._proc)
  63. self.assertEqual(await bridge.call("hello"), {"echo": "hello"})
  64. finally:
  65. await bridge.close()
  66. async def test_bridge_serializes_concurrent_requests(self):
  67. bridge = JsonLineBridge(self.bridge_config)
  68. try:
  69. results = await asyncio.gather(*(bridge.call(str(i)) for i in range(10)))
  70. self.assertEqual(results, [{"echo": str(i)} for i in range(10)])
  71. finally:
  72. await bridge.close()
  73. async def test_supply_ack_is_not_off_confirmation(self):
  74. device = HardwareDevice({"bridge": self.bridge_config, "supply_mode": "bridge"})
  75. try:
  76. self.assertEqual(await device.supply_set(False), "unknown")
  77. self.assertEqual(await device.set_target(80.5), 80.5)
  78. data = await device.read_telemetry()
  79. self.assertEqual(data["air_c"], 70.5)
  80. self.assertEqual(data["dimms"], [])
  81. finally:
  82. await device.close()
  83. async def test_manual_supply_requires_explicit_confirmation(self):
  84. device = HardwareDevice({"supply_mode": "manual"})
  85. self.assertEqual(await device.supply_read(), "unknown")
  86. with self.assertRaises(ManualActionRequired) as caught:
  87. await device.supply_set(True)
  88. self.assertTrue(caught.exception.on)
  89. await device.confirm_supply(True)
  90. self.assertEqual(await device.supply_set(True), "on")
  91. with self.assertRaises(ManualActionRequired):
  92. await device.supply_set(False)
  93. await device.confirm_supply(False)
  94. self.assertEqual(await device.supply_read(), "off")
  95. await device.close()
  96. async def test_invalid_telemetry_finite_values_required(self):
  97. script = BRIDGE.replace('"air_c":70.5', '"air_c":float("nan")')
  98. device = HardwareDevice({"bridge": {"argv": [sys.executable, "-u", "-c", script]}})
  99. try:
  100. with self.assertRaisesRegex(DeviceError, "有限数值"):
  101. await device.read_telemetry()
  102. finally:
  103. await device.close()
  104. async def test_bmc_password_is_environment_only_and_result_is_queried(self):
  105. capture = self.root / "argv.jsonl"
  106. script = '''import json,sys,os
  107. with open(os.environ["STL_TEST_CAPTURE"],"a") as f:
  108. f.write(json.dumps({"argv":sys.argv[1:],"password_present":bool(os.environ.get("IPMI_PASSWORD"))})+"\\n")
  109. print("Chassis Power is off" if sys.argv[-1]=="status" else "Down/Off")
  110. '''
  111. device = HardwareDevice({"bmc": {"host": "example.invalid", "user": "test", "password_env": "STL_TEST_PASSWORD",
  112. "ipmitool_argv": [sys.executable, "-c", script]}})
  113. try:
  114. with patch.dict(os.environ, {"STL_TEST_PASSWORD": "a-test-secret", "STL_TEST_CAPTURE": str(capture)}):
  115. self.assertEqual(await device.bmc_power("off"), "off")
  116. records = [json.loads(line) for line in capture.read_text().splitlines()]
  117. self.assertEqual(len(records), 2)
  118. self.assertEqual(records[-1]["argv"][-3:], ["chassis", "power", "status"])
  119. self.assertTrue(records[0]["password_present"])
  120. self.assertNotIn("a-test-secret", capture.read_text())
  121. finally:
  122. await device.close()
  123. async def test_bmc_query_keeps_partial_session_output_and_redacts_diagnostics(self):
  124. script = '''import os,sys
  125. secret=os.environ["IPMI_PASSWORD"]
  126. if sys.argv[-3:] == ["session","info","all"]:
  127. print("session handle : 1\\nactive sessions : 1\\nip : 192.0.2.10")
  128. elif sys.argv[-2:] == ["sol","info"]:
  129. print("authentication failed: "+secret,file=sys.stderr)
  130. elif sys.argv[-3:] == ["fru","print","0"]:
  131. print(secret+"温"*30000)
  132. else:
  133. print("partial device row: "+secret)
  134. print("diagnostic: "+secret,file=sys.stderr)
  135. sys.exit(1)
  136. '''
  137. device = HardwareDevice({"bmc": {"host": "example.invalid", "user": "test", "password_env": "STL_TEST_PASSWORD",
  138. "ipmitool_argv": [sys.executable, "-c", script]}})
  139. try:
  140. with patch.dict(os.environ, {"STL_TEST_PASSWORD": "partial-query-secret"}):
  141. sessions = await device.bmc_query("sessions")
  142. self.assertTrue(sessions.startswith("[工具退出码 1,以下可能是部分结果]"))
  143. self.assertIn("session handle : 1", sessions)
  144. self.assertIn("active sessions : 1", sessions)
  145. self.assertNotIn("[stderr]", sessions)
  146. partial = await device.bmc_query("info")
  147. self.assertIn("partial device row: [REDACTED]", partial)
  148. self.assertIn("[stderr]\ndiagnostic: [REDACTED]", partial)
  149. self.assertNotIn("partial-query-secret", partial)
  150. large = await device.bmc_query("fru")
  151. self.assertLessEqual(len(large.encode("utf-8")), 65536)
  152. self.assertTrue(large.endswith("[输出超过 64 KiB,已截断]"))
  153. self.assertNotIn("partial-query-secret", large)
  154. with self.assertRaises(DeviceError) as caught:
  155. await device.bmc_query("sol")
  156. self.assertIn("authentication failed: [REDACTED]", str(caught.exception))
  157. self.assertNotIn("partial-query-secret", str(caught.exception))
  158. finally:
  159. await device.close()
  160. async def test_bmc_nonzero_power_readback_and_telemetry_stay_errors(self):
  161. script = '''import os,sys
  162. print("Chassis Power is on")
  163. print("not completed: "+os.environ["IPMI_PASSWORD"]+" "+"x"*2000,file=sys.stderr)
  164. sys.exit(1)
  165. '''
  166. device = HardwareDevice({"bmc": {"host": "example.invalid", "user": "test", "password_env": "STL_TEST_PASSWORD",
  167. "ipmitool_argv": [sys.executable, "-c", script]}})
  168. try:
  169. with patch.dict(os.environ, {"STL_TEST_PASSWORD": "strict-power-secret"}):
  170. for operation in (lambda: device.bmc_power("on"), device.bmc_read, device.read_bmc_dimms):
  171. with self.assertRaises(DeviceError) as caught:
  172. await operation()
  173. error = str(caught.exception)
  174. self.assertIn("退出码 1", error)
  175. self.assertIn("not completed: [REDACTED]", error)
  176. self.assertNotIn("strict-power-secret", error)
  177. self.assertLess(len(error), 600)
  178. finally:
  179. await device.close()
  180. async def test_native_helper_contract_raw_stream_and_ready(self):
  181. script = '''import os,sys,json
  182. print(json.dumps({"event":"ready"}),file=sys.stderr,flush=True)
  183. while True:
  184. data=os.read(0,8192)
  185. if not data: break
  186. os.write(1,data)
  187. '''
  188. device = HardwareDevice({"bmc": {"host": "example.invalid", "user": "test", "password_env": "STL_TEST_PASSWORD",
  189. "sol_helper_argv": [sys.executable, "-u", "-c", script]}})
  190. try:
  191. with patch.dict(os.environ, {"STL_TEST_PASSWORD": "local-test-only"}):
  192. await device.sol_start()
  193. await device.sol_write(b"hello\r")
  194. reader = device.sol_read()
  195. self.assertEqual(await asyncio.wait_for(anext(reader), 1), b"hello\r")
  196. await reader.aclose()
  197. finally:
  198. await device.close()
  199. async def test_simulator_bios_and_mt_sequence_and_temperature_phase(self):
  200. device = SimulatedDevice({"simulation": {"step_delay_s": 0.01, "mt_duration_s": 0.04}})
  201. seen = bytearray()
  202. async def consume():
  203. async for chunk in device.sol_read():
  204. seen.extend(chunk)
  205. async def wait_for(token):
  206. async with asyncio.timeout(2):
  207. while token not in seen:
  208. await asyncio.sleep(0.005)
  209. await device.configure_run({"run_rmt": True, "run_amt": False}, [{"sn": "SN1", "slot": "A1", "cpu": 0, "channel": "A"}])
  210. await device.supply_set(True)
  211. await device.set_target(80)
  212. self.assertEqual((await device.read_telemetry())["dimms"], [])
  213. await device.sol_start()
  214. task = asyncio.create_task(consume())
  215. try:
  216. await device.bmc_power("on")
  217. await wait_for(b"[0][CxmtDdrTest]Current stage is 1")
  218. await device.sol_write(b"actm tCL 44\r")
  219. await device.sol_write(b"\r")
  220. await wait_for(b"[1][CxmtDdrTest]Current stage is 1")
  221. await device.sol_write(b"\r")
  222. await wait_for(b"Shell>")
  223. self.assertIn(b"STL_SIM RMT_DONE", seen)
  224. self.assertNotIn(b"STL_SIM AMT_START", seen)
  225. telemetry = await device.read_telemetry()
  226. self.assertEqual(telemetry["dimms"][0]["sn"], "SN1")
  227. await device.sol_write(b"memtest.efi RUN-1\r")
  228. await wait_for(b"STL_SIM RESULTS_FLUSHED")
  229. self.assertIn(b"STL_SIM TEST_RESULT PASS", seen)
  230. self.assertEqual(await device.supply_set(False), "off")
  231. await asyncio.wait_for(task, 1)
  232. finally:
  233. await device.close()
  234. if not task.done():
  235. task.cancel()
  236. await asyncio.gather(task, return_exceptions=True)
  237. async def test_simulator_second_boot_restarts_mt_after_host_or_supply_off(self):
  238. for power_path in ("host", "supply"):
  239. with self.subTest(power_path=power_path):
  240. device = SimulatedDevice({"simulation": {"step_delay_s": 0.005, "mt_duration_s": 0.02}})
  241. seen = bytearray()
  242. readers = []
  243. async def consume():
  244. async for chunk in device.sol_read():
  245. seen.extend(chunk)
  246. async def wait_for(token, offset):
  247. async with asyncio.timeout(2):
  248. while token not in seen[offset:]:
  249. await asyncio.sleep(0.005)
  250. async def boot_and_test():
  251. offset = len(seen)
  252. self.assertEqual(await device.bmc_power("on"), "on")
  253. await wait_for(b"[0][CxmtDdrTest]Current stage is 1", offset)
  254. self.assertEqual((await device.read_telemetry())["dimms"], [])
  255. await device.sol_write(b"\r")
  256. await wait_for(b"[1][CxmtDdrTest]Current stage is 1", offset)
  257. # Repeating ON while already on must not reset CPU1 to CPU0.
  258. self.assertEqual(await device.bmc_power("on"), "on")
  259. await device.sol_write(b"\r")
  260. await wait_for(b"Shell>", offset)
  261. self.assertEqual((await device.read_telemetry())["dimms"][0]["sn"], "BOOT-SN")
  262. await device.sol_write(b"memtest.efi\r")
  263. await wait_for(b"STL_SIM RESULTS_FLUSHED", offset)
  264. output = bytes(seen[offset:])
  265. self.assertEqual(output.count(b"STL_SIM TEST_START MT"), 1)
  266. self.assertEqual(output.count(b"[0][CxmtDdrTest]Current stage is 1"), 1)
  267. self.assertIn(b"STL_SIM TEST_RESULT PASS", output)
  268. self.assertNotIn(b"unfinished-input", output)
  269. try:
  270. # Configure once: the second boot is standalone diagnostics,
  271. # with no configure_run call to hide stale firmware state.
  272. await device.configure_run({"run_rmt": True, "run_amt": True},
  273. [{"sn": "BOOT-SN", "slot": "A1", "cpu": 0, "channel": "A"}])
  274. await device.supply_set(True)
  275. await device.sol_start()
  276. readers.append(asyncio.create_task(consume()))
  277. await boot_and_test()
  278. await device.sol_write(b"unfinished-input")
  279. if power_path == "supply":
  280. await device.supply_set(False)
  281. await asyncio.wait_for(readers[-1], 1)
  282. await device.supply_set(True)
  283. await device.sol_start()
  284. readers.append(asyncio.create_task(consume()))
  285. else:
  286. await device.bmc_power("off")
  287. await boot_and_test()
  288. self.assertEqual(seen.count(b"STL_SIM TEST_START MT"), 2)
  289. finally:
  290. await device.close()
  291. await asyncio.wait_for(asyncio.gather(*readers), 1)
  292. async def test_native_helper_failure_drains_bytes_then_raises(self):
  293. script = '''import os,sys,json,time
  294. print(json.dumps({"event":"ready"}),file=sys.stderr,flush=True)
  295. os.read(0,1)
  296. os.write(1,b"last evidence before disconnect\\r\\n")
  297. print(json.dumps({"event":"error","code":24}),file=sys.stderr,flush=True)
  298. time.sleep(30)
  299. '''
  300. device = HardwareDevice({"bmc": {"host": "example.invalid", "user": "test", "password_env": "STL_TEST_PASSWORD",
  301. "sol_helper_argv": [sys.executable, "-u", "-c", script]}})
  302. try:
  303. with patch.dict(os.environ, {"STL_TEST_PASSWORD": "local-test-only"}):
  304. await device.sol_start()
  305. reader = device.sol_read()
  306. await device.sol_write(b"x")
  307. self.assertEqual(await asyncio.wait_for(anext(reader), 1), b"last evidence before disconnect\r\n")
  308. with self.assertRaises(DeviceError):
  309. await asyncio.wait_for(anext(reader), 1)
  310. finally:
  311. await device.close()
  312. if __name__ == "__main__":
  313. unittest.main()