Dockerize Modbus + AB CIP + S7 test fixtures for reproducibility. Every driver integration simulator now has a pinned Docker image alongside the existing native launcher — Docker is the primary path, native fallbacks kept for contributors who prefer them. Matches the already-Dockerized OpcUaClient/opc-plc pattern from #215 so every fixture in the fleet presents the same compose-up/test/compose-down loop. Reproducibility gain: what used to require a local pip/Python install (Modbus pymodbus, S7 python-snap7) or a per-OS C build from source (AB CIP ab_server from libplctag) now collapses to a Dockerfile + docker compose up. Modbus — new tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.IntegrationTests/Docker/ with Dockerfile (python:3.12-slim-bookworm + pymodbus[simulator]==3.13.0) + docker-compose.yml with four compose profiles (standard / dl205 / mitsubishi / s7_1500) backed by the existing profile JSONs copied under Docker/profiles/ as canonical; native fallback in Pymodbus/ retained with the same JSON set (symlink-equivalent — manual re-sync when profiles change, noted in both READMEs). Port 5020 unchanged so MODBUS_SIM_ENDPOINT + ModbusSimulatorFixture work without code change. Dropped the --no_http CLI arg the old serve.ps1 + compose draft passed — pymodbus 3.13 doesn't recognize it; the simulator's http ui just binds inside the container where nothing maps it out and costs nothing. S7 — new tests/ZB.MOM.WW.OtOpcUa.Driver.S7.IntegrationTests/Docker/ with Dockerfile (python:3.12-slim-bookworm + python-snap7>=2.0) + docker-compose.yml with one s7_1500 compose profile; copies the existing server.py shim + s7_1500.json seed profile; runs python -u server.py ... --port 1102. Native fallback in PythonSnap7/ retained. Port 1102 unchanged. AB CIP — hardest because ab_server is a source-only C tool in libplctag's src/tools/ab_server/. New tests/ZB.MOM.WW.OtOpcUa.Driver.AbCip.IntegrationTests/Docker/ Dockerfile is multi-stage: build stage (debian:bookworm-slim + build-essential + cmake) clones libplctag at a pinned tag + cmake --build build --target ab_server; runtime stage (debian:bookworm-slim) copies just the binary from /src/build/bin_dist/ab_server. docker-compose.yml ships four compose profiles (controllogix / compactlogix / micro800 / guardlogix) with per-family ab_server CLI args matching AbServerProfile.cs. AbServerFixture updated: tries TCP probe on 127.0.0.1:44818 first (Docker path) + spawns the native binary only as fallback when no listener is there. AB_SERVER_ENDPOINT env var supported for pointing at a real PLC. AbServerFact/Theory attributes updated to IsServerAvailable() which accepts any of: live listener on 44818, AB_SERVER_ENDPOINT set, or binary on PATH. Required two CLI-compat fixes to ab_server's argument expectations that the existing native profile never caught because it was never actually run at CI: --plc is case-sensitive (ControlLogix not controllogix), CIP tags need [size] bracket notation (DINT[1] not bare DINT), ControlLogix also requires --path=1,0. Compose files carry the corrected flags; the existing native-path AbServerProfile.cs was never invoked in practice so we don't rewrite it here. Micro800 now uses the --plc=Micro800 mode rather than falling back to ControlLogix emulation — ab_server does have the dedicated mode, the old Notes saying otherwise were wrong. Updated docs: three fixture coverage docs (Modbus-Test-Fixture.md, S7-Test-Fixture.md, AbServer-Test-Fixture.md) flip their "What the fixture is" section from native-only to Docker-primary-with-native-fallback; dev-environment.md §Resource Inventory replaces the old ambiguous "Docker Desktop + ab_server native" mix with four per-driver rows (each listing the image, compose file, compose profiles, port, credentials) + a new Docker fixtures — quick reference subsection giving the one-line docker compose -f <…> --profile <…> up for each driver + the env-var override names + the native fallback install recipes. drivers/README.md coverage map table updated — Modbus/AB CIP/S7 entries now read "Dockerized …" consistent with OpcUaClient's line. Verified end-to-end against live containers: Modbus DL205 smoke 1/1, S7 3/3, AB CIP ControlLogix 4/4 (all family theory rows). Container lifecycle clean (up/test/down, no leaked state). Every fixture keeps its skip-when-absent probe + env-var endpoint override so dotnet test on a fresh clone without Docker running still gets a green run.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-04-20 12:09:44 -04:00
parent 3b3e814855
commit 6609141493
24 changed files with 1258 additions and 38 deletions

