| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342 |
- """Device boundary tests use subprocess stubs only; no BMC/network is contacted."""
- import asyncio
- import json
- import os
- from pathlib import Path
- import sys
- import tempfile
- import unittest
- from unittest.mock import patch
- from stl_backend.devices import DeviceError, HardwareDevice, JsonLineBridge, ManualActionRequired, SimulatedDevice
- BRIDGE = r'''
- import json,sys,time
- state="off"
- for line in sys.stdin:
- r=json.loads(line); op=r["operation"]
- if op=="wait": time.sleep(5)
- if op=="bad": print(json.dumps({"id":"wrong","ok":True,"result":{}}),flush=True); continue
- if op=="supply_set": state="unknown"; result={"accepted":True}
- elif op=="supply_read": result={"state":state}
- elif op=="set_target": result={"confirmed_target_c":r["arguments"]["target_c"]}
- elif op=="read_telemetry": result={"air_c":70.5,"dimms":[],"quality":"valid","board_state":"running"}
- else: result={"echo":op}
- print(json.dumps({"id":r["id"],"ok":True,"result":result}),flush=True)
- '''
- class DeviceTests(unittest.IsolatedAsyncioTestCase):
- async def asyncSetUp(self):
- self.tmp = tempfile.TemporaryDirectory()
- self.root = Path(self.tmp.name)
- self.bridge_config = {"argv": [sys.executable, "-u", "-c", BRIDGE], "timeout_s": 1}
- async def asyncTearDown(self):
- self.tmp.cleanup()
- async def test_bridge_id_mismatch_resets_process(self):
- bridge = JsonLineBridge(self.bridge_config)
- try:
- with self.assertRaisesRegex(DeviceError, "ID"):
- await bridge.call("bad")
- self.assertIsNone(bridge._proc)
- self.assertEqual(await bridge.call("hello"), {"echo": "hello"})
- finally:
- await bridge.close()
- async def test_bridge_timeout_kills_process_and_next_request_is_fresh(self):
- bridge = JsonLineBridge({**self.bridge_config, "timeout_s": 2})
- try:
- # Exercise an in-flight request timeout, not interpreter startup speed.
- self.assertEqual(await bridge.call("hello"), {"echo": "hello"})
- bridge.timeout = 0.1
- with self.assertRaisesRegex(DeviceError, "超时"):
- await bridge.call("wait")
- self.assertIsNone(bridge._proc)
- bridge.timeout = 2
- self.assertEqual(await bridge.call("hello"), {"echo": "hello"})
- finally:
- await bridge.close()
- async def test_bridge_cancel_does_not_leave_old_response(self):
- bridge = JsonLineBridge(self.bridge_config)
- task = asyncio.create_task(bridge.call("wait"))
- try:
- await asyncio.sleep(0.05)
- task.cancel()
- with self.assertRaises(asyncio.CancelledError):
- await task
- self.assertIsNone(bridge._proc)
- self.assertEqual(await bridge.call("hello"), {"echo": "hello"})
- finally:
- await bridge.close()
- async def test_bridge_serializes_concurrent_requests(self):
- bridge = JsonLineBridge(self.bridge_config)
- try:
- results = await asyncio.gather(*(bridge.call(str(i)) for i in range(10)))
- self.assertEqual(results, [{"echo": str(i)} for i in range(10)])
- finally:
- await bridge.close()
- async def test_supply_ack_is_not_off_confirmation(self):
- device = HardwareDevice({"bridge": self.bridge_config, "supply_mode": "bridge"})
- try:
- self.assertEqual(await device.supply_set(False), "unknown")
- self.assertEqual(await device.set_target(80.5), 80.5)
- data = await device.read_telemetry()
- self.assertEqual(data["air_c"], 70.5)
- self.assertEqual(data["dimms"], [])
- finally:
- await device.close()
- async def test_manual_supply_requires_explicit_confirmation(self):
- device = HardwareDevice({"supply_mode": "manual"})
- self.assertEqual(await device.supply_read(), "unknown")
- with self.assertRaises(ManualActionRequired) as caught:
- await device.supply_set(True)
- self.assertTrue(caught.exception.on)
- await device.confirm_supply(True)
- self.assertEqual(await device.supply_set(True), "on")
- with self.assertRaises(ManualActionRequired):
- await device.supply_set(False)
- await device.confirm_supply(False)
- self.assertEqual(await device.supply_read(), "off")
- await device.close()
- async def test_invalid_telemetry_finite_values_required(self):
- script = BRIDGE.replace('"air_c":70.5', '"air_c":float("nan")')
- device = HardwareDevice({"bridge": {"argv": [sys.executable, "-u", "-c", script]}})
- try:
- with self.assertRaisesRegex(DeviceError, "有限数值"):
- await device.read_telemetry()
- finally:
- await device.close()
- async def test_bmc_password_is_environment_only_and_result_is_queried(self):
- capture = self.root / "argv.jsonl"
- script = '''import json,sys,os
- with open(os.environ["STL_TEST_CAPTURE"],"a") as f:
- f.write(json.dumps({"argv":sys.argv[1:],"password_present":bool(os.environ.get("IPMI_PASSWORD"))})+"\\n")
- print("Chassis Power is off" if sys.argv[-1]=="status" else "Down/Off")
- '''
- device = HardwareDevice({"bmc": {"host": "example.invalid", "user": "test", "password_env": "STL_TEST_PASSWORD",
- "ipmitool_argv": [sys.executable, "-c", script]}})
- try:
- with patch.dict(os.environ, {"STL_TEST_PASSWORD": "a-test-secret", "STL_TEST_CAPTURE": str(capture)}):
- self.assertEqual(await device.bmc_power("off"), "off")
- records = [json.loads(line) for line in capture.read_text().splitlines()]
- self.assertEqual(len(records), 2)
- self.assertEqual(records[-1]["argv"][-3:], ["chassis", "power", "status"])
- self.assertTrue(records[0]["password_present"])
- self.assertNotIn("a-test-secret", capture.read_text())
- finally:
- await device.close()
- async def test_bmc_query_keeps_partial_session_output_and_redacts_diagnostics(self):
- script = '''import os,sys
- secret=os.environ["IPMI_PASSWORD"]
- if sys.argv[-3:] == ["session","info","all"]:
- print("session handle : 1\\nactive sessions : 1\\nip : 192.0.2.10")
- elif sys.argv[-2:] == ["sol","info"]:
- print("authentication failed: "+secret,file=sys.stderr)
- elif sys.argv[-3:] == ["fru","print","0"]:
- print(secret+"温"*30000)
- else:
- print("partial device row: "+secret)
- print("diagnostic: "+secret,file=sys.stderr)
- sys.exit(1)
- '''
- device = HardwareDevice({"bmc": {"host": "example.invalid", "user": "test", "password_env": "STL_TEST_PASSWORD",
- "ipmitool_argv": [sys.executable, "-c", script]}})
- try:
- with patch.dict(os.environ, {"STL_TEST_PASSWORD": "partial-query-secret"}):
- sessions = await device.bmc_query("sessions")
- self.assertTrue(sessions.startswith("[工具退出码 1,以下可能是部分结果]"))
- self.assertIn("session handle : 1", sessions)
- self.assertIn("active sessions : 1", sessions)
- self.assertNotIn("[stderr]", sessions)
- partial = await device.bmc_query("info")
- self.assertIn("partial device row: [REDACTED]", partial)
- self.assertIn("[stderr]\ndiagnostic: [REDACTED]", partial)
- self.assertNotIn("partial-query-secret", partial)
- large = await device.bmc_query("fru")
- self.assertLessEqual(len(large.encode("utf-8")), 65536)
- self.assertTrue(large.endswith("[输出超过 64 KiB,已截断]"))
- self.assertNotIn("partial-query-secret", large)
- with self.assertRaises(DeviceError) as caught:
- await device.bmc_query("sol")
- self.assertIn("authentication failed: [REDACTED]", str(caught.exception))
- self.assertNotIn("partial-query-secret", str(caught.exception))
- finally:
- await device.close()
- async def test_bmc_nonzero_power_readback_and_telemetry_stay_errors(self):
- script = '''import os,sys
- print("Chassis Power is on")
- print("not completed: "+os.environ["IPMI_PASSWORD"]+" "+"x"*2000,file=sys.stderr)
- sys.exit(1)
- '''
- device = HardwareDevice({"bmc": {"host": "example.invalid", "user": "test", "password_env": "STL_TEST_PASSWORD",
- "ipmitool_argv": [sys.executable, "-c", script]}})
- try:
- with patch.dict(os.environ, {"STL_TEST_PASSWORD": "strict-power-secret"}):
- for operation in (lambda: device.bmc_power("on"), device.bmc_read, device.read_bmc_dimms):
- with self.assertRaises(DeviceError) as caught:
- await operation()
- error = str(caught.exception)
- self.assertIn("退出码 1", error)
- self.assertIn("not completed: [REDACTED]", error)
- self.assertNotIn("strict-power-secret", error)
- self.assertLess(len(error), 600)
- finally:
- await device.close()
- async def test_native_helper_contract_raw_stream_and_ready(self):
- script = '''import os,sys,json
- print(json.dumps({"event":"ready"}),file=sys.stderr,flush=True)
- while True:
- data=os.read(0,8192)
- if not data: break
- os.write(1,data)
- '''
- device = HardwareDevice({"bmc": {"host": "example.invalid", "user": "test", "password_env": "STL_TEST_PASSWORD",
- "sol_helper_argv": [sys.executable, "-u", "-c", script]}})
- try:
- with patch.dict(os.environ, {"STL_TEST_PASSWORD": "local-test-only"}):
- await device.sol_start()
- await device.sol_write(b"hello\r")
- reader = device.sol_read()
- self.assertEqual(await asyncio.wait_for(anext(reader), 1), b"hello\r")
- await reader.aclose()
- finally:
- await device.close()
- async def test_simulator_bios_and_mt_sequence_and_temperature_phase(self):
- device = SimulatedDevice({"simulation": {"step_delay_s": 0.01, "mt_duration_s": 0.04}})
- seen = bytearray()
- async def consume():
- async for chunk in device.sol_read():
- seen.extend(chunk)
- async def wait_for(token):
- async with asyncio.timeout(2):
- while token not in seen:
- await asyncio.sleep(0.005)
- await device.configure_run({"run_rmt": True, "run_amt": False}, [{"sn": "SN1", "slot": "A1", "cpu": 0, "channel": "A"}])
- await device.supply_set(True)
- await device.set_target(80)
- self.assertEqual((await device.read_telemetry())["dimms"], [])
- await device.sol_start()
- task = asyncio.create_task(consume())
- try:
- await device.bmc_power("on")
- await wait_for(b"[0][CxmtDdrTest]Current stage is 1")
- await device.sol_write(b"actm tCL 44\r")
- await device.sol_write(b"\r")
- await wait_for(b"[1][CxmtDdrTest]Current stage is 1")
- await device.sol_write(b"\r")
- await wait_for(b"Shell>")
- self.assertIn(b"STL_SIM RMT_DONE", seen)
- self.assertNotIn(b"STL_SIM AMT_START", seen)
- telemetry = await device.read_telemetry()
- self.assertEqual(telemetry["dimms"][0]["sn"], "SN1")
- await device.sol_write(b"memtest.efi RUN-1\r")
- await wait_for(b"STL_SIM RESULTS_FLUSHED")
- self.assertIn(b"STL_SIM TEST_RESULT PASS", seen)
- self.assertEqual(await device.supply_set(False), "off")
- await asyncio.wait_for(task, 1)
- finally:
- await device.close()
- if not task.done():
- task.cancel()
- await asyncio.gather(task, return_exceptions=True)
- async def test_simulator_second_boot_restarts_mt_after_host_or_supply_off(self):
- for power_path in ("host", "supply"):
- with self.subTest(power_path=power_path):
- device = SimulatedDevice({"simulation": {"step_delay_s": 0.005, "mt_duration_s": 0.02}})
- seen = bytearray()
- readers = []
- async def consume():
- async for chunk in device.sol_read():
- seen.extend(chunk)
- async def wait_for(token, offset):
- async with asyncio.timeout(2):
- while token not in seen[offset:]:
- await asyncio.sleep(0.005)
- async def boot_and_test():
- offset = len(seen)
- self.assertEqual(await device.bmc_power("on"), "on")
- await wait_for(b"[0][CxmtDdrTest]Current stage is 1", offset)
- self.assertEqual((await device.read_telemetry())["dimms"], [])
- await device.sol_write(b"\r")
- await wait_for(b"[1][CxmtDdrTest]Current stage is 1", offset)
- # Repeating ON while already on must not reset CPU1 to CPU0.
- self.assertEqual(await device.bmc_power("on"), "on")
- await device.sol_write(b"\r")
- await wait_for(b"Shell>", offset)
- self.assertEqual((await device.read_telemetry())["dimms"][0]["sn"], "BOOT-SN")
- await device.sol_write(b"memtest.efi\r")
- await wait_for(b"STL_SIM RESULTS_FLUSHED", offset)
- output = bytes(seen[offset:])
- self.assertEqual(output.count(b"STL_SIM TEST_START MT"), 1)
- self.assertEqual(output.count(b"[0][CxmtDdrTest]Current stage is 1"), 1)
- self.assertIn(b"STL_SIM TEST_RESULT PASS", output)
- self.assertNotIn(b"unfinished-input", output)
- try:
- # Configure once: the second boot is standalone diagnostics,
- # with no configure_run call to hide stale firmware state.
- await device.configure_run({"run_rmt": True, "run_amt": True},
- [{"sn": "BOOT-SN", "slot": "A1", "cpu": 0, "channel": "A"}])
- await device.supply_set(True)
- await device.sol_start()
- readers.append(asyncio.create_task(consume()))
- await boot_and_test()
- await device.sol_write(b"unfinished-input")
- if power_path == "supply":
- await device.supply_set(False)
- await asyncio.wait_for(readers[-1], 1)
- await device.supply_set(True)
- await device.sol_start()
- readers.append(asyncio.create_task(consume()))
- else:
- await device.bmc_power("off")
- await boot_and_test()
- self.assertEqual(seen.count(b"STL_SIM TEST_START MT"), 2)
- finally:
- await device.close()
- await asyncio.wait_for(asyncio.gather(*readers), 1)
- async def test_native_helper_failure_drains_bytes_then_raises(self):
- script = '''import os,sys,json,time
- print(json.dumps({"event":"ready"}),file=sys.stderr,flush=True)
- os.read(0,1)
- os.write(1,b"last evidence before disconnect\\r\\n")
- print(json.dumps({"event":"error","code":24}),file=sys.stderr,flush=True)
- time.sleep(30)
- '''
- device = HardwareDevice({"bmc": {"host": "example.invalid", "user": "test", "password_env": "STL_TEST_PASSWORD",
- "sol_helper_argv": [sys.executable, "-u", "-c", script]}})
- try:
- with patch.dict(os.environ, {"STL_TEST_PASSWORD": "local-test-only"}):
- await device.sol_start()
- reader = device.sol_read()
- await device.sol_write(b"x")
- self.assertEqual(await asyncio.wait_for(anext(reader), 1), b"last evidence before disconnect\r\n")
- with self.assertRaises(DeviceError):
- await asyncio.wait_for(anext(reader), 1)
- finally:
- await device.close()
- if __name__ == "__main__":
- unittest.main()
|