feat(usb-can): add isolated adapter runtime and confirmed CAN transactions

Package the adapter SDK boundary and runtime lifecycle. Confirm admitted CAN transactions, bound retained data and test failure paths with synthetic hardware.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:09:59 +03:00
parent f32c7b400b
commit 8b210258ca
30 changed files with 3336 additions and 0 deletions
+150
View File
@@ -0,0 +1,150 @@
"""Channel arbitration tests with an inert SDK only."""
import pytest
from test_runtime import Engine, FakeSDK
def setup():
clock = [10.0]
sdk = FakeSDK()
e = Engine(sdk, lambda: clock[0], lambda seconds: clock.__setitem__(0, clock[0] + seconds))
token = e.dispatch("bridge.open", {"channel": 0, "bitrate": 500000, "receive_id": 254})["token"]
return clock, sdk, e, token
def test_owner_excludes_manual_tx_and_expiry_stops_channel():
clock, sdk, e, token = setup()
for action in ("configure", "start", "stop", "clear", "transmit", "transmit.stop"):
with pytest.raises(ValueError):
e.dispatch(action, {"channel": 0})
clock[0] = 11
e.tick()
assert not e.running[0]
assert not e.bridges.claims
assert not any(c[0] == "tx" for c in sdk.calls)
with pytest.raises(ValueError):
e.dispatch("bridge.poll", {"token": token})
def test_confirmed_setter_and_no_replay_after_deadline():
clock, sdk, e, token = setup()
request = {"token": token, "frames": [{"id": 0x84A, "data": "fe000500000000"}],
"deadline": 10.2}
e.dispatch("bridge.send", request)
assert sdk.calls[-1][2]["send_type"] == 2
clock[0] = 10.3
with pytest.raises(ValueError):
e.dispatch("bridge.send", request)
assert len([c for c in sdk.calls if c[0] == "tx"]) == 1
def test_same_channel_distinct_response_addresses_and_last_close():
clock, sdk, e, one = setup()
two = e.dispatch("bridge.open", {"channel": 0, "bitrate": 500000, "receive_id": 253})["token"]
frame = {"id": 0x8FE, "channel": 0, "extended": True, "data": "4a0100"}
e.bridges.receive(frame)
assert e.dispatch("bridge.poll", {"token": one})["frames"] == [frame]
assert e.dispatch("bridge.poll", {"token": two})["frames"] == []
e.dispatch("bridge.close", {"token": one})
assert e.running[0]
e.dispatch("bridge.close", {"token": two})
assert not e.running[0]
def test_occupied_bitrate_conflict_and_receive_overflow_end_session():
clock, sdk, e, token = setup()
with pytest.raises(ValueError):
e.dispatch("bridge.open", {"channel": 0, "bitrate": 250000, "receive_id": 253})
for _ in range(513):
e.bridges.receive({"id": 0x8FE, "channel": 0, "extended": True})
with pytest.raises(ValueError):
e.dispatch("bridge.poll", {"token": token})
assert not e.running[0]
def test_status_does_not_enumerate_usb_during_active_bridge():
clock, sdk, e, token = setup()
def blocking_enumeration():
raise AssertionError("vendor USB enumeration must not block a live CAN lease")
sdk.online = blocking_enumeration
assert e.dispatch("status", {})["channels"][0]["owner"] == "vesc"
assert e.dispatch("bridge.poll", {"token": token}) == {"frames": []}
# Status is neither a lease renewal nor a deferred command replay.
clock[0] = 11
e.tick()
assert not e.bridges.claims and not e.running[0]
assert not any(c[0] == "tx" for c in sdk.calls)
sdk.online = lambda: False
with pytest.raises(OSError, match="USB"):
e.dispatch("status", {})
def test_sysfs_detach_retires_active_bridge_even_without_sdk_online(tmp_path):
from test_runtime import Attachment, FakeLink, Service
attachments = [Attachment("1-2:6", "1-2", "/dev/bus/usb/001/006", "480")]
service = Service(tmp_path, lambda: list(attachments), FakeLink)
service.scan()
device = next(iter(service.devices.values()))
link, session = device.link, device.session
request = {"adapter": device.id, "session": session, "action": "open",
"parameters": {"channel": 0, "bitrate": 500000, "receive_id": 254}}
service.bridge(request)
link.engine.sdk.online = lambda: (_ for _ in ()).throw(AssertionError("blocking USB check"))
service.scan()
assert device.link is link and device.activity is None
attachments.clear()
service.scan()
assert not link.alive and device.session != session and not service.devices
@pytest.mark.parametrize("code", range(256))
def test_only_exact_read_commands_have_arbitration_retry(code):
clock, sdk, e, token = setup()
e.dispatch("bridge.send", {"token": token,
"frames": [{"id": 0x84A, "data": bytes((254, 0, code)).hex()}],
"deadline": 10.2})
assert sdk.calls[-1][2]["send_type"] == (2 if code in (0, 4, 14, 17, 31, 62) else 1)
@pytest.mark.parametrize("frame", [
{"id": 0x84A, "data": "fe000400"}, # extra argument
{"id": 0x84A, "data": "fe003e00"}, # scan with unexpected argument
{"id": 0x8FF, "data": "fe003e"}, # broadcast scan
{"id": 0x84A, "data": "fe00224a3e"}, # forwarded scan
{"id": 0x84A, "data": "fd0004"}, # different reply address
{"id": 0x84A, "data": "fe0104"}, # reply, not request
{"id": 0x84A, "data": "fe00224a04"}, # forwarded command
{"id": 0x8FF, "data": "fe0004"}, # broadcast
{"id": 0x8FE, "data": "fe0004"}, # self
{"id": 0x74A, "data": "fe0004"}, # fragmented packet completion
])
def test_no_retry_for_ambiguous_or_forwarded_payload(frame):
clock, sdk, e, token = setup()
e.dispatch("bridge.send", {"token": token, "frames": [frame], "deadline": 10.2})
assert sdk.calls[-1][2]["send_type"] == 1
def test_read_timeout_closes_claim_without_application_replay():
clock, sdk, e, token = setup()
request = {"token": token, "frames": [{"id": 0x84A, "data": "fe0004"}], "deadline": 10.2}
e.dispatch("bridge.send", request)
e.dispatch("bridge.close", {"token": token})
assert not e.running[0]
with pytest.raises(ValueError):
e.dispatch("bridge.send", request)
assert len([c for c in sdk.calls if c[0] == "tx"]) == 1
def test_bridge_inventory_includes_exact_os_usb_generation(tmp_path):
from test_runtime import Attachment, FakeLink, Service
attached = [Attachment("1-2:6", "1-2", "/dev/bus/usb/001/006", "480")]
service = Service(tmp_path, lambda: list(attached), FakeLink)
service.scan()
first = service.bridge_inventory()["items"][0]
assert first["attachment_id"] == attached[0].id
attached[0] = Attachment("1-2:7", "1-2", "/dev/bus/usb/001/007", "480")
service.scan()
second = service.bridge_inventory()["items"][0]
assert first["id"] == second["id"]
assert first["attachment_id"] != second["attachment_id"]
assert first["session_id"] != second["session_id"]
@@ -0,0 +1,138 @@
"""Configuration packet delivery and ACK fencing with an inert CAN bus."""
import binascii
import copy
import pytest
from test_bridge import setup
from test_limits_transport import send
def configuration_frames(command=13, size=458, target=74, sender=254):
# Synthetic parameter bytes; transport does not interpret the native schema.
payload = bytes((command,)) + bytes((i * 17 + 3) % 256 for i in range(size - 1))
frames = []
# Upstream comm_can_send_buffer: short offsets 0..252, then long from 259.
for start in range(0, min(size, 259), 7):
frames.append({"id": 0x500 | target, "data": (bytes((start,)) + payload[start:start+7]).hex()})
for start in range(259, size, 6):
frames.append({"id": 0x600 | target,
"data": (start.to_bytes(2, "big") + payload[start:start+6]).hex()})
frames.append({"id": 0x700 | target,
"data": (bytes((sender, 0)) + size.to_bytes(2, "big")
+ binascii.crc_hqx(payload, 0).to_bytes(2, "big")).hex()})
return payload, frames
def ack(command=13, target=74, sender=254, **changes):
return {"channel": 0, "id": 0x800 | sender, "extended": True,
"data": bytes((target, 1, command)).hex(), **changes}
@pytest.mark.parametrize("command,size", [(13, 458), (16, 313), (13, 259), (16, 260)])
def test_configuration_survives_arbitration_loss_and_is_submitted_only_once(command, size):
_, sdk, e, token = setup()
payload, frames = configuration_frames(command, size)
received, replies, dropped = bytearray(size), [], []
original = sdk.transmit
def wire(ch, value):
original(ch, value)
data, code = bytes.fromhex(value["data"]), value["id"] >> 8
if code in (5, 6):
width = 1 if code == 5 else 2
offset = int.from_bytes(data[:width], "big")
if offset in (14, 259) and value["send_type"] == 1:
dropped.append(offset)
return
received[offset:offset+len(data)-width] = data[width:]
elif code == 7 and binascii.crc_hqx(received, 0) == int.from_bytes(data[4:], "big"):
replies.append(ack(command))
sdk.transmit = wire
send(e, token, frames)
assert not dropped and bytes(received) == payload and replies == [ack(command)]
assert len([c for c in sdk.calls if c[0] == "tx"]) == len(frames)
assert e.bridges.claims[token]["write_pending"] == {"target": 74, "command": command}
e.bridges.receive(replies[0])
assert e.bridges.claims[token]["write_pending"] is None
@pytest.mark.parametrize("command", [5, 6, 8, 12, 14, 17, 34, 48, 49, 58, 255])
def test_no_arbitration_retry_for_other_long_commands(command):
_, sdk, e, token = setup()
send(e, token, configuration_frames(command)[1])
assert all(c[2]["send_type"] == 1 for c in sdk.calls if c[0] == "tx")
assert e.bridges.claims[token]["write_pending"] is None
@pytest.mark.parametrize("case", ["offset", "missing", "duplicate", "crc", "target", "sender",
"broadcast", "self", "length", "short-chunk", "long-code", "extra-commit"])
def test_incomplete_or_ambiguous_configuration_is_not_promoted(case):
_, sdk, e, token = setup()
frames = copy.deepcopy(configuration_frames()[1])
if case == "offset": frames[37]["data"] = "0104" + frames[37]["data"][4:]
elif case == "missing": frames.pop(37)
elif case == "duplicate": frames[38] = frames[37].copy()
elif case == "crc": frames[-1]["data"] = frames[-1]["data"][:-4] + "0000"
elif case == "target": frames[37]["id"] += 1
elif case == "sender": frames[-1]["data"] = "fd" + frames[-1]["data"][2:]
elif case == "broadcast": frames = configuration_frames(target=255)[1]
elif case == "self": frames = configuration_frames(target=254)[1]
elif case == "length": frames[-1]["data"] = frames[-1]["data"][:4] + "01cb" + frames[-1]["data"][8:]
elif case == "short-chunk": frames[2]["data"] = frames[2]["data"][:-2]
elif case == "long-code": frames[37]["id"] = 0x54A
elif case == "extra-commit": frames.append(frames[-1].copy())
send(e, token, frames)
assert all(c[2]["send_type"] == 1 for c in sdk.calls if c[0] == "tx")
assert e.bridges.claims[token]["write_pending"] is None
@pytest.mark.parametrize("command", [13, 16])
def test_only_configuration_exact_ack_releases_fence(command):
_, _, e, token = setup()
send(e, token, configuration_frames(command)[1])
for wrong in (ack(48), ack(16 if command == 13 else 13), ack(command, target=75),
ack(command, sender=253), ack(command, fd=True), ack(command, rtr=True),
ack(command, error=True), ack(command, channel=1), ack(command, data="4a010d00")):
e.bridges.receive(wrong)
assert e.bridges.claims[token]["write_pending"] == {"target": 74, "command": command}
e.bridges.receive(ack(command))
assert e.bridges.claims[token]["write_pending"] is None
@pytest.mark.parametrize("reason", ["close", "expire", "second-send"])
def test_unconfirmed_config_discards_channel_queue_and_other_claims(reason):
clock, sdk, e, token = setup()
other = e.dispatch("bridge.open", {"channel": 0, "bitrate": 500000, "receive_id": 253})["token"]
frames = configuration_frames()[1]
send(e, token, frames)
if reason == "close": e.dispatch("bridge.close", {"token": token})
elif reason == "expire":
clock[0] = 11
e.tick()
else:
with pytest.raises(ValueError, match="Подтверждение"):
send(e, token, frames)
assert not e.running[0] and not e.bridges.claims
assert sdk.calls[-1] == ("stop", 0)
assert len([c for c in sdk.calls if c[0] == "tx"]) == len(frames)
e.bridges.receive(ack())
for owner in (token, other):
with pytest.raises(ValueError): e.dispatch("bridge.poll", {"token": owner})
def test_partial_config_deadline_drops_queued_fragments_without_commit():
clock, sdk, e, token = setup()
original = sdk.transmit
def slow(ch, value):
original(ch, value)
clock[0] += .11
sdk.transmit = slow
with pytest.raises(ValueError, match="истёк"):
send(e, token, configuration_frames()[1])
sent = [c[2] for c in sdk.calls if c[0] == "tx"]
assert len(sent) == 2 and all(c["id"] >> 8 == 5 for c in sent)
assert not e.running[0] and not e.bridges.claims and sdk.calls[-1] == ("stop", 0)
+107
View File
@@ -0,0 +1,107 @@
"""CAN arbitration and ambiguous completion, with no hardware or motor RPCs."""
import pytest
from test_bridge import setup
from usbcan_test_runtime.confirmed_tx import ECHO_TIMEOUT
def request(token, payload=b'\x05\x00\x00\x4a\x38', deadline=10.2):
return {'token': token, 'frames': [{'id': 0x84a, 'data': (b'\xfe\x00'+payload).hex()}],
'deadline': deadline}
@pytest.mark.parametrize('payload', [b'\x05\x00\x00\x4a\x38', b'\x06'+b'\x00'*4,
b'\x08'+(3000).to_bytes(4,'big'), b'\x3f\x00\x00\x00\x00\xfa'])
def test_lost_arbitration_waits_for_echo_before_success_without_app_replay(payload):
clock, sdk, e, token = setup()
original = sdk.receive
def receive(ch):
# Hardware controller is still arbitrating; SDK accepted already.
if sdk.echoes[ch] and clock[0] < 10.007:
return []
return original(ch)
sdk.receive = receive
result = e.dispatch('bridge.send', request(token, payload))
assert 10.007 <= clock[0] < 10.009
assert result['tx_confirmation']['confirmed'] == 1
assert result['tx_confirmation']['kind'] == 'adapter_echo'
assert len([c for c in sdk.calls if c[0]=='tx']) == 1
assert sdk.calls[-1][2]['send_type'] == 2
assert e.running[0]
@pytest.mark.parametrize('fault', ['lost', 'late', 'wrong_payload', 'wrong_id', 'wrong_channel', 'rtr', 'error', 'standard', 'fd'])
def test_no_completion_fails_closed_resets_shared_channel_and_never_replays(fault):
clock, sdk, e, token = setup()
other = e.dispatch('bridge.open', {'channel':0,'bitrate':500000,'receive_id':253})['token']
original = sdk.receive
def receive(ch):
if fault == 'lost': return []
frames = original(ch)
if frames:
if fault == 'late': clock[0] += .1
elif fault == 'wrong_payload': frames[0]['data']='00'
elif fault == 'wrong_id': frames[0]['id']=0x84b
elif fault == 'wrong_channel': frames[0]['channel']=1
elif fault == 'standard': frames[0]['extended']=False
else: frames[0][fault]=True
return frames
sdk.receive = receive
with pytest.raises(OSError): e.dispatch('bridge.send', request(token))
assert not e.running[0] and not e.bridges.claims
assert sdk.calls[-1] == ('stop',0)
for value in (token,other):
with pytest.raises(ValueError): e.dispatch('bridge.send',request(value))
assert len([c for c in sdk.calls if c[0]=='tx'])==1
def test_request_deadline_wins_over_echo_budget():
clock, sdk, e, token = setup()
sdk.receive=lambda ch: []
with pytest.raises(OSError): e.dispatch('bridge.send',request(token,deadline=10.003))
assert clock[0] < 10.004 and not e.running[0]
def test_stale_buffered_echo_cannot_confirm_new_send():
clock, sdk, e, token=setup()
e.dispatch('bridge.send',request(token))
echo=dict(sdk.calls[-1][2],channel=0,error=False)
sdk.echoes[0].append(echo)
original=sdk.transmit
def lose(ch, value):
original(ch,value)
sdk.echoes[ch].clear()
sdk.transmit=lose
with pytest.raises(OSError): e.dispatch('bridge.send',request(token))
assert clock[0] >= 10+ECHO_TIMEOUT
def test_unrelated_read_response_is_preserved_during_confirmation():
clock,sdk,e,token=setup()
rx={'channel':0,'id':0x8fe,'extended':True,'data':'4a0100','dlc':3,'error':False}
original=sdk.receive
def receive(ch):
frames=original(ch)
return [rx,*frames] if frames else []
sdk.receive=receive
result=e.dispatch('bridge.send',request(token))
assert result['frames']==[rx]
def test_sdk_exception_after_enqueue_discards_every_shared_claim():
clock,sdk,e,token=setup()
e.dispatch('bridge.open',{'channel':0,'bitrate':500000,'receive_id':253})
original=sdk.transmit
def broken(ch,value):
original(ch,value)
raise OSError('uncertain SDK completion')
sdk.transmit=broken
with pytest.raises(OSError):e.dispatch('bridge.send',request(token))
assert not e.bridges.claims and not e.running[0]
@pytest.mark.parametrize('payload',[b'\x05',b'\x05'+b'\0'*3,b'\x05'+b'\0'*5,
b'\x3f\x01\0\0\0\xfa',b'\x3f\0\0\0\1\0',b'\x3f\0\0\0\0\0',b'\x22\x4a\x05\0\0\0'])
def test_unclassified_or_forwarded_command_never_gains_hardware_retry(payload):
clock,sdk,e,token=setup()
e.dispatch('bridge.send',request(token,payload))
assert sdk.calls[-1][2]['send_type']==1
@@ -0,0 +1,171 @@
"""Volatile configuration delivery under an inert arbitration-loss model."""
import binascii
import copy
import struct
import pytest
from test_bridge import setup
def frames(payload=None, target=74, sender=254):
# Firmware 5.02: command, store/forward/ack/divide, eight float32 values.
payload = payload if payload is not None else bytes((48, 0, 0, 1, 0)) + struct.pack(
">8f", .2, .2, -100000, 100000, .005, .95, -1500000, 1500000)
result = [{"id": (5 << 8) | target,
"data": (bytes((i,)) + payload[i:i+7]).hex()}
for i in range(0, len(payload), 7)]
result.append({"id": (7 << 8) | target,
"data": (bytes((sender, 0)) + len(payload).to_bytes(2, "big")
+ binascii.crc_hqx(payload, 0).to_bytes(2, "big")).hex()})
return result
def send(e, token, value):
return e.dispatch("bridge.send", {"token": token, "frames": value, "deadline": 10.2})
def ack(target=74, sender=254, **changes):
return {"channel": 0, "id": (8 << 8) | sender, "extended": True,
"data": bytes((target, 1, 48)).hex(), **changes}
def test_complete_limits_survive_inert_arbitration_loss_without_application_replay():
clock, sdk, e, token = setup()
original = sdk.transmit
received, replies, dropped = bytearray(37), [], []
def wire(ch, value):
original(ch, value)
# An independent bus model: single-shot loses one arbitration and is
# discarded; normal controller transmission eventually delivers it.
data = bytes.fromhex(value["data"])
if value["id"] >> 8 == 5:
if data[0] == 7 and value["send_type"] == 1:
dropped.append(value)
return
received[data[0]:data[0]+len(data)-1] = data[1:]
else:
if binascii.crc_hqx(received, 0) == int.from_bytes(data[4:6], "big"):
replies.append(ack())
sdk.transmit = wire
value = frames()
send(e, token, value)
assert not dropped and replies == [ack()]
assert len([v for v in sdk.calls if v[0] == "tx"]) == 7
assert e.bridges.claims[token]["write_pending"] == {"target": 74, "command": 48}
e.bridges.receive(replies[0])
assert e.bridges.claims[token]["write_pending"] is None
assert e.dispatch("bridge.poll", {"token": token})["frames"] == replies
@pytest.mark.parametrize("change", [
(0, 5), (0, 49), (1, 1), (2, 1), (3, 0), (4, 1),
])
def test_mutations_other_than_exact_acknowledged_volatile_limits_stay_single_shot(change):
clock, sdk, e, token = setup()
payload = bytearray(bytes((48, 0, 0, 1, 0)) + struct.pack(
">8f", .2, .2, -100000, 100000, .005, .95, -1500000, 1500000))
payload[change[0]] = change[1]
send(e, token, frames(bytes(payload)))
assert all(v[2]["send_type"] == 1 for v in sdk.calls if v[0] == "tx")
assert e.bridges.claims[token]["write_pending"] is None
@pytest.mark.parametrize("case", ["offset", "missing", "duplicate", "crc", "target",
"reply", "broadcast", "self", "length", "short-chunk"])
def test_ambiguous_fragments_never_get_hardware_retry(case):
clock, sdk, e, token = setup()
value = copy.deepcopy(frames())
if case == "offset":
value[1]["data"] = "08" + value[1]["data"][2:]
elif case == "missing":
value.pop(2)
elif case == "duplicate":
value[2] = value[1].copy()
elif case == "crc":
value[-1]["data"] = value[-1]["data"][:-4] + "0000"
elif case == "target":
value[1]["id"] += 1
elif case == "reply":
value[-1]["data"] = "fd" + value[-1]["data"][2:]
elif case == "broadcast":
value = frames(target=255)
elif case == "self":
value = frames(target=254)
elif case == "length":
value[-1]["data"] = value[-1]["data"][:4]+"0026"+value[-1]["data"][8:]
elif case == "short-chunk":
value[1]["data"] = value[1]["data"][:-2]
send(e, token, value)
assert all(v[2]["send_type"] == 1 for v in sdk.calls if v[0] == "tx")
@pytest.mark.parametrize("scale", [0., -1., 1.01, float("inf"), float("nan")])
def test_invalid_limits_never_get_hardware_retry(scale):
clock, sdk, e, token = setup()
payload = bytes((48, 0, 0, 1, 0)) + struct.pack(
">8f", scale, .2, -100000, 100000, .005, .95, -1500000, 1500000)
send(e, token, frames(payload))
assert all(v[2]["send_type"] == 1 for v in sdk.calls if v[0] == "tx")
def test_only_exact_ack_clears_pending_write():
clock, sdk, e, token = setup()
send(e, token, frames())
for wrong in (ack(target=75), ack(sender=253), ack(fd=True), ack(rtr=True),
ack(error=True), ack(data="4a0130ff"), ack(data="4a013e")):
e.bridges.receive(wrong)
assert e.bridges.claims[token]["write_pending"] == {"target": 74, "command": 48}
e.bridges.receive(ack())
assert e.bridges.claims[token]["write_pending"] is None
@pytest.mark.parametrize("reason", ["close", "expire", "second-send"])
def test_unconfirmed_write_resets_channel_and_retires_other_claims(reason):
clock, sdk, e, token = setup()
other = e.dispatch("bridge.open", {"channel": 0, "bitrate": 500000, "receive_id": 253})["token"]
send(e, token, frames())
if reason == "close":
e.dispatch("bridge.close", {"token": token})
elif reason == "expire":
clock[0] = 11
e.tick()
else:
with pytest.raises(ValueError, match="Подтверждение"):
send(e, token, frames())
assert not e.running[0] and not e.bridges.claims
assert sdk.calls[-1] == ("stop", 0)
assert len([v for v in sdk.calls if v[0] == "tx"]) == 7
e.bridges.receive(ack()) # A late ACK cannot resurrect either owner.
for t in (token, other):
with pytest.raises(ValueError):
e.dispatch("bridge.poll", {"token": t})
def test_acknowledged_write_does_not_retire_an_independent_reader():
clock, sdk, e, token = setup()
other = e.dispatch("bridge.open", {"channel": 0, "bitrate": 500000, "receive_id": 253})["token"]
send(e, token, frames())
e.bridges.receive(ack())
e.dispatch("bridge.close", {"token": token})
assert e.running[0] and other in e.bridges.claims
e.dispatch("bridge.close", {"token": other})
assert not e.running[0]
def test_partial_send_deadline_discards_queue_and_never_replays_commit():
clock, sdk, e, token = setup()
original = sdk.transmit
def slow(ch, value):
original(ch, value)
clock[0] += .11
sdk.transmit = slow
with pytest.raises(ValueError, match="истёк"):
send(e, token, frames())
sent = [v[2] for v in sdk.calls if v[0] == "tx"]
assert len(sent) == 2 and all(v["id"] >> 8 == 5 for v in sent)
assert sdk.calls[-1] == ("stop", 0) and not e.bridges.claims
+317
View File
@@ -0,0 +1,317 @@
# Runtime lives in a hyphenated plugin directory; load the package before imports.
# ruff: noqa: E402
"""Synthetic contract tests. These never load the SDK or open hardware."""
import importlib.util
import sys
from datetime import UTC, datetime, timedelta
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location(
"usbcan_test_runtime",
ROOT / "runtime/__init__.py",
submodule_search_locations=[str(ROOT / "runtime")],
)
runtime = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = runtime
spec.loader.exec_module(runtime)
from usbcan_test_runtime.contracts import DEFAULT, configuration, frame, transmission
from usbcan_test_runtime.discovery import Attachment, discover
from usbcan_test_runtime.sdk import check_abi
from usbcan_test_runtime.service import Service
from usbcan_test_runtime.worker import Engine
def sample(**updates):
return {
"id": 74,
"extended": True,
"fd": False,
"rtr": False,
"brs": False,
"data": "00FF",
"dlc": 2,
"send_type": 1,
**updates,
}
def plan(**updates):
return {
"frames": [sample()],
"repeat": 1,
"interval_ms": 10,
"increment_id": False,
"increment_data": False,
**updates,
}
class FakeSDK:
identity = {
"serial": "SYNTHETIC-ONLY",
"channels": 2,
"model": "USBCANFD0002",
"hardware": "1.00",
"firmware": "1.00",
"driver": "1.00",
"interface": "1.00",
}
def __init__(self):
self.calls = []
self.echoes = [[], []]
def start(self, ch, config):
self.calls.append(("start", ch))
def stop(self, ch):
self.calls.append(("stop", ch))
def clear(self, ch):
self.calls.append(("clear", ch))
def receive(self, ch):
frames, self.echoes[ch] = self.echoes[ch], []
return frames
def transmit(self, ch, value):
self.calls.append(("tx", ch, value))
if value["send_type"] == 2:
self.echoes[ch].append({**value, "channel": ch, "direction": "RX", "error": False})
def online(self):
return True
def close(self):
self.calls.append(("close",))
class FakeLink:
def __init__(self, index, path):
self.engine = Engine(FakeSDK())
self.initial = self.engine.dispatch("status", {})
self.alive = True
def call(self, action, params):
return self.engine.dispatch(action, params)
def close(self):
self.alive = False
def command(d, action, params=None, identifier="a" * 32):
now = datetime.now(UTC)
return {
"api_version": runtime.SCHEMA,
"kind": "OperationRequest",
"operation_id": "op_" + identifier,
"idempotency_key": "op_" + identifier,
"session": {"device_id": d.id, "session_id": d.session},
"requested_at": now.isoformat(),
"deadline_at": (now + timedelta(seconds=50)).isoformat(),
"action_id": action,
"parameters": params or {},
}
def test_exact_abi_and_safe_defaults():
check_abi()
sdk = FakeSDK()
engine = Engine(sdk)
engine.tick()
assert not sdk.calls
assert all(
c["config"]["mode"] == "listen" and not c["running"]
for c in engine.dispatch("status", {})["channels"]
)
@pytest.mark.parametrize(
"update",
[
{"id": 0x800, "extended": False},
{"dlc": 9},
{"fd": True, "rtr": True},
{"brs": True},
{"data": "ZZ"},
{"id": True},
{"fd": True, "dlc": 10, "data": "00" * 10},
],
)
def test_reject_invalid_frames(update):
with pytest.raises(ValueError):
frame(sample(**update))
def test_filter_and_job_bounds():
with pytest.raises(ValueError):
configuration({**DEFAULT, "filters": [{"extended": True, "start": 0, "end": 10}] * 33})
with pytest.raises(ValueError):
transmission(plan(repeat=1000, interval_ms=1000))
with pytest.raises(ValueError):
transmission(plan(frames=[sample(id=0x7FF, extended=False)], repeat=2, increment_id=True))
assert (
len(
configuration({**DEFAULT, "filters": [{"extended": False, "start": 0, "end": 1}] * 64})[
"filters"
]
)
== 64
)
def test_tx_requires_normal_running_channel_and_cancellation_stops_queue():
sdk = FakeSDK()
clock = [0.0]
engine = Engine(sdk, lambda: clock[0])
with pytest.raises(ValueError):
engine.dispatch("transmit", {"channel": 0, "plan": plan()})
engine.dispatch("start", {"channel": 0})
with pytest.raises(ValueError):
engine.dispatch("transmit", {"channel": 0, "plan": plan()})
engine.dispatch("stop", {"channel": 0})
engine.dispatch("configure", {"channel": 0, "config": {**DEFAULT, "mode": "normal"}})
engine.dispatch("start", {"channel": 0})
engine.dispatch("transmit", {"channel": 0, "plan": plan(repeat=2)})
engine.tick()
engine.dispatch("transmit.stop", {"channel": 0})
clock[0] += 1
engine.tick()
assert len([c for c in sdk.calls if c[0] == "tx"]) == 1
def test_rx_retention_is_bounded_and_expires():
clock = [0.0]
engine = Engine(FakeSDK(), lambda: clock[0])
for i in range(2100):
engine.append({"channel": 0, "direction": "RX", "id": i})
assert len(engine.frames) == 2000 and engine.evicted == 100
assert len(engine.dispatch("status", {"after": 0})["frames"]) == 256
clock[0] = 301
assert engine.dispatch("status", {"after": 0})["frames"] == []
def test_hotplug_changes_session_preserves_identity_and_never_resumes(tmp_path):
attachments = [Attachment("1-2:6", "1-2", "/dev/bus/usb/001/006", "480")]
service = Service(tmp_path, lambda: list(attachments), FakeLink)
service.scan()
old = next(iter(service.devices.values()))
old_id, old_session = old.id, old.session
service.execute(
command(
old,
"can.configure",
{"channel": 0, "revision": 0, "config": {**DEFAULT, "mode": "normal"}},
)
)
service.execute(command(old, "can.start", {"channel": 0}, "b" * 32))
stale = command(old, "can.start", {"channel": 0}, "c" * 32)
attachments.clear()
service.scan()
attachments.append(Attachment("1-7:9", "1-7", "/dev/bus/usb/001/009", "480"))
service.scan()
new = next(iter(service.devices.values()))
assert new.id == old_id and new.session != old_session
assert not any(c["running"] for c in new.status["channels"])
assert new.status["channels"][0]["config"]["mode"] == "normal"
with pytest.raises(ValueError):
service.execute(stale)
def test_preview_one_use_and_repeated_request_never_duplicates(tmp_path):
attachment = Attachment("1-2:6", "1-2", "/dev/bus/usb/001/006", "480")
service = Service(tmp_path, lambda: [attachment], FakeLink)
service.scan()
d = next(iter(service.devices.values()))
service.execute(
command(
d,
"can.configure",
{"channel": 0, "revision": 0, "config": {**DEFAULT, "mode": "normal"}},
)
)
service.execute(command(d, "can.start", {"channel": 0}, "b" * 32))
preview = service.execute(
command(d, "can.transmit.preview", {"channel": 0, "plan": plan()}, "c" * 32)
)["result"]
request = command(
d,
"can.transmit.apply",
{"channel": 0, "token": preview["token"], "confirmed": True},
"d" * 32,
)
first = service.execute(request)
assert service.execute(request) == first
assert (
service.execute(command(d, "can.transmit.apply", request["parameters"], "e" * 32))["state"]
== "error"
)
d.link.engine.tick()
assert len([c for c in d.link.engine.sdk.calls if c[0] == "tx"]) == 1
assert not list(tmp_path.glob("op_*"))
def test_discovery_requires_exact_model_and_ignores_usb_serial(tmp_path):
p = tmp_path / "1-5"
p.mkdir()
for name, value in {
"idVendor": "04d8",
"idProduct": "0053",
"product": "USB CANFD DEBUG",
"serial": "Љ",
"devnum": "6",
"busnum": "1",
"speed": "480",
}.items():
(p / name).write_text(value)
found = discover(tmp_path)
assert len(found) == 1 and found[0].binding == "1-5:6"
(p / "product").write_text("Different device")
assert discover(tmp_path) == []
def test_prepare_returns_confirmed_identity_and_refuses_active_channel(tmp_path):
a = Attachment("1-2:6", "1-2", "/dev/bus/usb/001/006", "480")
service = Service(tmp_path, lambda: [a], FakeLink)
service.scan()
d = next(iter(service.devices.values()))
result = service.execute(command(d, "verify"))
assert result["result"]["device_id"] == d.id
assert service.prepare_safe()
service.execute(command(d, "can.start", {"channel": 0}, "b" * 32))
assert not service.prepare_safe()
def test_usb_owner_recovery_rejects_previous_session(tmp_path):
a = Attachment("1-2:6", "1-2", "/dev/bus/usb/001/006", "480")
service = Service(tmp_path, lambda: [a], FakeLink)
service.scan()
d = next(iter(service.devices.values()))
stale = command(d, "can.start", {"channel": 0})
d.link.alive = False
d.retry_at = 0
service.scan()
with pytest.raises(ValueError):
service.execute(stale)
def test_preparation_verify_accepts_node_deadline_without_widening_can_commands(tmp_path):
attachment = Attachment("1-2:6", "1-2", "/dev/bus/usb/001/006", "480")
service = Service(tmp_path, lambda: [attachment], FakeLink)
service.scan()
d = next(iter(service.devices.values()))
request = command(d, "verify")
start = datetime.fromisoformat(request["requested_at"])
request["deadline_at"] = (start + timedelta(seconds=350)).isoformat()
assert service.execute(request)["state"] == "complete"
assert not d.link.engine.sdk.calls
request["action_id"] = "can.start"
request["parameters"] = {"channel": 0}
request["operation_id"] = request["idempotency_key"] = "op_" + "b" * 32
with pytest.raises(ValueError, match="Срок"):
service.execute(request)