View File

@@ -0,0 +1,24 @@
# python-snap7 S7 server container for the S7 integration suite.
#
# python-snap7 wraps the upstream snap7 C library; the pip install pulls
# platform-specific binaries automatically on Debian-based images. No build
# step needed — unlike ab_server which needs compiling from source.
FROM python:3.12-slim-bookworm
LABEL org.opencontainers.image.source="https://github.com/dohertj2/lmxopcua" \
org.opencontainers.image.description="python-snap7 S7 simulator for OtOpcUa S7 driver integration tests"
RUN pip install --no-cache-dir "python-snap7>=2.0"
WORKDIR /fixtures
# server.py is the Python shim that loads a JSON profile + starts the
# snap7.server.Server; profiles/ carries the seed definitions.
COPY server.py /fixtures/
COPY profiles/ /fixtures/
EXPOSE 1102
# -u for unbuffered stdout so `docker logs` tails the "seeded DB…"
# diagnostics without a buffer-flush delay.
CMD ["python", "-u", "/fixtures/server.py", "/fixtures/s7_1500.json", "--port", "1102"]

View File

@@ -0,0 +1,100 @@
# S7 integration-test fixture — python-snap7 (Docker)
[python-snap7](https://github.com/gijzelaerr/python-snap7) `Server` class
wrapped in a pinned `python:3.12-slim-bookworm` image. Docker is the
primary launcher; the native-Python fallback under
[`../PythonSnap7/`](../PythonSnap7/) is kept for contributors who prefer
to avoid Docker locally.
| File | Purpose |
|---|---|
| [`Dockerfile`](Dockerfile) | `python:3.12-slim-bookworm` + `python-snap7>=2.0` + the server shim + the profile JSONs |
| [`docker-compose.yml`](docker-compose.yml) | One service per profile; currently only `s7_1500` |
| [`server.py`](server.py) | Same Python shim the native fallback uses — copy kept in the build context |
| [`profiles/*.json`](profiles/) | Area-seed definitions (DB1 / MB layouts with typed seeds) |
## Run
From the repo root:
```powershell
docker compose -f tests\ZB.MOM.WW.OtOpcUa.Driver.S7.IntegrationTests\Docker\docker-compose.yml --profile s7_1500 up
```
Detached + stop:
```powershell
docker compose -f tests\...\Docker\docker-compose.yml --profile s7_1500 up -d
docker compose -f tests\...\Docker\docker-compose.yml --profile s7_1500 down
```
## Endpoint
- Default: `localhost:1102` (non-privileged; sidesteps Windows Firewall
prompt + Linux's root-required bind on port 102).
- Override with `S7_SIM_ENDPOINT` to point at a real S7 CPU on `:102`.
- The driver's S7DriverOptions.Port flows through S7netplus's 5-arg
`Plc(CpuType, host, port, rack, slot)` ctor so the non-standard port
works end-to-end.
## Run the integration tests
In a separate shell with the container up:
```powershell
cd C:\Users\dohertj2\Desktop\lmxopcua
dotnet test tests\ZB.MOM.WW.OtOpcUa.Driver.S7.IntegrationTests
```
`Snap7ServerFixture` probes `localhost:1102` at collection init + records
a `SkipReason` when unreachable, so tests stay green on a fresh clone
without Docker running.
## What's encoded in `profiles/s7_1500.json`
DB1 (1024 bytes) + MB (256 bytes) with typed seeds at known offsets:
| Address | Type | Seed | Purpose |
|---|---|---|---|
| `DB1.DBW0` | u16 | `4242` | read-back probe |
| `DB1.DBW10` | i16 | `-12345` | smoke i16 read |
| `DB1.DBD20` | i32 | `1234567890` | smoke i32 read |
| `DB1.DBD30` | f32 | `3.14159` | smoke f32 read (big-endian) |
| `DB1.DBX50.3` | bool | `true` | smoke bool read at bit 3 |
| `DB1.DBW100` | u16 | `0` | scratch for write-then-read |
| `DB1.STRING[200]` | S7 STRING | `"Hello"` | S7 STRING read |
| `MW0` | u16 | `1` | `S7ProbeOptions.ProbeAddress` default |
Seed types supported: `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `f32`,
`bool` (with `"bit": 0..7`), `ascii` (S7 STRING).
## Known limitations
From the `snap7.server.Server` docstring upstream:
> "Legacy S7 server implementation. Emulates a Siemens S7 PLC for testing
> and development purposes. [...] pure Python emulator implementation that
> simulates PLC behaviour for protocol compliance testing rather than
> full industrial-grade functionality."
Not exercised here — needs a lab rig:
- S7-1500 Optimized-DB symbolic access
- PG / OP / S7-Basic session-type differentiation
- PUT/GET-disabled-by-default enforcement
See [`docs/drivers/S7-Test-Fixture.md`](../../../docs/drivers/S7-Test-Fixture.md)
for the full coverage map.
## Native-Python fallback
[`../PythonSnap7/`](../PythonSnap7/) has the same `server.py` + profile
JSON launched via local Python install (`pip install python-snap7`).
Kept for contributors who prefer native.
## References
- [python-snap7 GitHub](https://github.com/gijzelaerr/python-snap7)
- [`../PythonSnap7/README.md`](../PythonSnap7/README.md) — native launcher
- [`docs/drivers/S7-Test-Fixture.md`](../../../docs/drivers/S7-Test-Fixture.md) — coverage map
- [`docs/v2/dev-environment.md`](../../../docs/v2/dev-environment.md) §Docker fixtures

View File

@@ -0,0 +1,20 @@
# S7 integration-test fixture — python-snap7 server.
#
# One service per profile (only s7_1500 ships today; add S7-1200 / S7-300
# as new profile JSONs drop into profiles/). All bind :1102 on the host;
# run one at a time.
#
# Usage:
# docker compose --profile s7_1500 up
services:
s7_1500:
profiles: ["s7_1500"]
build:
context: .
dockerfile: Dockerfile
image: otopcua-python-snap7:1.0
container_name: otopcua-python-snap7-s7_1500
restart: "no"
ports:
- "1102:1102"
command: ["python", "-u", "/fixtures/server.py", "/fixtures/s7_1500.json", "--port", "1102"]

View File

@@ -0,0 +1,35 @@
{
"_description": "S7-1500 profile — single DB1 (1024 bytes) + MB (256 bytes) with well-known seeds at named offsets for the smoke + byte-order + string tests. Big-endian Siemens wire order throughout.",
"areas": [
{
"area": "DB",
"index": 1,
"size": 1024,
"seeds": [
{ "_desc": "DB1.DBW0 — read-back probe, S7Driver default ProbeAddress target is MW0; this shadows it",
"offset": 0, "type": "u16", "value": 4242 },
{ "_desc": "DB1.DBW10 — i16 smoke value for SmokeI16 read path",
"offset": 10, "type": "i16", "value": -12345 },
{ "_desc": "DB1.DBD20 — i32 smoke value for SmokeI32 read path",
"offset": 20, "type": "i32", "value": 1234567890 },
{ "_desc": "DB1.DBD30 — f32 smoke value for SmokeF32 read path (IEEE-754 big-endian)",
"offset": 30, "type": "f32", "value": 3.14159 },
{ "_desc": "DB1.DBX50.3 — bool bit at byte-50 bit-3 for SmokeBool read path",
"offset": 50, "type": "bool", "value": true, "bit": 3 },
{ "_desc": "DB1.DBW100 — scratch for write-then-read round-trip tests; seeded 0",
"offset": 100, "type": "u16", "value": 0 },
{ "_desc": "DB1.STRING[200] — S7 string 'Hello' (max 32, cur 5)",
"offset": 200, "type": "ascii", "value": "Hello", "max_len": 32 }
]
},
{
"area": "MK",
"index": 0,
"size": 256,
"seeds": [
{ "_desc": "MW0 — probe target for S7ProbeOptions.ProbeAddress default",
"offset": 0, "type": "u16", "value": 1 }
]
}
]
}

View File

@@ -0,0 +1,150 @@
"""python-snap7 S7 server for integration tests.
Reads a JSON profile from argv[1], allocates bytearrays for each declared area
(DB / MB / EB / AB), poke-seeds values at declared offsets, then starts the
snap7 Server on the configured port + blocks until Ctrl+C. Shape intentionally
mirrors the pymodbus `serve.ps1 + *.json` pattern one directory over so
someone familiar with the Modbus fixture can read this without re-learning.
The snap7.server.Server class is the MIT-licensed S7 PLC emulator wrapped by
python-snap7 (https://github.com/gijzelaerr/python-snap7). Its own docstring
admits "protocol compliance testing rather than full industrial-grade
functionality" — good enough for ISO-on-TCP wire-level round-trip but NOT
for S7-1500 Optimized-DB symbolic access, SCL variant-specific behaviour, or
PG/OP/S7-Basic session differentiation.
"""
from __future__ import annotations
import argparse
import ctypes
import json
import signal
import sys
import time
from pathlib import Path
# python-snap7 installs as `snap7` package; Server class lives under `snap7.server`.
import snap7
from snap7.type import SrvArea
# Map JSON area names → SrvArea enum values. PE = inputs (I/E), PA = outputs
# (Q/A), MK = memory (M), DB = data blocks, TM = timers, CT = counters.
AREA_MAP: dict[str, int] = {
"PE": SrvArea.PE,
"PA": SrvArea.PA,
"MK": SrvArea.MK,
"DB": SrvArea.DB,
"TM": SrvArea.TM,
"CT": SrvArea.CT,
}
def seed_buffer(buf: bytearray, seeds: list[dict]) -> None:
"""Poke seed values into the area buffer at declared byte offsets.
Each seed is {"offset": int, "type": str, "value": int|float|bool|str}
where type ∈ {u8, i8, u16, i16, u32, i32, f32, bool, ascii}. Endianness is
big-endian (Siemens wire format).
"""
for seed in seeds:
off = int(seed["offset"])
t = seed["type"]
v = seed["value"]
if t == "u8":
buf[off] = int(v) & 0xFF
elif t == "i8":
buf[off] = int(v) & 0xFF
elif t == "u16":
buf[off:off + 2] = int(v).to_bytes(2, "big", signed=False)
elif t == "i16":
buf[off:off + 2] = int(v).to_bytes(2, "big", signed=True)
elif t == "u32":
buf[off:off + 4] = int(v).to_bytes(4, "big", signed=False)
elif t == "i32":
buf[off:off + 4] = int(v).to_bytes(4, "big", signed=True)
elif t == "f32":
import struct
buf[off:off + 4] = struct.pack(">f", float(v))
elif t == "bool":
bit = int(seed.get("bit", 0))
if bool(v):
buf[off] |= (1 << bit)
else:
buf[off] &= ~(1 << bit) & 0xFF
elif t == "ascii":
# Siemens STRING type: byte 0 = max length, byte 1 = current length,
# bytes 2+ = payload. Seeds supply the payload text; we fill max/cur.
payload = str(v).encode("ascii")
max_len = int(seed.get("max_len", 254))
buf[off] = max_len
buf[off + 1] = len(payload)
buf[off + 2:off + 2 + len(payload)] = payload
else:
raise ValueError(f"Unknown seed type '{t}'")
def main() -> int:
parser = argparse.ArgumentParser(description="python-snap7 S7 server for integration tests")
parser.add_argument("profile", help="Path to profile JSON")
parser.add_argument("--port", type=int, default=1102, help="TCP port (default 1102 non-privileged)")
args = parser.parse_args()
profile_path = Path(args.profile)
if not profile_path.is_file():
print(f"profile not found: {profile_path}", file=sys.stderr)
return 1
with profile_path.open() as f:
profile = json.load(f)
server = snap7.server.Server()
# Keep bytearray refs alive for the server's lifetime — snap7 doesn't copy
# the buffer, it takes a pointer. Letting GC collect would corrupt reads.
buffers: list[bytearray] = []
for area_decl in profile.get("areas", []):
area_name = area_decl["area"]
if area_name not in AREA_MAP:
print(f"unknown area '{area_name}' (expected one of {list(AREA_MAP)})", file=sys.stderr)
return 1
index = int(area_decl.get("index", 0)) # DB number for DB area, 0 for MK/PE/PA
size = int(area_decl["size"])
buf = bytearray(size)
seed_buffer(buf, area_decl.get("seeds", []))
buffers.append(buf)
# register_area takes (area, index, c-array); we wrap the bytearray
# into a ctypes char array so the native lib can take &buf[0].
arr_type = ctypes.c_char * size
arr = arr_type.from_buffer(buf)
server.register_area(AREA_MAP[area_name], index, arr)
print(f" seeded {area_name}{index} size={size} seeds={len(area_decl.get('seeds', []))}")
port = int(args.port)
print(f"Starting python-snap7 server on TCP {port} (Ctrl+C to stop)")
server.start(tcp_port=port)
stop = {"sig": False}
def _handle(*_a):
stop["sig"] = True
signal.signal(signal.SIGINT, _handle)
try:
signal.signal(signal.SIGTERM, _handle)
except Exception:
pass # SIGTERM not on all platforms
try:
while not stop["sig"]:
time.sleep(0.25)
finally:
print("stopping python-snap7 server")
try:
server.stop()
except Exception:
pass
return 0
if __name__ == "__main__":
sys.exit(main())