Files
NODEDC_MISSION_CORE/tests/test_arnavi_b2_write.py

286 lines
9.6 KiB
Python

"""Transaction failure cases with synthetic configurations; no physical USB."""
import base64
from dataclasses import replace
import pytest
from k1link.device_plugins.arnavi_b2.usb_protocol import (
Configuration,
Identity,
ProtocolError,
Setting,
)
from k1link.device_plugins.arnavi_b2.usb_read import UsbReadError
from k1link.device_plugins.arnavi_b2.usb_write import envelope, transact, write_all
IDENTITY = Identity(231, "123456", "123456789012345", "0.01", None, "89000000000000000001")
BEFORE = Configuration((Setting(5, b"123456"), Setting(25, b"\0\x0f"), Setting(135, b"opaque")))
class Fake:
def __init__(self, outcome="apply"):
self.outcome, self.current, self.commands = outcome, BEFORE, []
def identity(self):
return IDENTITY
def settings(self):
return self.current
def write(self, command):
from k1link.device_plugins.arnavi_b2.usb_protocol import decode_configuration
self.commands.append(command)
if self.outcome == "lost":
raise OSError("lost")
if self.outcome == "unchanged":
return False
target = decode_configuration(base64.b64decode(command[12:-2]))
self.current = (
Configuration((Setting(5, b"123456"), Setting(25, b"\0\x07"), Setting(135, b"opaque")))
if self.outcome == "partial" and len(self.commands) == 1
else target
)
return self.outcome != "no_ack"
@pytest.mark.parametrize(
"outcome,state,writes",
[
("apply", "applied", 1),
("no_ack", "applied", 1),
("unchanged", "not_applied", 1),
("lost", "uncertain", 1),
("partial", "rolled_back", 2),
],
)
def test_readback_not_ack_is_authoritative_and_writes_are_bounded(outcome, state, writes):
transport = Fake(outcome)
backups = []
def backup(before, target):
assert not transport.commands
backups.append((before, target))
result = transact(transport, IDENTITY, BEFORE, {"parameters": {"25": 30}}, backup)
assert result["state"] == state
assert len(transport.commands) == writes
assert result["changed_fields"] == [25]
assert backups[0][0] == BEFORE
if state == "rolled_back":
assert transport.current == BEFORE
def test_changed_sim_or_settings_or_unsupported_firmware_never_writes():
for expected, before in [
(replace(IDENTITY, iccid2_reported="89000000000000000002"), BEFORE),
(replace(IDENTITY, firmware="0.02"), BEFORE),
(IDENTITY, Configuration((Setting(5, b"123456"),))),
]:
transport = Fake()
with pytest.raises(ProtocolError):
transact(transport, expected, before, {"parameters": {"25": 30}}, lambda *_: None)
assert not transport.commands
def test_backup_failure_prevents_write_and_noop_does_not_rewrite_flash():
transport = Fake()
def fail(*_):
raise OSError("disk full")
with pytest.raises(OSError):
transact(transport, IDENTITY, BEFORE, {"parameters": {"25": 30}}, fail)
assert not transport.commands
assert transact(transport, IDENTITY, BEFORE, {}, lambda *_: None)["state"] == "unchanged"
assert not transport.commands
def test_envelope_has_only_qualified_command_and_rejects_password_change():
assert envelope(BEFORE, BEFORE) == b"123456*CONF*" + base64.b64encode(BEFORE.encode()) + b"\r\n"
with pytest.raises(ProtocolError):
envelope(BEFORE, Configuration((Setting(5, b"654321"),)))
def test_nonblocking_tty_completes_short_write_without_repeating_prefix(monkeypatch):
from k1link.device_plugins.arnavi_b2 import usb_write
payload = bytes(range(256)) * 5 + b"\r\n"
received = bytearray()
calls = []
def send(fd, suffix):
calls.append(suffix)
if len(calls) == 2:
raise BlockingIOError()
count = min(1024, len(suffix))
received.extend(suffix[:count])
return count
monkeypatch.setattr(usb_write.os, "write", send)
monkeypatch.setattr(usb_write.select, "select", lambda *args: ([], [42], []))
progress = []
write_all(42, payload, progress.append)
assert bytes(received) == payload
assert calls == [payload, payload[1024:], payload[1024:]]
assert progress == [1024, len(payload)]
def test_write_deadline_preserves_prefix_and_never_restarts_frame(monkeypatch):
from k1link.device_plugins.arnavi_b2 import usb_write
ticks = iter([0, 0, 9])
calls = []
monkeypatch.setattr(usb_write.time, "monotonic", lambda: next(ticks))
monkeypatch.setattr(usb_write.select, "select", lambda *args: ([], [42], []))
monkeypatch.setattr(usb_write.os, "write", lambda fd, b: calls.append(b) or 2)
progress = []
with pytest.raises(UsbReadError, match="usb_write_timeout"):
write_all(42, b"synthetic-frame\r\n", progress.append)
assert calls == [b"synthetic-frame\r\n"]
assert progress == [2]
def test_mts_readback_is_exact_and_preserves_unmodified_null_terminated_strings():
from k1link.device_plugins.arnavi_b2.profiles import prepare
before = Configuration(
(
Setting(5, b"123456"),
Setting(67, b"internet\0"),
Setting(89, b""),
Setting(90, b""),
Setting(91, b""),
)
)
policy = {
"connectivity": {
"strategy": "operator",
"preset_id": "ru-mts-public-v1",
"sim_slot": 2,
}
}
target = prepare(before, policy)
assert target.value(89) == b"internet.mts.ru"
assert target.value(90) == target.value(91) == b"mts"
assert target.value(67) == before.value(67)
assert prepare(target, policy).encode() == target.encode()
def test_configuration_service_bootstrap_preserves_every_other_record():
from k1link.device_plugins.arnavi_b2.usb_write import configuration_service_target
before = Configuration(
BEFORE.records + (Setting(70, b"vendor.example"), Setting(71, b"\x24\x0f"))
)
target = configuration_service_target(before, {"host": "owner.example", "port": 9922})
assert target.text(70) == "owner.example"
assert target.integer(71, 2) == 9922
assert [(r.number, r.value) for r in target.records if r.number not in (70, 71)] == [
(r.number, r.value) for r in BEFORE.records
]
for value in ("https://owner.example/", "bad\r\ncommand"):
with pytest.raises(ValueError):
configuration_service_target(before, {"host": value, "port": 9922})
def test_initial_provisioning_sets_monitoring_and_configuration_channel_together():
from k1link.device_plugins.arnavi_b2.usb_write import bootstrap_target
before = Configuration(
BEFORE.records
+ tuple(
Setting(n, v)
for n, v in (
(1, b"vendor.example"),
(2, b"\x24\x0f"),
(9, b"\0"),
(3, b""),
(4, b"\0\0"),
(8, b"\0"),
(70, b"vendor.example"),
(71, b"\x24\x0f"),
(72, b"\x80\x00\x08\x19"),
(62, b"\x00\x96"),
)
)
)
policy = {
"endpoint": {"slot": 1, "host": "owner.example", "port": 9922},
"parameters": {"25": 16},
}
target = bootstrap_target(before, policy)
assert all(target.text(n) == "owner.example" for n in (1, 3, 70))
assert all(target.integer(n, 2) == 9922 for n in (2, 4, 71))
assert target.integer(25, 2) == 16
assert target.integer(72, 4) == before.integer(72, 4) & ~1
assert target.value(62) == before.value(62)
assert [r.number for r in target.records if r.value != before.value(r.number)] == [
25,
1,
2,
3,
4,
70,
71,
72,
]
assert target.value(135) == before.value(135) and target.value(5) == before.value(5)
assert bootstrap_target(target, policy).encode() == target.encode()
with pytest.raises(ProtocolError):
bootstrap_target(before, {"parameters": {"25": 16}})
# An absent or malformed bitset must fail before backing up/sending a write.
for value in (None, b"\x01", b"\x00" * 5):
records = tuple(r for r in before.records if r.number != 72)
if value is not None:
records += (Setting(72, value),)
transport = Fake()
transport.current = Configuration(records)
backups = []
with pytest.raises(ProtocolError):
transact(
transport,
IDENTITY,
transport.current,
policy,
lambda *args, backups=backups: backups.append(args),
prepare_target=bootstrap_target,
)
assert not transport.commands and not backups
def test_bootstrap_uses_one_backed_up_verified_usb_transaction():
from k1link.device_plugins.arnavi_b2.usb_write import bootstrap_target
before = Configuration(
BEFORE.records
+ tuple(
Setting(n, v)
for n, v in (
(1, b"vendor.example"),
(2, b"\x24\x0f"),
(9, b"\0"),
(3, b""),
(4, b"\0\0"),
(8, b"\0"),
(70, b"vendor.example"),
(71, b"\x24\x0f"),
(72, b"\x00\x00\x08\x19"),
)
)
)
t = Fake()
t.current = before
backups = []
result = transact(
t,
IDENTITY,
before,
{"endpoint": {"slot": 1, "host": "owner.example", "port": 9922}},
lambda a, b: backups.append((a, b)),
prepare_target=bootstrap_target,
)
assert result["state"] == "applied" and len(t.commands) == len(backups) == 1
assert t.current == backups[0][1] and backups[0][0] == before