test: model modbus refusals and request accounting in grpc fixture
This commit is contained in:
@@ -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)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user