test_prod2u_p4_ack_only_host_contract.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. #!/usr/bin/env python3
  2. """RED contract tests for the minimal ACK-only Normal-v3 wire path."""
  3. from __future__ import annotations
  4. import importlib.util
  5. import sys
  6. import unittest
  7. from pathlib import Path
  8. ROOT = Path(__file__).resolve().parents[2]
  9. TOOLS = ROOT / "tools"
  10. sys.path.insert(0, str(TOOLS))
  11. import prod2u_p4_normal_v3_model as model_v3 # noqa: E402
  12. import prod2u_p4_protocol as protocol # noqa: E402
  13. GOLDEN_REQUEST_HEX = {
  14. "enable": (
  15. "a55a0204070000000000000000222a00"
  16. "000000000000000000000000000000000000000000000000"
  17. "1e1e1e1e00000000d6df"
  18. ),
  19. "jog_x": "a55a020411000000000000000008350001000100000086c3",
  20. "jog_y": "a55a0204110000000000000000083501000001000000473e",
  21. "mark_x": "a55a0204110000000000000000083600010000000000477d",
  22. "mark_y": "a55a02041100000000000000000836010000000000008680",
  23. "open": (
  24. "a55a0204070000000000000000222a00"
  25. "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a"
  26. "46464646646464642c75"
  27. ),
  28. "close": (
  29. "a55a0204070000000000000000222a00"
  30. "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a"
  31. "4646464600000000684a"
  32. ),
  33. "disable": "a55a02040500000000000000000426000000c4ae",
  34. }
  35. def load_cli():
  36. path = TOOLS / "prod2u_p4_cli.py"
  37. spec = importlib.util.spec_from_file_location(
  38. "test_prod2u_p4_minimal_ack_only_cli",
  39. path,
  40. )
  41. if spec is None or spec.loader is None:
  42. raise AssertionError(f"unable to import {path}")
  43. module = importlib.util.module_from_spec(spec)
  44. sys.modules[spec.name] = module
  45. spec.loader.exec_module(module)
  46. return module
  47. class ScriptedEndpoint:
  48. """Expose scripted response bytes only after the request is written."""
  49. def __init__(self, response: bytes) -> None:
  50. self._response = bytearray(response)
  51. self.writes: list[bytes] = []
  52. def write(self, data: bytes) -> int:
  53. self.writes.append(bytes(data))
  54. return len(data)
  55. def read(self, size: int = 1) -> bytes:
  56. if not self.writes or not self._response:
  57. return b""
  58. take = min(size, len(self._response))
  59. result = bytes(self._response[:take])
  60. del self._response[:take]
  61. return result
  62. def legacy_temperature_request() -> bytes:
  63. return protocol.encode_frame(
  64. frame_type=protocol.FrameType.HOST_CMD,
  65. seq=0,
  66. timestamp_tick=0,
  67. payload=b"\x29\x00\x00\x00",
  68. )
  69. class Prod2UP4MinimalAckOnlyContractTests(unittest.TestCase):
  70. def test_existing_input_request_hex_vectors_remain_byte_exact(self) -> None:
  71. self.assertEqual(
  72. {name: value.hex() for name, value in model_v3.GOLDEN_VECTORS.items()},
  73. GOLDEN_REQUEST_HEX,
  74. )
  75. def test_ordinary_command_accepts_ack_as_first_and_only_response(self) -> None:
  76. cli = load_cli()
  77. request = protocol.build_host_command(command=protocol.CommandId.GET_STATUS)
  78. ack = protocol.build_host_ack(
  79. ok=True,
  80. command=protocol.CommandId.GET_STATUS,
  81. status=protocol.StatusCode.OK,
  82. state_hash16=0xBEEF,
  83. )
  84. endpoint = ScriptedEndpoint(ack)
  85. session = cli.NormalSession(endpoint, timeout_seconds=0.05)
  86. result = session.command(request, expected_command=protocol.CommandId.GET_STATUS)
  87. self.assertEqual(result.raw_response, ack)
  88. self.assertEqual(
  89. [frame.frame_type for frame in result.frames],
  90. [protocol.FrameType.HOST_ACK],
  91. )
  92. self.assertEqual(result.ack.state_hash16, 0xBEEF)
  93. self.assertEqual(endpoint.writes, [request])
  94. self.assertFalse(hasattr(session, "_trace_policy"))
  95. self.assertFalse(hasattr(result, "command_result_trace"))
  96. def test_motor_status_response_is_ack_then_one_ten_byte_status(self) -> None:
  97. cli = load_cli()
  98. request = protocol.build_get_motor_status()
  99. ack = protocol.build_host_ack(
  100. ok=True,
  101. command=protocol.MotionOpcode.GET_MOTOR_STATUS,
  102. status=protocol.StatusCode.OK,
  103. response_type=protocol.FrameType.MOTION_STATUS,
  104. result_flags=0x08,
  105. )
  106. status_wire = protocol.build_motion_status(
  107. flags=0x02,
  108. position_valid_mask=0,
  109. busy_mask=0,
  110. current_xyz=(0xFF, 0xFF, 0xFF),
  111. target_xyz=(0xFF, 0xFF, 0xFF),
  112. fault_mask=0,
  113. )
  114. endpoint = ScriptedEndpoint(ack + status_wire)
  115. session = cli.NormalSession(endpoint, timeout_seconds=0.05)
  116. result = session.motor_status()
  117. frames, remainder = protocol.decode_stream(result.raw_response)
  118. self.assertEqual(remainder, b"")
  119. self.assertEqual(
  120. [frame.frame_type for frame in frames],
  121. [protocol.FrameType.HOST_ACK, protocol.FrameType.MOTION_STATUS],
  122. )
  123. self.assertEqual(len(frames[1].payload), protocol.MOTION_STATUS_PAYLOAD_LEN)
  124. self.assertEqual(result.status.current_xyz, (0xFF, 0xFF, 0xFF))
  125. self.assertEqual(endpoint.writes, [request])
  126. def test_mark_closed_is_unsupported_and_has_no_model_side_effect(self) -> None:
  127. subject = model_v3.NormalV3Model()
  128. before = subject.state_fingerprint()
  129. result = subject.apply_frame(bytes.fromhex(GOLDEN_REQUEST_HEX["mark_x"]))
  130. self.assertFalse(result.accepted)
  131. self.assertEqual(result.command, 0x36)
  132. self.assertEqual(result.status, protocol.StatusCode.UNSUPPORTED_IN_PROFILE)
  133. self.assertEqual(subject.state_fingerprint(), before)
  134. def test_legacy_temperature_request_is_unsupported_and_has_no_side_effect(self) -> None:
  135. subject = model_v3.NormalV3Model()
  136. before = subject.state_fingerprint()
  137. result = subject.apply_frame(legacy_temperature_request())
  138. self.assertFalse(result.accepted)
  139. self.assertEqual(result.command, 0x29)
  140. self.assertEqual(result.status, protocol.StatusCode.UNSUPPORTED_IN_PROFILE)
  141. self.assertEqual(subject.state_fingerprint(), before)
  142. def test_jog_step_field_keeps_zero_invalid_and_65535_valid(self) -> None:
  143. with self.assertRaisesRegex(ValueError, "steps must be from 1 to 65535"):
  144. protocol.build_motor_jog(axis=0, raw_dir=1, speed_code=3, steps=0)
  145. maximum = protocol.build_motor_jog(
  146. axis=1,
  147. raw_dir=1,
  148. speed_code=3,
  149. steps=65535,
  150. )
  151. decoded = protocol.decode_motion_command(protocol.decode_frame(maximum))
  152. self.assertEqual(decoded.steps, 65535)
  153. self.assertEqual(protocol.decode_frame(maximum).payload[4:6], b"\xFF\xFF")
  154. def test_snapshot_ack_has_no_axis_acceptance_or_skip_bits(self) -> None:
  155. wire = protocol.build_host_ack(
  156. ok=True,
  157. command=protocol.CommandId.SET_OUTPUT_SNAPSHOT,
  158. status=protocol.StatusCode.OK,
  159. detail=0,
  160. state_hash16=0xE177,
  161. result_flags=0x01,
  162. )
  163. ack = protocol.decode_host_ack(protocol.decode_frame(wire))
  164. self.assertEqual(ack.detail, 0)
  165. self.assertEqual(ack.state_hash16, 0xE177)
  166. self.assertEqual(ack.result_flags, 0x01)
  167. if __name__ == "__main__":
  168. unittest.main()