"""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()