test_prod2u_p4_send_hex_template.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. #!/usr/bin/env python3
  2. """Offline contract tests for the packaged ACK-only SEND_HEX utility."""
  3. from __future__ import annotations
  4. import json
  5. import subprocess
  6. import sys
  7. import tempfile
  8. import unittest
  9. from pathlib import Path
  10. ROOT = Path(__file__).resolve().parents[2]
  11. TOOLS = ROOT / "tools"
  12. SEND_HEX = TOOLS / "package_templates" / "SEND_HEX.ps1"
  13. INITIALIZE_DISABLE = TOOLS / "package_templates" / "INITIALIZE_DISABLE.ps1"
  14. RUNTIME_MARKER = "# SEND_HEX_RUNTIME_START"
  15. sys.path.insert(0, str(TOOLS))
  16. import prod2u_p4_protocol as protocol # noqa: E402
  17. def _with_recomputed_crc(frame: bytes, *, offset: int, value: int) -> bytes:
  18. changed = bytearray(frame)
  19. changed[offset] = value
  20. changed[-2:] = protocol.crc16_ccitt(changed[2:-2]).to_bytes(2, "little")
  21. return bytes(changed)
  22. def _invoke_parser(request: bytes, response: bytes) -> subprocess.CompletedProcess[str]:
  23. source = SEND_HEX.read_text(encoding="utf-8", errors="strict")
  24. if RUNTIME_MARKER not in source:
  25. raise AssertionError(f"{SEND_HEX} must expose pure parser functions before {RUNTIME_MARKER}")
  26. definitions = source.split(RUNTIME_MARKER, 1)[0]
  27. response_expression = (
  28. f"Convert-HexToBytes '{response.hex()}'" if response else "[byte[]]::new(0)"
  29. )
  30. invocation = f"""
  31. $requestBytes = Convert-HexToBytes '{request.hex()}'
  32. $responseBytes = {response_expression}
  33. try {{
  34. $result = Assert-ResponseContract -Request $requestBytes -ResponseBytes $responseBytes
  35. $result | ConvertTo-Json -Depth 8 -Compress
  36. exit 0
  37. }} catch {{
  38. [Console]::Error.WriteLine($_.Exception.Message)
  39. exit 7
  40. }}
  41. """
  42. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  43. probe = Path(temporary) / "send-hex-parser-probe.ps1"
  44. probe.write_text(definitions + invocation, encoding="utf-8")
  45. return subprocess.run(
  46. [
  47. "powershell.exe",
  48. "-NoProfile",
  49. "-ExecutionPolicy",
  50. "Bypass",
  51. "-File",
  52. str(probe),
  53. "-Hex",
  54. request.hex(),
  55. ],
  56. cwd=ROOT,
  57. capture_output=True,
  58. text=True,
  59. timeout=10,
  60. check=False,
  61. )
  62. def _ordinary_request() -> bytes:
  63. return protocol.build_host_command(command=protocol.CommandId.GET_STATUS)
  64. def _ordinary_ack(
  65. *,
  66. ok: bool = True,
  67. command: int = int(protocol.CommandId.GET_STATUS),
  68. status: protocol.StatusCode = protocol.StatusCode.OK,
  69. ) -> bytes:
  70. return protocol.build_host_ack(ok=ok, command=command, status=status)
  71. def _motor_status_pair() -> tuple[bytes, bytes, bytes]:
  72. request = protocol.build_get_motor_status()
  73. ack = protocol.build_host_ack(
  74. ok=True,
  75. command=protocol.MotionOpcode.GET_MOTOR_STATUS,
  76. status=protocol.StatusCode.OK,
  77. response_type=protocol.FrameType.MOTION_STATUS,
  78. result_flags=0x08,
  79. )
  80. status = protocol.build_motion_status(
  81. flags=0,
  82. position_valid_mask=0,
  83. busy_mask=0,
  84. current_xyz=(0xFF, 0xFF, 0xFF),
  85. target_xyz=(0xFF, 0xFF, 0xFF),
  86. fault_mask=0,
  87. )
  88. return request, ack, status
  89. class Prod2UP4SendHexTemplateTests(unittest.TestCase):
  90. def assertRejected(self, request: bytes, response: bytes, pattern: str) -> None:
  91. completed = _invoke_parser(request, response)
  92. output = completed.stdout + completed.stderr
  93. self.assertNotEqual(completed.returncode, 0, output)
  94. self.assertRegex(output, pattern)
  95. def test_valid_ordinary_ack_is_parsed_as_the_only_response(self) -> None:
  96. completed = _invoke_parser(_ordinary_request(), _ordinary_ack())
  97. self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
  98. result = json.loads(completed.stdout)
  99. self.assertEqual(result["status"], "pass")
  100. self.assertEqual(result["request_opcode"], "0x24")
  101. self.assertEqual(result["ack"]["command"], "0x24")
  102. self.assertTrue(result["ack"]["ok"])
  103. self.assertEqual(result["ack"]["status"], "OK")
  104. self.assertEqual([frame["type"] for frame in result["frames"]], ["0x06"])
  105. def test_partial_is_an_accepted_ack_status(self) -> None:
  106. request = protocol.build_output_snapshot(
  107. ptc_percent=(0,) * 24,
  108. fan_percent=(30,) * 4,
  109. solenoid=0,
  110. xyz=(0, 0, 0),
  111. )
  112. response = protocol.build_host_ack(
  113. ok=True,
  114. command=protocol.CommandId.SET_OUTPUT_SNAPSHOT,
  115. status=protocol.StatusCode.PARTIAL,
  116. detail=0x41,
  117. result_flags=0x0D,
  118. )
  119. completed = _invoke_parser(request, response)
  120. self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
  121. result = json.loads(completed.stdout)
  122. self.assertEqual(result["ack"]["status"], "PARTIAL")
  123. self.assertEqual(result["ack"]["detail"], "0x41")
  124. def test_error_ack_returns_nonzero_for_initialize_disable_propagation(self) -> None:
  125. response = _ordinary_ack(ok=False, status=protocol.StatusCode.BUSY)
  126. self.assertRejected(_ordinary_request(), response, r"(?i)device rejected.*BUSY")
  127. initialize = INITIALIZE_DISABLE.read_text(encoding="utf-8", errors="strict")
  128. self.assertIn("SEND_HEX.ps1", initialize)
  129. self.assertRegex(initialize, r"(?i)exit\s+\$LASTEXITCODE")
  130. def test_ack_ok_and_status_must_agree(self) -> None:
  131. for ok, status in (
  132. (True, protocol.StatusCode.BUSY),
  133. (False, protocol.StatusCode.OK),
  134. (False, protocol.StatusCode.PARTIAL),
  135. ):
  136. with self.subTest(ok=ok, status=status):
  137. self.assertRejected(
  138. _ordinary_request(),
  139. _ordinary_ack(ok=ok, status=status),
  140. r"(?i)ACK ok/status mismatch",
  141. )
  142. def test_ack_command_must_match_request_opcode(self) -> None:
  143. response = _ordinary_ack(command=int(protocol.CommandId.DISABLE))
  144. self.assertRejected(_ordinary_request(), response, r"(?i)ACK command mismatch")
  145. def test_host_ack_payload_must_be_exactly_eight_bytes(self) -> None:
  146. request = _ordinary_request()
  147. for payload_length in (7, 9):
  148. with self.subTest(payload_length=payload_length):
  149. response = protocol.encode_frame(
  150. frame_type=protocol.FrameType.HOST_ACK,
  151. seq=0,
  152. timestamp_tick=0,
  153. payload=bytes(payload_length),
  154. )
  155. self.assertRejected(request, response, r"(?i)HOST_ACK payload length")
  156. def test_response_crc_and_zeroed_envelope_fields_are_enforced(self) -> None:
  157. request = _ordinary_request()
  158. ack = _ordinary_ack()
  159. bad_crc = bytearray(ack)
  160. bad_crc[-1] ^= 0x01
  161. cases = (
  162. (bytes(bad_crc), r"(?i)Response CRC mismatch"),
  163. (_with_recomputed_crc(ack, offset=5, value=1), r"(?i)Response envelope mismatch.*seq"),
  164. (_with_recomputed_crc(ack, offset=9, value=1), r"(?i)Response envelope mismatch.*timestamp"),
  165. (_with_recomputed_crc(ack, offset=3, value=5), r"(?i)Response envelope mismatch.*profile"),
  166. )
  167. for response, pattern in cases:
  168. with self.subTest(pattern=pattern):
  169. self.assertRejected(request, response, pattern)
  170. def test_ordinary_response_rejects_missing_extra_and_out_of_order_frames(self) -> None:
  171. request = _ordinary_request()
  172. ack = _ordinary_ack()
  173. _, _, status = _motor_status_pair()
  174. cases = (
  175. (b"", r"(?i)missing HOST_ACK"),
  176. (ack + status, r"(?i)exactly one HOST_ACK"),
  177. (status + ack, r"(?i)first response is not HOST_ACK"),
  178. )
  179. for response, pattern in cases:
  180. with self.subTest(pattern=pattern):
  181. self.assertRejected(request, response, pattern)
  182. def test_get_motor_status_accepts_exact_ack_then_ten_byte_status(self) -> None:
  183. request, ack, status = _motor_status_pair()
  184. completed = _invoke_parser(request, ack + status)
  185. self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
  186. result = json.loads(completed.stdout)
  187. self.assertEqual(result["request_opcode"], "0x37")
  188. self.assertEqual(result["ack"]["response_type"], "0x12")
  189. self.assertEqual(
  190. [frame["type"] for frame in result["frames"]],
  191. ["0x06", "0x12"],
  192. )
  193. self.assertEqual(result["frames"][1]["payload_length"], 10)
  194. def test_get_motor_status_rejects_missing_extra_out_of_order_or_bad_length(self) -> None:
  195. request, ack, status = _motor_status_pair()
  196. short_status = protocol.encode_frame(
  197. frame_type=protocol.FrameType.MOTION_STATUS,
  198. seq=0,
  199. timestamp_tick=0,
  200. payload=bytes(9),
  201. )
  202. cases = (
  203. (ack, r"(?i)exactly HOST_ACK then MOTION_STATUS"),
  204. (status + ack, r"(?i)first response is not HOST_ACK"),
  205. (ack + status + status, r"(?i)exactly HOST_ACK then MOTION_STATUS"),
  206. (ack + short_status, r"(?i)MOTION_STATUS payload length"),
  207. )
  208. for response, pattern in cases:
  209. with self.subTest(pattern=pattern):
  210. self.assertRejected(request, response, pattern)
  211. if __name__ == "__main__":
  212. unittest.main()