test_host_monitor_and_programmer.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. """Protocol and programmer result tests with synthetic I/O only."""
  2. from collections import deque
  3. from contextlib import redirect_stdout
  4. import io
  5. import json
  6. from pathlib import Path
  7. import tempfile
  8. import time
  9. import types
  10. import unittest
  11. from unittest.mock import patch
  12. from tools import monitor_10min as monitor
  13. from tools import remote_flash_cpld as flash
  14. from tools import run_hardware_regression_r2 as legacy
  15. from tools._vendor.hth_protocol import FrameType, decode_frame, encode_frame
  16. class MonitorWire:
  17. def __init__(self):
  18. self.writes = []
  19. self.payload = bytes([17] * 24 + [20, 21, 22, 23, 30, 31, 32, 33] + [255] * 51 + [5, 37, 80])
  20. self.chunks = deque([encode_frame(FrameType.GET_DATA, self.payload)])
  21. def __enter__(self):
  22. return self
  23. def __exit__(self, *args):
  24. pass
  25. def write(self, raw):
  26. self.writes.append(decode_frame(raw))
  27. self.chunks.append(encode_frame(FrameType.GET_ACK) + encode_frame(FrameType.GET_DATA, self.payload))
  28. return len(raw)
  29. def flush(self):
  30. pass
  31. def read(self, size):
  32. if self.chunks:
  33. return self.chunks.popleft()
  34. time.sleep(0.002)
  35. return b""
  36. class MonitorTests(unittest.TestCase):
  37. def test_passive_mode_emits_current_auto_mapping_and_sends_nothing(self):
  38. wire = MonitorWire()
  39. output = io.StringIO()
  40. fake_serial = types.SimpleNamespace(Serial=lambda *args, **kwargs: wire)
  41. with patch.dict("sys.modules", {"serial": fake_serial}), redirect_stdout(output):
  42. self.assertEqual(monitor.main(["fixture", "230400", "--seconds", "0.01", "--passive"]), 0)
  43. data = [json.loads(line) for line in output.getvalue().splitlines()]
  44. telemetry = next(item for item in data if item["event"] == "GET_DATA")
  45. self.assertEqual(wire.writes, [])
  46. self.assertEqual(telemetry["source"], "AUTO")
  47. self.assertEqual(telemetry["ptc_chambers_1_to_4"], [[17] * 6] * 4)
  48. self.assertEqual(telemetry["intake_chambers_1_to_4"], [20, 21, 22, 23])
  49. self.assertEqual(telemetry["exhaust_chambers_1_to_4"], [30, 31, 32, 33])
  50. self.assertEqual(telemetry["ct_c"], [None] * 27)
  51. self.assertEqual(telemetry["heater_cloths_percent"],
  52. {"SSR1_chamber1": 5, "SSR2_chambers2_and3": 37, "SSR4_chamber4": 80})
  53. def test_polling_only_sends_get_and_distinguishes_automatic_data(self):
  54. wire = MonitorWire()
  55. output = io.StringIO()
  56. fake_serial = types.SimpleNamespace(Serial=lambda *args, **kwargs: wire)
  57. with patch.dict("sys.modules", {"serial": fake_serial}), redirect_stdout(output):
  58. self.assertEqual(monitor.main(["fixture", "--seconds", "0.01"]), 0)
  59. telemetry = [json.loads(line) for line in output.getvalue().splitlines()
  60. if json.loads(line)["event"] == "GET_DATA"]
  61. self.assertEqual([item["source"] for item in telemetry], ["AUTO", "QUERY"])
  62. self.assertEqual([item.frame_type for item in wire.writes], [FrameType.GET_ALL])
  63. def test_passive_diagnostic_is_decoded_without_transmitting(self):
  64. wire = MonitorWire()
  65. diagnostic = bytes([1, 0x64, 3, 0, 0, 0x23, 0x82, 1, 0x4C, 7, 2,
  66. 0x80, 0x0C, 25, 5, 1, 9, 5, 24, 16])
  67. unknown = bytes([2]) + diagnostic[1:]
  68. wire.chunks.append(encode_frame(FrameType.DIAGNOSTIC, diagnostic)
  69. + encode_frame(FrameType.DIAGNOSTIC, unknown))
  70. output = io.StringIO()
  71. fake_serial = types.SimpleNamespace(Serial=lambda *args, **kwargs: wire)
  72. with patch.dict("sys.modules", {"serial": fake_serial}), redirect_stdout(output):
  73. self.assertEqual(monitor.main(["fixture", "--seconds", "0.01", "--passive"]), 0)
  74. records = [json.loads(line) for line in output.getvalue().splitlines()]
  75. records = [item for item in records if item["event"] == "DIAGNOSTIC"]
  76. self.assertEqual(len(records), 2)
  77. self.assertEqual(records[0]["error_name"], "REGISTER_NACK")
  78. self.assertEqual(records[0]["raw_temperature"], 0x0C80)
  79. self.assertEqual(records[0]["temperature_c"], 25)
  80. self.assertEqual(records[0]["source"], "AUTO")
  81. self.assertFalse(records[0]["matched"])
  82. self.assertFalse(records[1]["supported"])
  83. self.assertTrue(records[1]["raw_hex"].startswith("02 64"))
  84. self.assertEqual(wire.writes, [])
  85. class ProgrammerResultTests(unittest.TestCase):
  86. def test_a_failed_burn_or_refresh_cannot_return_success(self):
  87. with tempfile.TemporaryDirectory() as directory:
  88. bit = Path(directory) / "fixture.bit"
  89. bit.write_bytes(b"fixture, not a hardware bitstream")
  90. bit.with_suffix(".bmk").write_bytes(b"fixture mask")
  91. old_success = 'Chip validation success: EF2L45\nfinish command "download -mode refresh"\n'
  92. for result in ((1, old_success, "program failed"), (0, old_success, ""),
  93. (0, 'puts "PROD2U_PROGRAM_REFRESH_OK"\n', "")):
  94. with self.subTest(result=result), patch.object(flash, "run_tcl", return_value=result), redirect_stdout(io.StringIO()):
  95. self.assertEqual(flash.cmd_burn(str(bit)), 1)
  96. 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()):
  97. self.assertEqual(flash.cmd_burn(str(bit)), 0)
  98. def test_main_returns_subcommand_failure_and_uses_current_uart_default(self):
  99. with patch("sys.argv", ["programmer", "uart", "--port", "fixture"]), patch.object(flash, "cmd_uart", return_value=1) as listen:
  100. self.assertEqual(flash.main(), 1)
  101. listen.assert_called_once_with(921600, 3.0, "fixture")
  102. def test_historical_r2_cannot_program_an_implicit_old_bit(self):
  103. with patch.object(legacy, "run_command", side_effect=AssertionError("must not run hardware")), patch("sys.stderr", io.StringIO()):
  104. with self.assertRaises(SystemExit) as result:
  105. legacy.main(["--bitstream", "fixture.bit"])
  106. self.assertEqual(result.exception.code, 2)
  107. if __name__ == "__main__":
  108. unittest.main()