| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206 |
- #!/usr/bin/env python3
- """RED contract tests for the minimal ACK-only Normal-v3 wire path."""
- from __future__ import annotations
- import importlib.util
- import sys
- import unittest
- from pathlib import Path
- ROOT = Path(__file__).resolve().parents[2]
- TOOLS = ROOT / "tools"
- sys.path.insert(0, str(TOOLS))
- import prod2u_p4_normal_v3_model as model_v3 # noqa: E402
- import prod2u_p4_protocol as protocol # noqa: E402
- GOLDEN_REQUEST_HEX = {
- "enable": (
- "a55a0204070000000000000000222a00"
- "000000000000000000000000000000000000000000000000"
- "1e1e1e1e00000000d6df"
- ),
- "jog_x": "a55a020411000000000000000008350001000100000086c3",
- "jog_y": "a55a0204110000000000000000083501000001000000473e",
- "mark_x": "a55a0204110000000000000000083600010000000000477d",
- "mark_y": "a55a02041100000000000000000836010000000000008680",
- "open": (
- "a55a0204070000000000000000222a00"
- "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a"
- "46464646646464642c75"
- ),
- "close": (
- "a55a0204070000000000000000222a00"
- "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a"
- "4646464600000000684a"
- ),
- "disable": "a55a02040500000000000000000426000000c4ae",
- }
- def load_cli():
- path = TOOLS / "prod2u_p4_cli.py"
- spec = importlib.util.spec_from_file_location(
- "test_prod2u_p4_minimal_ack_only_cli",
- path,
- )
- if spec is None or spec.loader is None:
- raise AssertionError(f"unable to import {path}")
- module = importlib.util.module_from_spec(spec)
- sys.modules[spec.name] = module
- spec.loader.exec_module(module)
- return module
- class ScriptedEndpoint:
- """Expose scripted response bytes only after the request is written."""
- def __init__(self, response: bytes) -> None:
- self._response = bytearray(response)
- self.writes: list[bytes] = []
- def write(self, data: bytes) -> int:
- self.writes.append(bytes(data))
- return len(data)
- def read(self, size: int = 1) -> bytes:
- if not self.writes or not self._response:
- return b""
- take = min(size, len(self._response))
- result = bytes(self._response[:take])
- del self._response[:take]
- return result
- def legacy_temperature_request() -> bytes:
- return protocol.encode_frame(
- frame_type=protocol.FrameType.HOST_CMD,
- seq=0,
- timestamp_tick=0,
- payload=b"\x29\x00\x00\x00",
- )
- class Prod2UP4MinimalAckOnlyContractTests(unittest.TestCase):
- def test_existing_input_request_hex_vectors_remain_byte_exact(self) -> None:
- self.assertEqual(
- {name: value.hex() for name, value in model_v3.GOLDEN_VECTORS.items()},
- GOLDEN_REQUEST_HEX,
- )
- def test_ordinary_command_accepts_ack_as_first_and_only_response(self) -> None:
- cli = load_cli()
- request = protocol.build_host_command(command=protocol.CommandId.GET_STATUS)
- ack = protocol.build_host_ack(
- ok=True,
- command=protocol.CommandId.GET_STATUS,
- status=protocol.StatusCode.OK,
- state_hash16=0xBEEF,
- )
- endpoint = ScriptedEndpoint(ack)
- session = cli.NormalSession(endpoint, timeout_seconds=0.05)
- result = session.command(request, expected_command=protocol.CommandId.GET_STATUS)
- self.assertEqual(result.raw_response, ack)
- self.assertEqual(
- [frame.frame_type for frame in result.frames],
- [protocol.FrameType.HOST_ACK],
- )
- self.assertEqual(result.ack.state_hash16, 0xBEEF)
- self.assertEqual(endpoint.writes, [request])
- self.assertFalse(hasattr(session, "_trace_policy"))
- self.assertFalse(hasattr(result, "command_result_trace"))
- def test_motor_status_response_is_ack_then_one_ten_byte_status(self) -> None:
- cli = load_cli()
- request = protocol.build_get_motor_status()
- ack = protocol.build_host_ack(
- ok=True,
- command=protocol.MotionOpcode.GET_MOTOR_STATUS,
- status=protocol.StatusCode.OK,
- response_type=protocol.FrameType.MOTION_STATUS,
- result_flags=0x08,
- )
- status_wire = protocol.build_motion_status(
- flags=0x02,
- position_valid_mask=0,
- busy_mask=0,
- current_xyz=(0xFF, 0xFF, 0xFF),
- target_xyz=(0xFF, 0xFF, 0xFF),
- fault_mask=0,
- )
- endpoint = ScriptedEndpoint(ack + status_wire)
- session = cli.NormalSession(endpoint, timeout_seconds=0.05)
- result = session.motor_status()
- frames, remainder = protocol.decode_stream(result.raw_response)
- self.assertEqual(remainder, b"")
- self.assertEqual(
- [frame.frame_type for frame in frames],
- [protocol.FrameType.HOST_ACK, protocol.FrameType.MOTION_STATUS],
- )
- self.assertEqual(len(frames[1].payload), protocol.MOTION_STATUS_PAYLOAD_LEN)
- self.assertEqual(result.status.current_xyz, (0xFF, 0xFF, 0xFF))
- self.assertEqual(endpoint.writes, [request])
- def test_mark_closed_is_unsupported_and_has_no_model_side_effect(self) -> None:
- subject = model_v3.NormalV3Model()
- before = subject.state_fingerprint()
- result = subject.apply_frame(bytes.fromhex(GOLDEN_REQUEST_HEX["mark_x"]))
- self.assertFalse(result.accepted)
- self.assertEqual(result.command, 0x36)
- self.assertEqual(result.status, protocol.StatusCode.UNSUPPORTED_IN_PROFILE)
- self.assertEqual(subject.state_fingerprint(), before)
- def test_legacy_temperature_request_is_unsupported_and_has_no_side_effect(self) -> None:
- subject = model_v3.NormalV3Model()
- before = subject.state_fingerprint()
- result = subject.apply_frame(legacy_temperature_request())
- self.assertFalse(result.accepted)
- self.assertEqual(result.command, 0x29)
- self.assertEqual(result.status, protocol.StatusCode.UNSUPPORTED_IN_PROFILE)
- self.assertEqual(subject.state_fingerprint(), before)
- def test_jog_step_field_keeps_zero_invalid_and_65535_valid(self) -> None:
- with self.assertRaisesRegex(ValueError, "steps must be from 1 to 65535"):
- protocol.build_motor_jog(axis=0, raw_dir=1, speed_code=3, steps=0)
- maximum = protocol.build_motor_jog(
- axis=1,
- raw_dir=1,
- speed_code=3,
- steps=65535,
- )
- decoded = protocol.decode_motion_command(protocol.decode_frame(maximum))
- self.assertEqual(decoded.steps, 65535)
- self.assertEqual(protocol.decode_frame(maximum).payload[4:6], b"\xFF\xFF")
- def test_snapshot_ack_has_no_axis_acceptance_or_skip_bits(self) -> None:
- wire = protocol.build_host_ack(
- ok=True,
- command=protocol.CommandId.SET_OUTPUT_SNAPSHOT,
- status=protocol.StatusCode.OK,
- detail=0,
- state_hash16=0xE177,
- result_flags=0x01,
- )
- ack = protocol.decode_host_ack(protocol.decode_frame(wire))
- self.assertEqual(ack.detail, 0)
- self.assertEqual(ack.state_hash16, 0xE177)
- self.assertEqual(ack.result_flags, 0x01)
- if __name__ == "__main__":
- unittest.main()
|