test: validate grpc data connections with local docker and opcua cli

This commit is contained in:
Joseph Doherty
2026-11-17 22:01:26 -05:00
parent 1df29a3124
commit 29fec57fac
194 changed files with 23327 additions and 740 deletions
+112 -19
View File
@@ -1,11 +1,4 @@
"""Evidence validators for the repository CLI's current human-readable output.
These functions validate individual healthy operations, not the complete P10
scenario matrix. A process exit of zero alone is never success. Subscription
summary text must come from a fresh run-owned --summary-file; stdout alone is
insufficient. Integration orchestration and explicit denial/fault expectations
will be connected once the production fixture graph exists.
"""
"""Run the isolated production CLI/probe gate and validate actual operation evidence."""
import argparse
from datetime import datetime
import ipaddress
@@ -22,8 +15,8 @@ class CliGateError(RuntimeError):
def _process_ok(result):
if not isinstance(result, ProcessResult) or result.timed_out or result.returncode != 0 or result.truncated:
raise CliGateError("CLI failed, timed out, or produced truncated evidence")
if not isinstance(result, ProcessResult) or result.cancelled or result.timed_out or result.returncode != 0 or result.truncated:
raise CliGateError("CLI failed, was cancelled, timed out, or produced truncated evidence")
if not isinstance(result.stdout, str) or not result.stdout.strip():
raise CliGateError("CLI stdout evidence is missing")
@@ -45,17 +38,30 @@ def _timestamp(value):
return value
def is_good_status(status):
return re.fullmatch(r"Good(?: \[0x00000000\])?", status) is not None
def parse_notification(line):
match = re.fullmatch(r"\[([^\]]+)\] (.+?) = (.*) \(([^()]*)\)\r?", line)
if match is None:
return None
timestamp, node, value, status = match.groups()
_timestamp(timestamp)
return {"timestamp": timestamp, "node": node, "value": value, "status": status}
def validate_read(result, *, expected_node):
_process_ok(result)
if _field(result.stdout, "Node") != expected_node:
raise CliGateError("CLI read returned a different node")
status = _field(result.stdout, "Status")
if status != "Good":
if not is_good_status(status):
raise CliGateError("CLI read status is not Good")
value = _field(result.stdout, "Value")
if not value:
raise CliGateError("CLI read value is missing")
return {"node": expected_node, "status": status, "value": value,
return {"node": expected_node, "status": "Good", "value": value,
"source_time": _timestamp(_field(result.stdout, "Source Time")),
"server_time": _timestamp(_field(result.stdout, "Server Time"))}
@@ -68,6 +74,44 @@ def validate_write(result, *, expected_node):
return {"node": expected_node, "accepted_value": successes[0][1].strip()}
def validate_connect(result, *, expected_endpoint):
_process_ok(result)
if _field(result.stdout, "Connected to") != expected_endpoint or result.stdout.count("Connection successful.") != 1:
raise CliGateError("CLI connection did not confirm the selected endpoint")
return {"endpoint": expected_endpoint, "server": _field(result.stdout, "Server")}
def validate_browse(result, *, expected_nodes):
_process_ok(result)
found = re.findall(r"^\s*\[(?:Object|Variable|Method)\] .+? \(NodeId: (.+)\)$", result.stdout, re.M)
if not expected_nodes or not set(expected_nodes).issubset(found):
raise CliGateError("CLI browse did not expose every expected child")
return {"nodes": found, "count": len(found)}
def validate_denial(result, *, command, expected_statuses):
if not isinstance(result, ProcessResult) or result.cancelled or result.timed_out or result.truncated:
raise CliGateError("denial evidence was cancelled, timed out, or was truncated")
combined = result.stdout + "\n" + result.stderr
if not expected_statuses or not any(status in combined for status in expected_statuses):
raise CliGateError("CLI did not explicitly report the expected denial")
if command == "write" and "Write successful:" in combined:
raise CliGateError("denied CLI write reported success")
if command == "read" and re.search(r"^Status:[ \t]*Good$", combined, re.M):
raise CliGateError("denied CLI read reported Good")
return {"denied": True, "command": command}
def resolve_node_id(namespace_array, namespace_uri, identifier):
"""Resolve only by an observed NamespaceArray; ambiguous/absent URIs fail."""
if not isinstance(namespace_array, list) or namespace_array.count(namespace_uri) != 1:
raise CliGateError("namespace URI is absent or ambiguous")
index = namespace_array.index(namespace_uri)
if not 0 < index <= 65535 or not isinstance(identifier, str) or not identifier:
raise CliGateError("invalid namespace or string identifier")
return f"ns={index};s={identifier}"
_COUNTERS = {
"total": "Total subscribed",
"ever_bad": " Ever went BAD during window",
@@ -128,7 +172,7 @@ def validate_subscription(result, *, summary_text, expected_nodes, require_chang
if node not in expected:
raise CliGateError("CLI notification refers to an unexpected node")
_timestamp(timestamp)
if status != "Good":
if not is_good_status(status):
raise CliGateError("CLI notification status is not Good")
notifications[node].append(value)
for values in notifications.values():
@@ -140,6 +184,39 @@ def validate_subscription(result, *, summary_text, expected_nodes, require_chang
"summary": file_counts}
def validate_recovery_subscription(result, *, summary_text, expected_node, require_gap, require_held_session=False):
_process_ok(result)
attached = re.findall(r"^Subscribed to (\d+)/(\d+) nodes \(interval: (\d+)ms\)\.", result.stdout, re.M)
if len(attached) != 1 or attached[0][:2] != ("1", "1") or int(attached[0][2]) <= 0 or "FAILED to subscribe" in result.stdout:
raise CliGateError("recovery subscription did not attach its item")
counts = _summary(summary_text)
if counts != _summary(result.stdout) or counts["total"] != 1 or counts["good"] != 1 or counts["bad"] or counts["never"]:
raise CliGateError("CLI subscription did not finish with a recovered Good item")
if require_gap and counts["ever_bad"] != 1:
raise CliGateError("CLI subscription did not observe the remote quality gap")
if require_held_session and re.search(r"Session lost on .+?\. Attempting failover\.\.\.",
result.stdout.split(_SUMMARY_HEADING, 1)[0]):
raise CliGateError("CLI started transport failover before the held subscription finished")
notifications = re.findall(r"^\[([^\]]+)\] (.+?) = (.*) \(([^()]*)\)$", result.stdout, re.M)
good = []
for timestamp, node, value, status in notifications:
if node != expected_node:
raise CliGateError("recovery notification has unexpected node")
_timestamp(timestamp)
if is_good_status(status):
good.append(value)
if len(good) < 2 or len(set(good)) < 2:
raise CliGateError("recovery lacks changing Good values")
if not notifications or not is_good_status(notifications[-1][3]):
raise CliGateError("recovery final notification is not Good")
if require_gap:
bad_indexes = [index for index, entry in enumerate(notifications) if entry[3].startswith("Bad")]
if not bad_indexes or not any(is_good_status(entry[3]) for entry in notifications[:bad_indexes[0]]) or not any(
is_good_status(entry[3]) for entry in notifications[bad_indexes[-1] + 1:]):
raise CliGateError("recovery must have Good notifications before and after a Bad gap")
return {"summary": counts, "good_notifications": len(good)}
def _local_endpoint(url):
try:
parsed = urlsplit(url)
@@ -154,7 +231,7 @@ def _local_endpoint(url):
def build_cli_argv(dll, command, endpoint, credential, *, node=None, value=None,
summary_file=None, duration=30, interval=200, recursive=False, depth=6,
partner_endpoint=None):
partner_endpoint=None, max_age_ms=0):
"""Build portable argv from a published DLL and current supported CLI flags.
Returned argv contains the key solely to pass it to the CLI, which currently
@@ -177,10 +254,16 @@ def build_cli_argv(dll, command, endpoint, credential, *, node=None, value=None,
if not isinstance(node, str) or not node:
raise CliGateError("an explicit resolved NodeId is required")
argv.extend(["-n", node])
if command == "read":
if type(max_age_ms) is not int or not 0 <= max_age_ms <= 30000:
raise CliGateError("read maximum age must be a bounded millisecond value")
if max_age_ms:
argv.extend(["--max-age", str(max_age_ms)])
if command == "write":
if value is None:
raise CliGateError("an explicit write value is required")
argv.extend(["-v", str(value)])
# The physical fixture scalars are UInt16; writing must not require read access.
argv.extend(["-v", str(value), "--type", "UInt16"])
if command == "browse" and recursive:
if type(depth) is not int or depth <= 0:
raise CliGateError("browse depth must be positive")
@@ -200,10 +283,20 @@ def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--run-id", required=True)
parser.add_argument("--scenario", required=True)
parser.parse_args(argv)
print("grpc-data CLI gate: scenario prerequisites not configured; production rig, published CLI, "
"restricted manifest, and concrete scenario assertions are required", file=sys.stderr)
return 2
parser.add_argument("--manifest", type=Path)
parser.add_argument("--cli-dll", type=Path)
parser.add_argument("--probe-dll", type=Path)
arguments = parser.parse_args(argv)
try:
from scenarios import ScenarioRunner
runner = ScenarioRunner(arguments.run_id, manifest_path=arguments.manifest,
cli_dll=arguments.cli_dll, probe_dll=arguments.probe_dll)
report = runner.run(arguments.scenario)
print(__import__("json").dumps(report, sort_keys=True))
return 0 if report["passed"] else 1
except Exception as error:
print("grpc-data CLI gate: " + type(error).__name__ + "; restricted diagnostics retained", file=sys.stderr)
return 2
if __name__ == "__main__":