| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126 |
- """Protocol and programmer result tests with synthetic I/O only."""
- from collections import deque
- from contextlib import redirect_stdout
- import io
- import json
- from pathlib import Path
- import tempfile
- import time
- import types
- import unittest
- from unittest.mock import patch
- from tools import monitor_10min as monitor
- from tools import remote_flash_cpld as flash
- from tools import run_hardware_regression_r2 as legacy
- from tools._vendor.hth_protocol import FrameType, decode_frame, encode_frame
- class MonitorWire:
- def __init__(self):
- self.writes = []
- self.payload = bytes([17] * 24 + [20, 21, 22, 23, 30, 31, 32, 33] + [255] * 51 + [5, 37, 80])
- self.chunks = deque([encode_frame(FrameType.GET_DATA, self.payload)])
- def __enter__(self):
- return self
- def __exit__(self, *args):
- pass
- def write(self, raw):
- self.writes.append(decode_frame(raw))
- self.chunks.append(encode_frame(FrameType.GET_ACK) + encode_frame(FrameType.GET_DATA, self.payload))
- return len(raw)
- def flush(self):
- pass
- def read(self, size):
- if self.chunks:
- return self.chunks.popleft()
- time.sleep(0.002)
- return b""
- class MonitorTests(unittest.TestCase):
- def test_passive_mode_emits_current_auto_mapping_and_sends_nothing(self):
- wire = MonitorWire()
- output = io.StringIO()
- fake_serial = types.SimpleNamespace(Serial=lambda *args, **kwargs: wire)
- with patch.dict("sys.modules", {"serial": fake_serial}), redirect_stdout(output):
- self.assertEqual(monitor.main(["fixture", "230400", "--seconds", "0.01", "--passive"]), 0)
- data = [json.loads(line) for line in output.getvalue().splitlines()]
- telemetry = next(item for item in data if item["event"] == "GET_DATA")
- self.assertEqual(wire.writes, [])
- self.assertEqual(telemetry["source"], "AUTO")
- self.assertEqual(telemetry["ptc_chambers_1_to_4"], [[17] * 6] * 4)
- self.assertEqual(telemetry["intake_chambers_1_to_4"], [20, 21, 22, 23])
- self.assertEqual(telemetry["exhaust_chambers_1_to_4"], [30, 31, 32, 33])
- self.assertEqual(telemetry["ct_c"], [None] * 27)
- self.assertEqual(telemetry["heater_cloths_percent"],
- {"SSR1_chamber1": 5, "SSR2_chambers2_and3": 37, "SSR4_chamber4": 80})
- def test_polling_only_sends_get_and_distinguishes_automatic_data(self):
- wire = MonitorWire()
- output = io.StringIO()
- fake_serial = types.SimpleNamespace(Serial=lambda *args, **kwargs: wire)
- with patch.dict("sys.modules", {"serial": fake_serial}), redirect_stdout(output):
- self.assertEqual(monitor.main(["fixture", "--seconds", "0.01"]), 0)
- telemetry = [json.loads(line) for line in output.getvalue().splitlines()
- if json.loads(line)["event"] == "GET_DATA"]
- self.assertEqual([item["source"] for item in telemetry], ["AUTO", "QUERY"])
- self.assertEqual([item.frame_type for item in wire.writes], [FrameType.GET_ALL])
- def test_passive_diagnostic_is_decoded_without_transmitting(self):
- wire = MonitorWire()
- diagnostic = bytes([1, 0x64, 3, 0, 0, 0x23, 0x82, 1, 0x4C, 7, 2,
- 0x80, 0x0C, 25, 5, 1, 9, 5, 24, 16])
- unknown = bytes([2]) + diagnostic[1:]
- wire.chunks.append(encode_frame(FrameType.DIAGNOSTIC, diagnostic)
- + encode_frame(FrameType.DIAGNOSTIC, unknown))
- output = io.StringIO()
- fake_serial = types.SimpleNamespace(Serial=lambda *args, **kwargs: wire)
- with patch.dict("sys.modules", {"serial": fake_serial}), redirect_stdout(output):
- self.assertEqual(monitor.main(["fixture", "--seconds", "0.01", "--passive"]), 0)
- records = [json.loads(line) for line in output.getvalue().splitlines()]
- records = [item for item in records if item["event"] == "DIAGNOSTIC"]
- self.assertEqual(len(records), 2)
- self.assertEqual(records[0]["error_name"], "REGISTER_NACK")
- self.assertEqual(records[0]["raw_temperature"], 0x0C80)
- self.assertEqual(records[0]["temperature_c"], 25)
- self.assertEqual(records[0]["source"], "AUTO")
- self.assertFalse(records[0]["matched"])
- self.assertFalse(records[1]["supported"])
- self.assertTrue(records[1]["raw_hex"].startswith("02 64"))
- self.assertEqual(wire.writes, [])
- class ProgrammerResultTests(unittest.TestCase):
- def test_a_failed_burn_or_refresh_cannot_return_success(self):
- with tempfile.TemporaryDirectory() as directory:
- bit = Path(directory) / "fixture.bit"
- bit.write_bytes(b"fixture, not a hardware bitstream")
- bit.with_suffix(".bmk").write_bytes(b"fixture mask")
- old_success = 'Chip validation success: EF2L45\nfinish command "download -mode refresh"\n'
- for result in ((1, old_success, "program failed"), (0, old_success, ""),
- (0, 'puts "PROD2U_PROGRAM_REFRESH_OK"\n', "")):
- with self.subTest(result=result), patch.object(flash, "run_tcl", return_value=result), redirect_stdout(io.StringIO()):
- self.assertEqual(flash.cmd_burn(str(bit)), 1)
- with patch.object(flash, "run_tcl", side_effect=[(0, m + "\n", "") for m in ("PROD2U_FLASH_PROGRAMMED_VERIFIED", "PROD2U_FLASH_REFRESHED", "PROD2U_FLASH_BOOT_VERIFIED")]), redirect_stdout(io.StringIO()):
- self.assertEqual(flash.cmd_burn(str(bit)), 0)
- def test_main_returns_subcommand_failure_and_uses_current_uart_default(self):
- with patch("sys.argv", ["programmer", "uart", "--port", "fixture"]), patch.object(flash, "cmd_uart", return_value=1) as listen:
- self.assertEqual(flash.main(), 1)
- listen.assert_called_once_with(921600, 3.0, "fixture")
- def test_historical_r2_cannot_program_an_implicit_old_bit(self):
- with patch.object(legacy, "run_command", side_effect=AssertionError("must not run hardware")), patch("sys.stderr", io.StringIO()):
- with self.assertRaises(SystemExit) as result:
- legacy.main(["--bitstream", "fixture.bit"])
- self.assertEqual(result.exception.code, 2)
- if __name__ == "__main__":
- unittest.main()
|