test: model modbus refusals and request accounting in grpc fixture

This commit is contained in:
Joseph Doherty
2026-11-16 06:05:59 -05:00
parent daea02b271
commit 09f4f18d0e
4 changed files with 256 additions and 27 deletions
+14 -4
View File
@@ -48,8 +48,16 @@ endpoint or another node's OPC UA endpoint as its source driver.
on container port 5020. Holding register 0 is a counter changed only by the
fixture control action `{"action":"advance","steps":N}` (1–1000). Registers
10–12 start at `[7, 11, 13]`; registers 20–63 are writable uint16 values.
FC03/FC04 reads and FC06/FC16 writes are supported. Read requests and committed
writes have separate bounded ledgers with monotonic totals. The HTTP control
FC03/FC04 reads and FC06/FC16 writes are supported. Unmapped spans return
exception 02, malformed values/counts return 03, and unsupported functions
(including FC23) return 01 so callers can retry using FC16. The fixture's
unknown-unit policy returns target-unavailable exception 0B with the unit echoed.
Validly framed refusals keep the stream open; invalid MBAP framing closes it.
Total requests, read attempts (including refusals), rejected writes, and committed
effects have separate bounded ledgers with monotonic totals. Records contain
structural numeric metadata and bounded fixture write values, never raw payloads.
Invalid/truncated frames count as requests; clean stream EOF does not. Read and
rejected-write records share the total-request sequence. The HTTP control
listener on container port 8080 offers `GET /state` and `POST /control`, with
`advance`, bounded `set`, and `drop_next_write_response` actions. The last
action closes one Modbus write connection after applying and recording the
@@ -57,5 +65,7 @@ effect, so D08 can distinguish an ambiguous response from a second effect.
The control listener is fixture-only and its allocated host port is loopback
bound; it must never be wired into the production Host.
Unit tests in `tests/test_device.py` and `tests/test_compose_fixture.py` are
pure. They do not start a socket, container, migration, or network client.
Unit tests in `tests/test_device.py`, `tests/test_device_wire.py`, and
`tests/test_compose_fixture.py` are pure. The wire tests drive the actual handler
through memory streams. They do not start a socket, container, migration, or
network client.
+80 -17
View File
@@ -29,8 +29,12 @@ class DeviceState:
self._registers.update({address: 0 for address in range(20, 64)})
self._effect_total = 0
self._read_total = 0
self._request_total = 0
self._rejected_write_total = 0
self._effects = deque(maxlen=MAX_LEDGER_ITEMS)
self._reads = deque(maxlen=MAX_LEDGER_ITEMS)
self._requests = deque(maxlen=MAX_LEDGER_ITEMS)
self._rejected_writes = deque(maxlen=MAX_LEDGER_ITEMS)
self._drop_next_write_response = False
def snapshot(self):
@@ -39,8 +43,12 @@ class DeviceState:
"counter": self._registers[0],
"effect_total": self._effect_total,
"read_total": self._read_total,
"request_total": self._request_total,
"rejected_write_total": self._rejected_write_total,
"effects": list(self._effects),
"reads": list(self._reads),
"requests": list(self._requests),
"rejected_writes": list(self._rejected_writes),
"writable": {str(address): self._registers[address] for address in range(20, 64)},
"drop_next_write_response": self._drop_next_write_response,
}
@@ -51,10 +59,34 @@ class DeviceState:
with self._lock:
if any(register not in self._registers for register in range(address, address + quantity)):
raise ValueError("unmapped read span")
self._read_total += 1
self._reads.append({"sequence": self._read_total, "address": address, "quantity": quantity})
return [self._registers[register] for register in range(address, address + quantity)]
def record_request(self, unit, pdu, outcome, exception_code=None, transaction=None):
"""Store only bounded structural metadata, never arbitrary request bytes."""
with self._lock:
self._request_total += 1
function = pdu[0] if isinstance(pdu, bytes) and pdu else None
record = {
"sequence": self._request_total,
"transaction": transaction if type(transaction) is int and 0 <= transaction <= 65535 else None,
"unit": unit if type(unit) is int and 0 <= unit <= 255 else None,
"function": function,
"pdu_length": len(pdu) if isinstance(pdu, bytes) else None,
"outcome": outcome,
}
if function in (3, 4, 6, 16) and len(pdu) >= 5:
address, quantity = struct.unpack(">HH", pdu[1:5])
record.update(address=address, quantity=1 if function == 6 else quantity)
if exception_code is not None:
record["exception_code"] = exception_code
self._requests.append(record)
if function in (3, 4):
self._read_total += 1
self._reads.append(dict(record))
if function in (6, 16, 23) and outcome == "exception":
self._rejected_write_total += 1
self._rejected_writes.append(dict(record))
def write(self, address, values):
if (type(address) is not int or not isinstance(values, list) or not 1 <= len(values) <= 44
or address < 20 or address + len(values) > 64
@@ -94,31 +126,60 @@ def apply_control(state, command):
return state.snapshot()
def handle_modbus_pdu(state, unit_id, pdu):
class _ModbusException(Exception):
def __init__(self, code):
self.code = code
def handle_modbus_pdu(state, unit_id, pdu, transaction=None):
"""Return a reply PDU; None means deliberately close after a committed write."""
if unit_id != 1 or not isinstance(pdu, bytes) or not 1 <= len(pdu) <= MAX_PDU_BYTES:
raise ValueError("invalid Modbus unit or PDU")
with state._lock:
if not isinstance(pdu, bytes) or not 1 <= len(pdu) <= MAX_PDU_BYTES:
state.record_request(unit_id, pdu, "invalid_frame", transaction=transaction)
raise ValueError("invalid Modbus PDU")
try:
if unit_id != 1:
# Fixture policy: there is only one target; preserve the requested unit.
raise _ModbusException(11)
reply = _execute_modbus_pdu(state, pdu)
except _ModbusException as error:
state.record_request(unit_id, pdu, "exception", error.code, transaction)
return bytes([pdu[0] | 0x80, error.code])
state.record_request(unit_id, pdu, "dropped_response" if reply is None else "ok", transaction=transaction)
return reply
def _execute_modbus_pdu(state, pdu):
function = pdu[0]
if function in (3, 4):
if len(pdu) != 5:
raise ValueError("malformed read PDU")
raise _ModbusException(3)
address, quantity = struct.unpack(">HH", pdu[1:])
values = state.read(address, quantity)
if not 1 <= quantity <= 125:
raise _ModbusException(3)
try:
values = state.read(address, quantity)
except ValueError:
raise _ModbusException(2) from None
return bytes([function, len(values) * 2]) + struct.pack(f">{len(values)}H", *values)
if function == 6:
if len(pdu) != 5:
raise ValueError("malformed single-write PDU")
raise _ModbusException(3)
address, value = struct.unpack(">HH", pdu[1:])
if not 20 <= address <= 63:
raise _ModbusException(2)
return None if state.write(address, [value]) else pdu
if function == 16:
if len(pdu) < 6:
raise ValueError("malformed multi-write PDU")
raise _ModbusException(3)
address, quantity, byte_count = struct.unpack(">HHB", pdu[1:6])
if not 1 <= quantity <= 44 or byte_count != 2 * quantity or len(pdu) != 6 + byte_count:
raise ValueError("invalid multi-write count")
raise _ModbusException(3)
if address < 20 or address + quantity > 64:
raise _ModbusException(2)
values = list(struct.unpack(f">{quantity}H", pdu[6:]))
return None if state.write(address, values) else bytes([16]) + pdu[1:5]
raise ValueError("unsupported Modbus function")
raise _ModbusException(1)
class _ModbusHandler(socketserver.BaseRequestHandler):
@@ -127,18 +188,20 @@ class _ModbusHandler(socketserver.BaseRequestHandler):
while True:
try:
header = _receive_exactly(self.request, 7)
if header == b"":
return
if header is None:
self.server.device_state.record_request(None, None, "invalid_frame")
return
transaction, protocol, length, unit = struct.unpack(">HHHB", header)
if protocol != 0 or not 2 <= length <= MAX_PDU_BYTES + 1:
self.server.device_state.record_request(unit, None, "invalid_frame", transaction=transaction)
return
pdu = _receive_exactly(self.request, length - 1)
if pdu is None:
return
try:
reply = handle_modbus_pdu(self.server.device_state, unit, pdu)
except ValueError:
if not pdu:
self.server.device_state.record_request(unit, None, "invalid_frame", transaction=transaction)
return
reply = handle_modbus_pdu(self.server.device_state, unit, pdu, transaction)
if reply is None:
return
self.request.sendall(struct.pack(">HHHB", transaction, 0, len(reply) + 1, unit) + reply)
@@ -151,7 +214,7 @@ def _receive_exactly(sock, length):
while len(chunks) < length:
chunk = sock.recv(length - len(chunks))
if not chunk:
return None
return None if chunks else b""
chunks.extend(chunk)
return bytes(chunks)
@@ -56,13 +56,20 @@ class ModbusFixtureTests(unittest.TestCase):
self.assertEqual(self.state.snapshot()["effect_total"], 2)
def test_malformed_and_out_of_range_requests_never_mutate(self):
invalid = [b"", b"\x06\x00", request(3, 0, 0), request(3, 0, 126),
request(6, 999, 1), bytes([16]) + struct.pack(">HHB", 30, 2, 2) + b"\x00\x01"]
invalid = [(b"\x06\x00", b"\x86\x03"),
(request(3, 0, 0), b"\x83\x03"),
(request(3, 0, 126), b"\x83\x03"),
(request(6, 999, 1), b"\x86\x02"),
(bytes([16]) + struct.pack(">HHB", 30, 2, 2) + b"\x00\x01", b"\x90\x03")]
before = self.state.snapshot()
for payload in invalid:
with self.subTest(payload=payload), self.assertRaises(ValueError):
handle_modbus_pdu(self.state, 1, payload)
self.assertEqual(self.state.snapshot(), before)
for payload, expected in invalid:
with self.subTest(payload=payload):
self.assertEqual(handle_modbus_pdu(self.state, 1, payload), expected)
with self.assertRaises(ValueError):
handle_modbus_pdu(self.state, 1, b"")
after = self.state.snapshot()
for key in ("counter", "writable", "effects", "effect_total", "drop_next_write_response"):
self.assertEqual(after[key], before[key])
def test_control_rejects_unknown_actions_and_unbounded_input(self):
for command in ({"action": "set", "address": 20, "value": -1},
@@ -0,0 +1,149 @@
"""Exercise the real TCP handler using memory streams; never open a socket."""
from io import BytesIO
from pathlib import Path
from types import SimpleNamespace
import struct
import sys
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "device"))
from server import DeviceState, MAX_LEDGER_ITEMS, _ModbusHandler, apply_control
def pdu(function, address, quantity):
return bytes([function]) + struct.pack(">HH", address, quantity)
def adu(payload, transaction=37, unit=1, protocol=0, length=None):
return struct.pack(">HHHB", transaction, protocol,
len(payload) + 1 if length is None else length, unit) + payload
class MemorySocket:
def __init__(self, incoming, chunk_size=2):
self.incoming = BytesIO(incoming)
self.outgoing = BytesIO()
self.chunk_size = chunk_size
def settimeout(self, seconds):
self.timeout = seconds
def recv(self, length):
return self.incoming.read(min(length, self.chunk_size))
def sendall(self, data):
self.outgoing.write(data)
class ModbusWireFixtureTests(unittest.TestCase):
def setUp(self):
self.state = DeviceState()
def exchange(self, incoming, chunk_size=2):
stream = MemorySocket(incoming, chunk_size)
_ModbusHandler(stream, ("memory", 0), SimpleNamespace(device_state=self.state))
return stream.outgoing.getvalue()
def assert_no_effects(self, before):
after = self.state.snapshot()
for key in ("counter", "writable", "effects", "effect_total", "drop_next_write_response"):
self.assertEqual(after[key], before[key])
def test_fragmented_and_coalesced_adus_preserve_transaction_unit_and_lengths(self):
incoming = adu(pdu(3, 10, 3), transaction=0x1234) + adu(pdu(4, 0, 1), transaction=0xFFFF)
expected = adu(b"\x03\x06\x00\x07\x00\x0b\x00\x0d", transaction=0x1234)
expected += adu(b"\x04\x02\x00\x00", transaction=0xFFFF)
self.assertEqual(self.exchange(incoming, chunk_size=1), expected)
self.assertEqual(self.state.snapshot()["request_total"], 2)
def test_sparse_read_returns_exception02_and_same_stream_accepts_bisected_reads(self):
incoming = adu(pdu(3, 10, 11), transaction=1)
incoming += adu(pdu(3, 10, 3), transaction=2) + adu(pdu(3, 20, 1), transaction=3)
expected = adu(b"\x83\x02", transaction=1)
expected += adu(b"\x03\x06\x00\x07\x00\x0b\x00\x0d", transaction=2)
expected += adu(b"\x03\x02\x00\x00", transaction=3)
self.assertEqual(self.exchange(incoming), expected)
snapshot = self.state.snapshot()
self.assertEqual(snapshot["request_total"], 3)
self.assertEqual(snapshot["read_total"], 3)
self.assertEqual([item["outcome"] for item in snapshot["reads"]], ["exception", "ok", "ok"])
self.assertEqual(snapshot["reads"][0]["exception_code"], 2)
def test_fc23_exception01_allows_following_fc16_without_losing_connection(self):
fc23 = bytes([23]) + struct.pack(">HHHHBH", 20, 1, 20, 1, 2, 42)
fc16 = bytes([16]) + struct.pack(">HHBH", 20, 1, 2, 42)
incoming = adu(fc23, transaction=4) + adu(fc16, transaction=5) + adu(pdu(3, 20, 1), transaction=6)
expected = adu(b"\x97\x01", transaction=4) + adu(pdu(16, 20, 1), transaction=5)
expected += adu(b"\x03\x02\x00\x2a", transaction=6)
self.assertEqual(self.exchange(incoming), expected)
snapshot = self.state.snapshot()
self.assertEqual(snapshot["request_total"], 3)
self.assertEqual(snapshot["effect_total"], 1)
self.assertEqual(snapshot["rejected_write_total"], 1)
self.assertEqual(snapshot["rejected_writes"][0]["function"], 23)
def test_invalid_values_and_unmapped_writes_return_exception03_and02_without_effects(self):
malformed = bytes([16]) + struct.pack(">HHB", 20, 2, 2) + b"\x00\x01"
cases = [(pdu(3, 0, 0), b"\x83\x03"), (pdu(4, 0, 126), b"\x84\x03"),
(b"\x06\x00", b"\x86\x03"), (malformed, b"\x90\x03"),
(pdu(6, 19, 42), b"\x86\x02")]
before = self.state.snapshot()
incoming = b"".join(adu(payload, transaction=i) for i, (payload, _) in enumerate(cases))
expected = b"".join(adu(reply, transaction=i) for i, (_, reply) in enumerate(cases))
self.assertEqual(self.exchange(incoming), expected)
self.assert_no_effects(before)
snapshot = self.state.snapshot()
self.assertEqual(snapshot["request_total"], len(cases))
self.assertEqual(snapshot["rejected_write_total"], 3)
def test_wrong_unit_is_rejected_with_echoed_unit_and_no_effect(self):
before = self.state.snapshot()
self.assertEqual(self.exchange(adu(pdu(6, 20, 42), unit=2)), adu(b"\x86\x0b", unit=2))
self.assert_no_effects(before)
self.assertEqual(self.state.snapshot()["requests"][0]["unit"], 2)
def test_invalid_mbap_and_truncated_frames_do_not_execute_the_payload(self):
invalid = [adu(pdu(6, 20, 42), protocol=1), adu(pdu(6, 20, 42), length=1),
adu(pdu(6, 20, 42), length=255), adu(pdu(6, 20, 42))[:-1], b"\x00\x01"]
before = self.state.snapshot()
for frame in invalid:
with self.subTest(frame=frame):
self.assertEqual(self.exchange(frame), b"")
self.assert_no_effects(before)
self.assertEqual(self.state.snapshot()["request_total"], len(invalid))
self.assertTrue(all(item["outcome"] == "invalid_frame" for item in self.state.snapshot()["requests"]))
def test_response_loss_closes_only_after_one_effect_and_leaves_next_adu_unprocessed(self):
apply_control(self.state, {"action": "drop_next_write_response"})
before = self.state.snapshot()
self.assertEqual(self.exchange(adu(pdu(6, 19, 42))), adu(b"\x86\x02"))
self.assert_no_effects(before)
incoming = adu(pdu(6, 20, 42), transaction=1) + adu(pdu(6, 20, 43), transaction=2)
self.assertEqual(self.exchange(incoming), b"")
snapshot = self.state.snapshot()
self.assertEqual(snapshot["request_total"], 2)
self.assertEqual(snapshot["effect_total"], 1)
self.assertEqual(snapshot["writable"]["20"], 42)
self.assertEqual(snapshot["requests"][-1]["outcome"], "dropped_response")
self.assertEqual(self.exchange(adu(pdu(6, 20, 43))), adu(pdu(6, 20, 43)))
def test_request_read_and_rejected_write_ledgers_are_bounded_and_structural(self):
count = MAX_LEDGER_ITEMS + 3
incoming = b"".join(adu(pdu(3, 13, 1), transaction=i) + adu(pdu(6, 19, 42), transaction=i)
for i in range(count))
self.exchange(incoming, chunk_size=65536)
snapshot = self.state.snapshot()
self.assertEqual(snapshot["request_total"], count * 2)
self.assertEqual(snapshot["read_total"], count)
self.assertEqual(snapshot["rejected_write_total"], count)
self.assertEqual(snapshot["effect_total"], 0)
for key in ("requests", "reads", "rejected_writes"):
self.assertEqual(len(snapshot[key]), MAX_LEDGER_ITEMS)
self.assertEqual(snapshot[key][-1]["sequence"], count * 2 - (1 if key == "reads" else 0))
for record in snapshot[key]:
self.assertLessEqual(set(record), {"sequence", "transaction", "unit", "function", "pdu_length",
"address", "quantity", "outcome", "exception_code"})
if __name__ == "__main__":
unittest.main()