Package the adapter SDK boundary and runtime lifecycle. Confirm admitted CAN transactions, bound retained data and test failure paths with synthetic hardware.
318 lines
10 KiB
Python
318 lines
10 KiB
Python
# 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)
|