test: complete grpc data solution validation

This commit is contained in:
Joseph Doherty
2026-11-17 22:01:27 -05:00
parent 4cf3acb1c5
commit 9c8c1054fa
39 changed files with 37835 additions and 160 deletions
@@ -0,0 +1,104 @@
# Local whole-solution prerequisites
The explicit local mode of `scripts/ci/integration-fixtures.sh` dispatches to
`local_fixtures.py` before the legacy CI helper reads defaults or performs cleanup.
It never starts any existing Compose stack. Existing fixture Dockerfiles, seeded
SQL/configuration files and JSON-array service commands are reused as inputs.
The final coordinator runs the fake Docker ownership tests before actual startup:
```bash
python3 -m unittest discover -s scripts/validation/grpc-data/tests -p test_fixture_ownership.py
```
Use a fresh suffix and absolute output file for every run. The final runner passes
these variables directly to the helper; printed output must never be evaluated.
```bash
CI_FIXTURE_LOCAL_OWNED=1 \
CI_FIXTURE_SUFFIX=grpc-data-final-unique \
CI_FIXTURE_ENV_JSON=/absolute/private/run/fixture-environment.json \
FIXTURE_HOST=127.0.0.1 \
bash scripts/ci/integration-fixtures.sh up
```
Startup writes a JSON dictionary of test environment variables at the requested
path with mode `0600`. The ownership journal is that path plus `.manifest.json`;
the private directory for logs, generated certificates and profile environment
dictionaries is that path plus `.d` (`0700`). Standard output contains only a
redacted status and the environment output path. Credentials are randomly
generated for this run. The ordinary SQL fixture is separate from the SQL
blackhole fixture and from the P10 rig's SQL instance.
The default service set includes SQL Server, PostgreSQL, MySQL, Oracle Free,
QuestDB, ordinary and NAT opc-plc, GLAuth, python-snap7, FOCAS mock, the MTConnect
agent and SHDR adapter, authenticated TLS/plain Mosquitto and its retained JSON
publisher, all six Modbus profiles and all seven AB CIP/PCCC family profiles.
SQL Server and Oracle run as `linux/amd64` when emulation is needed. Images built
from repository Dockerfiles receive unique run labels and image IDs. Published
images pulled as dependencies are retained in the ordinary image cache.
Each run creates its own labelled Docker bridge. Every published port binds to
`127.0.0.1`. Docker allocates host ports; ordinary
opc-plc uses a candidate allocated locally for both advertised and published port.
Docker bind failures fail startup without removing a pre-existing resource.
Container creation intent and immutable ID are journaled before start, so a
failed start or interrupted setup can be cleaned up by the same run.
Run `down` with the same four inputs after success or failed setup. Cleanup first
validates the entire recorded inventory against the current local Docker context
and exact owner/project/creation-instance labels. It then removes only the
recorded IDs, rechecking immediately before removal. Pending creation records are
recovered by exact name lookup, followed by ownership and ID validation; names
are never deletion targets. Daemon errors are not treated as absent resources.
The helper never uses Compose down, wildcard deletion, global prune or an
unverified container name. Private evidence and secrets remain restricted for
the coordinator to retain or dispose of under its run directory policy.
`logs` uses the same manifest and writes bounded container-log tails into the
private command logs. Each subprocess has a duration/output bound. A failure
prints no captured output or command arguments; inspect the private logs locally.
The base environment enables standard Modbus plus RTU, ControlLogix, and all
three PCCC families through their explicit per-family ports. Other Modbus and AB
CIP profile environments are written to `.d/profile-environments.json`. After
the unfiltered full-solution command, the coordinator runs the corresponding
integration project with each profile environment. Every AB overlay retains the
same owned ControlLogix companion endpoint for tests authored for ControlLogix.
The variant smoke tests dial the selected CompactLogix, Micro800 or GuardLogix
endpoint. The runner validates both literal loopback endpoints and requires
distinct ports across the four simulators. The read-only differential runs
against ControlLogix with the general write fixtures closed.
The process-wide SDK lifecycle diagnostic runs its exact 90-second case in a
fresh test process. Its discovery, TRX and diagnostic JSONL are included in the
final result inventory. The unfiltered run still executes the folder-event
performance tests and the short saturation-observer protocol controls. A
profile-specific skip counts as coverage only when its matching test ran. `CI_FIXTURE_SERVICES` can
select a comma-separated subset for focused fixture diagnosis; a subset is not
the whole-solution prerequisites gate.
Generated S7 pause/restart commands and SQL blackhole controls use the same
helper's `control` action. It revalidates local context, restricted manifest,
recorded service ID and ownership labels before each verb. The local Host probe
tests require `HOST_PROBE_OPCUA_ENDPOINT` from the P10 rig's actual OtOpcUa OPC
listener. No proprietary Galaxy gateway is substituted by another protocol;
its exact live test remains explicitly unavailable when no local backend exists.
Refresh `fixture-environment-map.json` with `python3
scripts/validation/grpc-data/fixture_inventory.py` after the candidate changes.
This source inventory includes every test project, linked source, category and
environment switch. Discovery/TRX is still required for concrete theory names,
per-assembly execution, every skip reason and the final availability decision.
ODBC host drivers and the built ScriptWorker are software prerequisites to
verify separately. The map lists explicit Windows/native/proprietary/live
requirements and long-running opt-in decisions; source presence never proves
execution.
When the coordinator has installed a compatible native PostgreSQL ODBC driver,
pass its existing absolute library path as `CI_FIXTURE_ODBC_DRIVER` during `up`.
The helper validates that input and writes `SQL_ODBC_CONNECTION_STRING` using
only this run's seeded PostgreSQL endpoint and generated credentials. It never
inherits an ODBC connection string or uses a driver registration that could hide
an external endpoint. The coordinator still verifies the native driver manager
and .NET ODBC runtime through the applicable tests.
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""Refresh the final gate's source inventory without discovery, builds or network.
Source method names are preparation evidence only. The final runner must reconcile
them with discovery/TRX, including theory rows and runtime skip reasons.
"""
from __future__ import annotations
import glob
import hashlib
import json
from pathlib import Path
import re
import xml.etree.ElementTree as ET
ROOT = Path(__file__).resolve().parents[3]
OUTPUT = Path(__file__).with_name("fixture-environment-map.json")
PREFIXES = ("OTOPCUA_", "SQL_", "AB_", "MODBUS_", "S7_", "TWINCAT_", "HEIDENHAIN_", "HISTGW_", "GALAXY_", "MXGW_", "MQTT_", "MTCONNECT_", "OPCUA_", "HISTORIAN_", "HOST_PROBE_", "GRPC_", "D1_", "AKKA_", "BENCH_", "DOTNET_", "CI_", "ODBC_")
def quoted_environment_names(text):
# Includes named constants used as GetEnvironmentVariable arguments and the
# small Env(name)/ReadInt(name) helpers; no inherited values are read.
constants = {match for match in re.findall(r'"([A-Z][A-Z0-9_]{2,})"', text) if match.startswith(PREFIXES)}
literals = set(re.findall(r'GetEnvironmentVariable\(\s*"([^"\n]+)"', text))
return sorted(constants | literals)
def source_methods(text):
namespace = re.search(r"^namespace\s+([\w.]+)", text, re.M)
name = namespace[1] if namespace else ""
# Match test attributes through their following method declaration. This is
# intentionally labelled source names: discovery owns concrete theory rows.
methods = []
for match in re.finditer(r"(?:\[(?:\w*Fact|\w*Theory)(?:\([^\]]*\))?\][\s\S]*?)\bpublic\s+(?:async\s+)?(?:Task(?:<[^>]*>)?|ValueTask|void)\s+(\w+)\s*\(", text):
preceding = text[:match.start()]
classes = list(re.finditer(r"^\s*(?:(?:public|internal|private|protected|abstract|sealed|partial|static)\s+)*class\s+(\w+)", preceding, re.M))
if classes:
methods.append(name + "." + classes[-1][1] + "." + match[1])
return sorted(set(methods))
GROUPS = [
{"id": "odbc-software", "projects": ["Driver.Sql.IntegrationTests"], "services": ["postgres"], "variables": ["SQL_ODBC_CONNECTION_STRING"], "policy": "required when coordinator supplies installed local PostgreSQL driver through CI_FIXTURE_ODBC_DRIVER; helper builds the connection using only owned seeded PG, explicit absolute driver path and fresh password; host native driver manager and .NET ODBC assets verified by actual tests"},
{"id": "sql-configuration", "projects": ["Configuration.Tests", "ControlPlane.Tests", "AdminUI.Tests"], "services": ["sql"], "variables": ["OTOPCUA_CONFIG_TEST_SERVER", "OTOPCUA_CONFIG_TEST_SA_PASSWORD"], "policy": "required-before-discovery; remove OTOPCUA_UNIT_ONLY_DISCOVERY"},
{"id": "sql-historian", "projects": ["Driver.Historian.SqlServer.IntegrationTests"], "services": ["sql"], "variables": ["HISTORIAN_SQL_TEST_CONNECTION"], "policy": "required; disposable database administration"},
{"id": "questdb", "projects": ["Driver.Historian.QuestDb.IntegrationTests"], "services": ["questdb"], "variables": ["HISTORIAN_QUESTDB_TEST_CONNECTION", "HISTORIAN_QUESTDB_STRESS_SECONDS"], "policy": "required; explicit stress-duration decision in final report"},
{"id": "sql-poll", "projects": ["Driver.Sql.IntegrationTests"], "services": ["sql", "postgres", "mysql", "oracle", "sql-blackhole"], "variables": ["SQL_TEST_ENDPOINT", "SQL_TEST_USER", "SQL_TEST_PASSWORD", "SQL_PG_ENDPOINT", "SQL_PG_USER", "SQL_PG_PASSWORD", "SQL_MYSQL_ENDPOINT", "SQL_MYSQL_USER", "SQL_MYSQL_PASSWORD", "SQL_ORACLE_ENDPOINT", "SQL_ORACLE_USER", "SQL_ORACLE_PASSWORD", "SQL_ORACLE_SERVICE", "SQL_BLACKHOLE_ENDPOINT", "SQL_BLACKHOLE_USER", "SQL_BLACKHOLE_PASSWORD", "SQL_BLACKHOLE_CONTAINER_ID", "SQL_BLACKHOLE_FIXTURE_OWNER", "SQL_BLACKHOLE_ENV_JSON", "SQL_BLACKHOLE_CONTROL_SCRIPT"], "policy": "required; seed PG/MySQL/Oracle; blackhole has separate SQL service; clear Sql__ConnectionStrings__Fixture and SQL_BLACKHOLE_DOCKER_SSH"},
{"id": "opc", "projects": ["Driver.OpcUaClient.IntegrationTests", "Driver.OpcUaClient.Browser.IntegrationTests"], "services": ["opc", "opc-nat"], "variables": ["OPCUA_SIM_ENDPOINT", "OPCUA_NAT_ENDPOINT", "OPCUA_NAT_SERVER_CERT"], "policy": "required; normal advertised port equals allocated port; NAT advertises unreachable .invalid; fresh private-directory public cert"},
{"id": "modbus", "projects": ["Driver.Modbus.IntegrationTests"], "services": ["modbus-standard", "modbus-dl205", "modbus-mitsubishi", "modbus-s7-1500", "modbus-exception-injection", "modbus-rtu-over-tcp"], "variables": ["MODBUS_SIM_ENDPOINT", "MODBUS_SIM_PROFILE", "MODBUS_RTU_SIM_ENDPOINT"], "policy": "required; full run standard+RTU; focused project overlays dl205/mitsubishi/s7_1500/exception_injection from profile-environments.json"},
{"id": "s7", "projects": ["Driver.S7.IntegrationTests"], "services": ["s7"], "variables": ["S7_SIM_ENDPOINT", "S7_SIM_ALLOW_WRITES", "S7_RECONNECT_BOUNCE_CMD", "S7_TIMEOUT_OUTAGE_START_CMD", "S7_TIMEOUT_OUTAGE_STOP_CMD"], "policy": "required; writes enabled only on owned simulator; generated control commands verify manifest/ID/labels/local context"},
{"id": "ab-cip", "projects": ["Driver.AbCip.IntegrationTests"], "services": ["ab-controllogix", "ab-compactlogix", "ab-micro800", "ab-guardlogix"], "variables": ["AB_SERVER_ENDPOINT", "AB_SERVER_COMPOSE_PROFILE", "AB_SERVER_PROFILE", "AB_SERVER_ALLOW_WRITES"], "policy": "required; patched source build; full run controllogix and focused project overlays remaining profiles; no hardware/differential controls inherited"},
{"id": "ab-legacy", "projects": ["Driver.AbLegacy.IntegrationTests"], "services": ["legacy-slc500", "legacy-micrologix", "legacy-plc5"], "variables": ["AB_LEGACY_ENDPOINT", "AB_LEGACY_CIP_PATH", "AB_LEGACY_SLC500_ENDPOINT", "AB_LEGACY_MICROLOGIX_ENDPOINT", "AB_LEGACY_PLC5_ENDPOINT", "AB_SERVER_ALLOW_WRITES"], "policy": "required; all per-family endpoints explicit; no AB_LEGACY_COMPOSE_PROFILE pin in base run, discover full family matrix"},
{"id": "focas", "projects": ["Driver.FOCAS.IntegrationTests"], "services": ["focas"], "variables": ["OTOPCUA_FOCAS_SIM_ENDPOINT", "OTOPCUA_FOCAS_SIM_PROFILE"], "policy": "required; managed wire with mock native-Ethernet responder; tests load per-series profiles through local admin API"},
{"id": "mtconnect", "projects": ["Driver.MTConnect.IntegrationTests"], "services": ["mtconnect-adapter", "mtconnect"], "variables": ["MTCONNECT_AGENT_ENDPOINT", "MTCONNECT_WRITE_TARGET"], "policy": "required; official pinned agent plus live SHDR feeder and dedicated fixture_writeback target"},
{"id": "mqtt", "projects": ["Driver.Mqtt.IntegrationTests"], "services": ["mqtt", "mqtt-publisher"], "variables": ["MQTT_FIXTURE_ENDPOINT", "MQTT_FIXTURE_PLAIN_ENDPOINT", "MQTT_FIXTURE_USERNAME", "MQTT_FIXTURE_PASSWORD", "MQTT_FIXTURE_CA_CERT", "MQTT_FIXTURE_TOPIC_PREFIX"], "policy": "required; fresh loopback TLS CA+leaf and password; verify authenticated TLS + retained publisher seed; Sparkplug tests own in-process edge nodes"},
{"id": "host-real-mode", "projects": ["Host.IntegrationTests"], "services": ["sql", "ldap"], "variables": ["OTOPCUA_HARNESS_USE_SQL", "OTOPCUA_HARNESS_SQL_HOST", "OTOPCUA_HARNESS_SQL_PASSWORD", "OTOPCUA_HARNESS_USE_LDAP", "OTOPCUA_HARNESS_LDAP_HOST", "OTOPCUA_HARNESS_LDAP_PORT", "HOST_PROBE_OPCUA_ENDPOINT", "OTOPCUA_LOCAL_FIXTURE_MODE"], "policy": "required local real SQL/LDAP; HOST_PROBE_OPCUA_ENDPOINT bridges owned P10 central OPC listener; all protocol probes loopback before reachability"},
{"id": "scriptworker", "projects": ["ScriptWorker.Tests"], "services": [], "variables": ["OTOPCUA_SCRIPTWORKER_TEST_PATH"], "policy": "required built platform-matching local executable and native dependencies; default beside-test worker acceptable when built by project reference; Windows isolation cases separately unavailable"},
{"id": "scripting-child-process", "projects": ["Core.Scripting.Tests"], "services": [], "variables": ["OTOPCUA_RECURSION_CHILD_SCENARIO", "OTOPCUA_RECURSION_CHILD_RESULT"], "policy": "do not inherit either switch into the parent final process; containment test owns child process, temp output and bounded recursion/crash scenario"},
]
UNAVAILABLE = [
{"id": "twincat", "projects": ["Driver.TwinCAT.IntegrationTests"], "file_pattern": "*", "variables": ["TWINCAT_TARGET_HOST", "TWINCAT_TARGET_NETID", "TWINCAT_TARGET_PORT"], "requires": "Local Windows TwinCAT XAR runtime with valid trial/license, native ADS support, bilateral AMS routes and fixture PLC program; run that platform gate with exact discovered test names."},
{"id": "heidenhain-live", "projects": ["Driver.Heidenhain.Tests"], "file_pattern": "*HeidenhainLiveIntegrationTests.cs", "variables": ["HEIDENHAIN_LSV2_HOST", "HEIDENHAIN_LSV2_PORT", "OTOPCUA_HEIDENHAIN_INSPECT_PASSWORD"], "requires": "Owned Heidenhain controller or licensed matching simulator exposing LSV2 with INSPECT credentials; in-process protocol tests remain runnable separately."},
{"id": "galaxy-live", "projects": ["Driver.Galaxy.Tests", "Host.IntegrationTests"], "file_pattern": "*", "method_exclusions": ["Modbus_", "OpcUaClient_", "S7_", "AbCip_", "Galaxy_Red_"], "variables": ["MXGW_ENDPOINT", "GALAXY_MXGW_API_KEY", "GALAXY_904_ACK_USER", "GALAXY_904_ACK_PASSWORD", "GALAXY_904_ALARM_REF", "HOST_PROBE_GALAXY_ENDPOINT"], "requires": "Local licensed Galaxy runtime and MxAccessGateway with writable meter/alarm scenario and scoped API key; no equivalent production backend fixture is supplied in this repository. Only live methods explicitly gated by these variables are unavailable; unit methods remain required."},
{"id": "historian-gateway-live", "projects": ["Driver.Historian.Gateway.Tests"], "file_pattern": "*Live*.cs", "variables": ["HISTGW_GATEWAY_ENDPOINT", "HISTGW_GATEWAY_APIKEY", "HISTGW_TEST_TAG", "HISTGW_WRITE_SANDBOX_TAG", "HISTGW_BOOL_SANDBOX_TAG", "HISTGW_ALARM_SOURCE", "HISTGW_GATEWAY_ALLOW_UNTRUSTED"], "requires": "Local HistorianGateway hosting service with licensed/writable history/event backend, scoped key and dedicated sandbox tags; repository contains no production backend hosting fixture."},
{"id": "aveva-live", "projects": ["OpcUaServer.IntegrationTests"], "file_pattern": "*Aveva*LiveGateTests.cs", "variables": ["OTOPCUA_AVEVA_GATE_900", "OTOPCUA_AVEVA_GATE_TAGS", "OTOPCUA_AVEVA_GATE_WINDOWS", "OTOPCUA_AVEVA_GATE_EVENT_SOURCES", "OTOPCUA_AVEVA_GATE_EVENT_WINDOW", "OTOPCUA_AVEVA_GATE_GALAXY_REFS", "OTOPCUA_AVEVA_GATE_LABEL", "OTOPCUA_AVEVA_GATE_OUT", "OTOPCUA_AVEVA_GATE_STRICT_ENDPOINT", "OTOPCUA_AVEVA_GATE_STRICT_CONTAINER", "OTOPCUA_AVEVA_GATE_STRICT_SET_CEILING"], "requires": "Local licensed AVEVA Historian/Galaxy event backend and compatible HistorianGateway with configured history windows, alarms and scoped keys; strict container control additionally requires exact owned ID/labels."},
{"id": "ab-proprietary-emulate", "projects": ["Driver.AbCip.IntegrationTests"], "file_pattern": "*Emulate*Tests.cs", "variables": ["AB_SERVER_PROFILE"], "requires": "Owned licensed Rockwell Emulate controller with authored UDT/array/alarm project; ab_server has no equivalent structured-tag/type metadata. Keep AB_SERVER_PROFILE=abserver; simulator cases remain required."},
{"id": "ab-controller-evidence", "projects": ["Driver.AbCip.IntegrationTests"], "file_pattern": "*", "variables": ["AB_DIFF_ENDPOINT", "AB_DIFF_PATH", "AB_DIFF_FAMILY", "AB_DIFF_TAGS", "AB_DIFF_COUNT_OPENS", "AB_DIFF_MAX_TAGS", "AB_DIFF_MAX_TEMPLATES", "AB_DIFF_PACE_MS", "AB_HW_WRITE_APPROVED", "AB_HW_WRITE_GATEWAY", "AB_HW_WRITE_STRING_TAG", "AB_HW_WRITE_DRYRUN", "AB_HW_WRITE_GAP_SECONDS", "AB_EVID_IDLE", "AB_EVID_BROWSE", "AB_EVID_MIX", "AB_LAT_TAGS", "AB_LAT_PASSES", "AB_LAT_PASS_GAP_MS", "AB_LAT_ENFORCE"], "requires": "Owned controller with required differential/browse/meter tags and separately authorized physical write sandbox. No hardware controls or endpoints are inherited; local simulator tests remain required."},
{"id": "s7-real-timer-counter", "projects": ["Driver.S7.IntegrationTests"], "file_pattern": "*SpanReadTests.cs", "method_inclusions": ["Timer_and_counter_decode_the_seeded_values_at_their_device_numbers"], "variables": ["S7_TIMER_NUMBER_ADDRESSING"], "requires": "Owned S7 CPU implementing native timer/counter number addressing; python-snap7 simulator deliberately has byte-addressed timer memory. Only exact opt-in methods unavailable."},
{"id": "odbc", "projects": ["Driver.Sql.IntegrationTests"], "file_pattern": "*OdbcReadTests.cs", "variables": ["SQL_ODBC_CONNECTION_STRING"], "requires": "Host ODBC driver manager plus compatible installed vendor driver for the seeded owned backend. This is software availability to inspect/install and run if available, not hardware and not automatically unavailable on macOS."},
{"id": "windows-installer", "projects": ["ScriptWorker.Tests"], "file_pattern": "*InstallerLayoutIsolationTests.cs", "variables": ["OTOPCUA_ISOLATION_INSTALLER_E2E"], "requires": "Windows elevated administrator with PowerShell5.1, installer/service-account and AppLocker machine-state fixture; not runnable on local macOS. Other software-supported worker cases remain required."},
{"id": "windows-worker-identity", "projects": ["ScriptWorker.Tests"], "file_pattern": "*WorkerIsolationTests.cs", "method_inclusions": ["The_pipe_acl_is_protected_and_admits_exactly_the_host_and_the_worker_identity", "A_live_pipe_carries_the_acl_and_a_host_only_pipe_admits_the_host_alone", "The_worker_token_is_restricted_privilege_free_and_reaches_only_what_its_identity_may", "A_worker_under_the_identity_runs_scripts_with_a_restricted_token_and_a_plain_one_does_not"], "variables": [], "requires": "Windows named-pipe ACLs, local restricted worker identity/token and Windows process-launch security APIs; exact four Windows-only methods skip on local macOS."},
{"id": "windows-pipe-async-refusal", "projects": ["ScriptWorker.Tests"], "file_pattern": "*BlockingPipeStreamTests.cs", "method_inclusions": ["The_asynchronous_surface_is_refused_on_windows"], "variables": [], "requires": "Windows blocking pipe wrapper; the exact method returns early on non-Windows and must be recorded as unavailable semantic coverage even if TRX reports Passed."},
]
LONG = [
{"id": "sdk-lifecycle-soak", "files": ["Sdk2LifecycleSoakTests.cs", "Sdk2LifecycleLateSlopeTests.cs", "Sdk2LifecycleCloseOwnershipTests.cs"], "variables": ["OTOPCUA_SDK2_SOAK", "OTOPCUA_SDK2_SOAK_SECONDS", "OTOPCUA_SDK2_SOAK_MODE", "OTOPCUA_SDK2_SOAK_OUTPUT", "OTOPCUA_SOAK_BUILD_SHA", "OTOPCUA_SDK2_CLOSE_CONTROL", "OPCUA_CERTIFICATE_LEAK_TRACKING", "OTOPCUA_SDK2_SATURATION_CONTROL", "OTOPCUA_SDK2_SATURATION_RUN_ID", "OTOPCUA_SDK2_SATURATION_OBSERVER"], "decision": "Final coordinator must explicitly select duration/mode and run supported cases or report exact disabled names. Saturation/late-slope controls require matching runtime, external observer and prior protocol; never silently infer enabled from category-free execution."},
{"id": "folder-event-performance", "files": ["FolderEventDeliveryPerfTests.cs"], "variables": ["OTOPCUA_EVENT_PERF", "OTOPCUA_EVENT_PERF_REPORTS", "OTOPCUA_EVENT_PERF_ROUNDS", "OTOPCUA_EVENT_PERF_OUT"], "decision": "Software-supported opt-in; coordinator must enable and capture private per-run output or list exact disabled names."},
{"id": "questdb-race-stress", "files": ["LiveWriteReadRaceStressTests.cs"], "variables": ["HISTORIAN_QUESTDB_STRESS_SECONDS"], "decision": "Software-supported owned QuestDB; explicit positive duration enables stress; coordinator records duration and results."},
{"id": "ab-native-lease-soak", "files": ["NativeLeaseReleaseSoakTests.cs"], "variables": ["AB_LEASE_SOAK_CYCLES"], "decision": "Default 100 cycles on owned ab_server, not disabled; explicit duration tuning must not bypass native assertions."},
{"id": "worker-performance", "files": ["ScriptRunnerPerfTests.cs"], "variables": ["OTOPCUA_SCRIPTWORKER_TEST_PATH", "OTOPCUA_SCRIPT_PERF", "OTOPCUA_SCRIPT_PERF_SECONDS", "OTOPCUA_SCRIPT_PERF_OUT"], "decision": "Software-supported opt-in; built platform-matching worker required; default10s; coordinator must enable or list exact disabled names."},
{"id": "node-manager-benchmark-budget", "files": ["NodeManagerLockTimeBenchmarkTests.cs"], "variables": ["OTOPCUA_BENCH"], "decision": "Measurements and deterministic assertions run by default; OTOPCUA_BENCH=1 additionally enforces wall-clock budgets. Record budget-enabled/disabled explicitly; default execution is not enforced performance-budget evidence."},
]
def generate():
projects = []
all_sources = {}
source_digest = hashlib.sha256()
for path in sorted((ROOT / "tests").rglob("*.csproj")):
content = path.read_text()
if "Microsoft.NET.Test.Sdk" not in content and not re.search(r"<IsTestProject>\s*true", content):
continue
tree = ET.fromstring(content)
files = {file for file in path.parent.rglob("*.cs") if not ({"bin", "obj"} & set(file.relative_to(path.parent).parts))}
for element in tree.iter():
if element.tag.rsplit("}", 1)[-1] == "Compile" and element.get("Include"):
pattern = element.get("Include").replace("\\", "/")
files.update(Path(file).resolve() for file in glob.glob(str(path.parent / pattern), recursive=True) if Path(file).is_file())
records = []
categories = set()
variables = set()
for file in sorted(files):
text = file.read_text()
relative = file.relative_to(ROOT).as_posix()
source_digest.update(relative.encode() + b"\0" + text.encode() + b"\0")
gates = quoted_environment_names(text)
traits = sorted(set(re.findall(r'Trait\(\s*"Category"\s*,\s*"([^"\n]+)"', text)))
methods = source_methods(text)
categories.update(traits)
variables.update(gates)
if gates or methods:
platform_checks = sorted(set(re.findall(r"OperatingSystem\.(Is\w+)\(", text)))
record = {"path": relative, "environment_names": gates, "categories": traits, "platform_checks": platform_checks, "source_test_methods": methods}
records.append(record)
all_sources[relative] = record
assembly = path.stem.removeprefix("ZB.MOM.WW.OtOpcUa.")
group_ids = [group["id"] for group in GROUPS if assembly in group["projects"]]
unavailable_ids = [group["id"] for group in UNAVAILABLE if assembly in group["projects"]]
projects.append({"project": path.relative_to(ROOT).as_posix(), "assembly_suffix": assembly,
"categories_observed": sorted(categories) or ["unclassified"], "fixture_groups": group_ids or ["local-in-process"],
"unavailable_candidate_groups": unavailable_ids, "environment_names": sorted(variables), "sources": records})
unavailable = []
for group in UNAVAILABLE:
selected = [record for project in projects if project["assembly_suffix"] in group["projects"] for record in project["sources"]
if Path(record["path"]).match(group["file_pattern"]) and (group["file_pattern"] != "*" or set(record["environment_names"]) & set(group["variables"]))]
methods = {method for record in selected for method in record["source_test_methods"]}
if group.get("method_inclusions"):
methods = {method for method in methods if any(method.rsplit(".", 1)[-1] == name for name in group["method_inclusions"])}
if group.get("method_exclusions"):
methods = {method for method in methods if not any(method.rsplit(".", 1)[-1].startswith(name) for name in group["method_exclusions"])}
unavailable.append({**group, "disposition": "candidate-unavailable-until-local-prerequisite-verified", "source_test_methods": sorted(methods), "source_paths": sorted(record["path"] for record in selected)})
long_modes = []
for group in LONG:
selected = [record for record in all_sources.values() if any(Path(record["path"]).match(pattern) for pattern in group["files"])]
long_modes.append({**group, "source_paths": sorted(record["path"] for record in selected), "source_test_methods": sorted({method for record in selected for method in record["source_test_methods"]})})
return {
"schema_version": 1, "inventory_kind": "source-preparation-not-execution", "source_sha256": source_digest.hexdigest(),
"refresh_command": "python3 scripts/validation/grpc-data/fixture_inventory.py", "project_count": len(projects),
"ownership_contract": {"entrypoint": "scripts/ci/integration-fixtures.sh", "required_inputs": ["CI_FIXTURE_LOCAL_OWNED=1", "CI_FIXTURE_SUFFIX=<unique-safe-owner>", "CI_FIXTURE_ENV_JSON=<absolute-per-run-path>", "FIXTURE_HOST=127.0.0.1"],
"environment": "0600 JSON dict at CI_FIXTURE_ENV_JSON", "manifest": "CI_FIXTURE_ENV_JSON + '.manifest.json'", "run_directory": "CI_FIXTURE_ENV_JSON + '.d' (0700)",
"profile_environments": "run_directory/profile-environments.json (0600 dict of full allowlisted profile overlays)", "cleanup": "same inputs + down; exact recorded ID and both labels required; no compose down/name removal/prune", "ci_compatibility": "legacy behavior only outside explicit local-owned dispatch"},
"fixture_groups": GROUPS, "unavailable_candidates": unavailable, "long_running_optins": long_modes,
"environment_name_union": sorted({name for project in projects for name in project["environment_names"]}), "projects": projects,
"final_reconciliation_required": ["same candidate solution membership/discovery/TRX; every project nonzero executed", "concrete theory row names and each skipped reason", "zero skipped required GrpcData/software fixture cases", "profile-specific focused reruns with owned endpoint overlays", "exact unavailable platform/proprietary/live names, requirements and next gate", "explicit long-mode enabled/duration/results or exact disabled names", "no inherited fixture endpoints, credentials, SSH commands, unit-only discovery flag or forbidden shared-host probes"]
}
if __name__ == "__main__":
OUTPUT.write_text(json.dumps(generate(), indent=2, sort_keys=True) + "\n")
print(str(OUTPUT))
@@ -0,0 +1,771 @@
#!/usr/bin/env python3
"""Run-owned, loopback-only software prerequisites for the final local gate.
No existing Compose stack is started. Fixture sources supply only image build
contexts, commands and read-only seed/config files. Resource creation is journaled
before start; cleanup requires exact recorded identity AND both owner labels.
All subprocess output goes to bounded private logs; no credentials reach stdout.
"""
from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
import re
import secrets
import shlex
import signal
import socket
import stat
import subprocess
import sys
import threading
import time
from rig import RigError, validate_docker_context
ROOT = Path(__file__).resolve().parents[3]
HERE = Path(__file__).resolve().parent
OWNER_LABEL = "com.zb.otopcua.final-fixtures.owner"
PROJECT_LABEL = "com.docker.compose.project"
INSTANCE_LABEL = "com.zb.otopcua.final-fixtures.instance"
SUFFIX = re.compile(r"[a-z0-9][a-z0-9-]{0,47}\Z")
RESOURCE_ID = re.compile(r"[a-f0-9]{64}\Z")
LIMIT = 2 * 1024 * 1024
DRIVERS = ROOT / "tests/Drivers"
class FixtureError(RuntimeError):
"""A redacted fixture orchestration failure."""
def driver(name):
return DRIVERS / f"ZB.MOM.WW.OtOpcUa.Driver.{name}.IntegrationTests/Docker"
def private_json(path, value, *, exclusive=False):
"""Never follow an existing symlink; replace atomically with mode 0600."""
path = Path(path)
if path.is_symlink() or (path.exists() and not path.is_file()):
raise FixtureError("unsafe structured output path")
if exclusive and path.exists():
raise FixtureError("structured output already exists; use a new run suffix/path")
temporary = path.with_name(path.name + "." + secrets.token_hex(8) + ".tmp")
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
try:
with os.fdopen(fd, "w") as stream:
json.dump(value, stream, indent=2, sort_keys=True)
stream.write("\n")
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
def read_private(path):
path = Path(path)
fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
with os.fdopen(fd) as stream:
info = os.fstat(stream.fileno())
if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077 or info.st_uid != os.getuid():
raise FixtureError("structured fixture file must be an owned regular 0600 file")
if info.st_size > LIMIT:
raise FixtureError("structured fixture file exceeds size bound")
return json.loads(stream.read(LIMIT + 1))
class PrivateProcess:
"""Bound duration and output without ever copying tool output to a terminal."""
def __init__(self, directory, environment):
self.directory = Path(directory)
self.environment = environment
self.number = 0
self.invocation = secrets.token_hex(8)
def __call__(self, argv, *, timeout=120, input_bytes=None, check=True):
self.number += 1
log = self.directory / f"command-{self.invocation}-{self.number:05d}.log"
fd = os.open(log, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
chunks = []
state = {"size": 0, "overflow": False, "kill_failed": False}
with os.fdopen(fd, "wb") as output:
process = subprocess.Popen(argv, env=self.environment, stdin=subprocess.PIPE if input_bytes is not None else subprocess.DEVNULL,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, start_new_session=True)
def stop_owned_child():
if process.poll() is not None:
return
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
except PermissionError:
# Some macOS execution hosts deny killpg even for a child
# started in a new session. Fall back to this Popen child's
# handle; never discover/kill an unrelated PID or group.
try:
process.kill()
except ProcessLookupError:
pass
except PermissionError:
state["kill_failed"] = True
def drain():
while True:
block = process.stdout.read(65536)
if not block:
return
available = max(0, LIMIT - state["size"])
if available:
output.write(block[:available])
chunks.append(block[:available])
state["size"] += len(block)
if state["size"] > LIMIT:
state["overflow"] = True
stop_owned_child()
reader = threading.Thread(target=drain, daemon=True)
reader.start()
def write_input():
try:
process.stdin.write(input_bytes)
except BrokenPipeError:
pass
finally:
process.stdin.close()
writer = None
try:
if input_bytes is not None:
writer = threading.Thread(target=write_input, daemon=True)
writer.start()
process.wait(timeout=timeout)
except (subprocess.TimeoutExpired, BrokenPipeError):
stop_owned_child()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
raise FixtureError("owned fixture subprocess could not be stopped; inspect private logs") from None
raise FixtureError("fixture subprocess timed out or rejected input; inspect private logs") from None
except BaseException:
stop_owned_child()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
raise FixtureError("owned fixture subprocess could not be stopped; inspect private logs") from None
raise
finally:
reader.join(timeout=5)
if writer:
writer.join(timeout=5)
process.stdout.close()
if state["overflow"]:
raise FixtureError("fixture subprocess exceeded private output bound")
if state["kill_failed"]:
raise FixtureError("owned fixture subprocess termination failed")
result = b"".join(chunks)
if check and process.returncode:
raise FixtureError("fixture subprocess failed; inspect private logs")
return process.returncode, result
def compose_command(directory, service):
"""Read committed JSON-array commands, never execute its Compose lifecycle."""
source = (directory / "docker-compose.yml").read_text()
block = re.search(r"^ " + re.escape(service) + r":\s*\n(.*?)(?=^ [a-zA-Z][\w-]*:|\Z)", source, re.M | re.S)
if not block:
raise FixtureError("fixture source service is missing")
match = re.search(r"^ command:\s*(\[.*)", block[1], re.M | re.S)
if not match:
raise FixtureError("fixture source command is missing")
command, _ = json.JSONDecoder().raw_decode(match[1])
if not isinstance(command, list) or any(not isinstance(item, str) for item in command):
raise FixtureError("fixture command must be a JSON string array")
return command
def definitions():
"""All software fixtures use published dynamic loopback ports and no restart."""
sql = {"image": "mcr.microsoft.com/mssql/server:2022-latest", "ports": [1433],
"environment": {"ACCEPT_EULA": "Y", "MSSQL_PID": "Developer", "MSSQL_SA_PASSWORD": "@SQL_PASSWORD@"},
"platform": "linux/amd64"}
result = {
"sql": sql,
"sql-blackhole": dict(sql),
"postgres": {"image": "postgres:17-alpine", "ports": [5432], "environment": {"POSTGRES_PASSWORD": "@PG_PASSWORD@", "POSTGRES_DB": "sqlpollfixture"}},
"mysql": {"image": "mysql:8.4", "ports": [3306], "environment": {"MYSQL_ROOT_PASSWORD": "@MYSQL_PASSWORD@"}, "command": ["--log-bin-trust-function-creators=1"]},
"oracle": {"image": "gvenzl/oracle-free:23-slim", "platform": "linux/amd64", "ports": [1521], "environment": {"ORACLE_PASSWORD": "@ORACLE_PASSWORD@", "APP_USER": "otopcua", "APP_USER_PASSWORD": "@ORACLE_PASSWORD@"}},
"questdb": {"image": re.search(r"image:\s*(questdb/questdb:[\w.-]+)", (driver("Historian.QuestDb") / "docker-compose.yml").read_text())[1], "ports": [8812, 9000]},
"opc": {"image": "mcr.microsoft.com/iotedge/opc-plc:2.14.10", "ports": [50000], "same_port": True, "command": ["--pn=@OPC_PORT@", "--ut", "--aa", "--alm"]},
"opc-nat": {"image": "mcr.microsoft.com/iotedge/opc-plc:2.14.10", "ports": [50000], "command": ["--pn=50000", "--ph=owned-opc-private.invalid", "--ut", "--aa"]},
"ldap": {"image": "glauth/glauth:latest", "ports": [3893], "mounts": [(ROOT / "tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/glauth/config.toml", "/app/config/config.cfg")]},
"s7": {"build": driver("S7"), "ports": [1102], "stable_ports": True, "command": compose_command(driver("S7"), "s7_1500")},
"focas": {"build": driver("FOCAS") / "focas-mock", "ports": [8193], "command": ["--profile", "FWLIB64"]},
"mtconnect-adapter": {"image": "python:3.13-alpine", "ports": [], "alias": "adapter", "mounts": [(driver("MTConnect") / "adapter.py", "/fixtures/adapter.py")], "command": ["python", "-u", "/fixtures/adapter.py", "--host", "0.0.0.0", "--port", "7878"]},
"mtconnect": {"image": "mtconnect/agent:2.7.0.12", "ports": [5000], "mounts": [(driver("MTConnect") / "agent.cfg", "/mtconnect/config/agent.cfg"), (driver("MTConnect") / "Devices.xml", "/mtconnect/config/Devices.xml")]},
"mqtt": {"image": "eclipse-mosquitto:2.0.22", "ports": [1883, 8883], "alias": "mosquitto", "user": "0:0", "mounts": [("@MQTT_CONFIG@", "/mosquitto/config/mosquitto.conf"), ("@MQTT_DIR@", "/mosquitto/secrets")]},
"mqtt-publisher": {"image": "eclipse-mosquitto:2.0.22", "ports": [], "environment": {"BROKER_HOST": "mosquitto", "BROKER_PORT": "1883", "TOPIC_PREFIX": "@MQTT_PREFIX@", "MQTT_FIXTURE_USERNAME": "otopcua", "MQTT_FIXTURE_PASSWORD": "@MQTT_PASSWORD@"}, "mounts": [(driver("Mqtt") / "publisher/publish.sh", "/publish.sh")], "entrypoint": "/bin/sh", "command": ["/publish.sh"]},
}
for profile in ("standard", "dl205", "mitsubishi", "s7_1500", "rtu_over_tcp", "exception_injection"):
result["modbus-" + profile.replace("_", "-")] = {"build": driver("Modbus"), "ports": [5021 if profile == "rtu_over_tcp" else 5020], "command": compose_command(driver("Modbus"), profile)}
for profile in ("controllogix", "compactlogix", "micro800", "guardlogix"):
result["ab-" + profile] = {"build": driver("AbCip"), "ports": [44818], "command": compose_command(driver("AbCip"), profile)}
for profile in ("slc500", "micrologix", "plc5"):
result["legacy-" + profile] = {"build": driver("AbCip"), "ports": [44818], "command": compose_command(driver("AbLegacy"), profile)}
return result
class OwnedFixtures:
def __init__(self, environment=None, *, process=None):
self.input = dict(os.environ if environment is None else environment)
self.owner = self.input.get("CI_FIXTURE_SUFFIX", "")
if not SUFFIX.fullmatch(self.owner):
raise FixtureError("local fixtures require a nonempty safe unique CI_FIXTURE_SUFFIX")
if self.input.get("CI_FIXTURE_LOCAL_OWNED") != "1" or self.input.get("FIXTURE_HOST") != "127.0.0.1":
raise FixtureError("local fixtures require explicit local-owned mode and FIXTURE_HOST=127.0.0.1")
raw = self.input.get("CI_FIXTURE_ENV_JSON", "")
if not raw or not Path(raw).is_absolute():
raise FixtureError("CI_FIXTURE_ENV_JSON must be an absolute per-run output path")
self.output = Path(raw)
self.manifest_path = Path(raw + ".manifest.json")
if not self.manifest_path.is_absolute() or self.output == self.manifest_path:
raise FixtureError("fixture manifest requires a separate absolute path")
self.directory = Path(raw + ".d")
self.project = "grpc-final-" + self.owner
self.labels = {OWNER_LABEL: self.owner, PROJECT_LABEL: self.project}
self.odbc_driver = self.input.get("CI_FIXTURE_ODBC_DRIVER", "")
if self.odbc_driver:
if (not Path(self.odbc_driver).is_absolute() or not Path(self.odbc_driver).is_file()
or any(character in self.odbc_driver for character in ";{}\r\n\0")):
raise FixtureError("CI_FIXTURE_ODBC_DRIVER requires an existing absolute local driver library path")
# Never inherit fixture credentials, endpoint URLs, proxies, SSH commands,
# daemon overrides unrelated to the inspected local context, or GITHUB_ENV.
allowed = {"PATH", "HOME", "USER", "TMPDIR", "SystemRoot", "DOCKER_CONTEXT", "DOCKER_HOST", "DOCKER_CONFIG", "DOCKER_API_VERSION"}
self.environment = {k: v for k, v in self.input.items() if k in allowed}
self.process = process
self.manifest = None
self.docker_prefix = ["docker"]
self.ports = {}
self.containers = {}
self.images = {}
def prepare(self, *, creating):
self.output.parent.mkdir(parents=True, exist_ok=True)
if creating:
if self.directory.exists() or self.output.exists() or self.manifest_path.exists():
raise FixtureError("fixture output already exists; use a new unique run path")
self.directory.mkdir(mode=0o700)
else:
info = self.directory.lstat()
if not stat.S_ISDIR(info.st_mode) or info.st_mode & 0o077 or info.st_uid != os.getuid():
raise FixtureError("fixture directory must be an owned private directory")
if self.process is None:
logs = self.directory / "logs"
logs.mkdir(mode=0o700, exist_ok=True)
self.process = PrivateProcess(logs, self.environment)
# Read-only context validation precedes every mutation, including teardown.
selected = self.environment.get("DOCKER_CONTEXT")
argv = ["docker", "context", "inspect"] + ([selected] if selected else [])
_, raw = self.process(argv)
try:
contexts = json.loads(raw)
if len(contexts) != 1:
raise ValueError()
context = contexts[0]
validate_docker_context(context, environment=self.environment)
except (ValueError, TypeError, KeyError, RigError):
raise FixtureError("Docker local context validation failed") from None
self.docker_prefix = ["docker", "--context", context["Name"]]
if creating:
self.instance = secrets.token_hex(16)
self.labels[INSTANCE_LABEL] = self.instance
self.manifest = {"schema_version": 1, "owner": self.owner, "project": self.project, "labels": self.labels,
"instance": self.instance,
"environment_json": str(self.output), "directory": str(self.directory), "context": context,
"resources": [], "pending": [], "status": "creating", "services": {}}
self.save()
else:
self.manifest = read_private(self.manifest_path)
instance = self.manifest.get("instance", "") if isinstance(self.manifest, dict) else ""
if not isinstance(instance, str) or not re.fullmatch(r"[a-f0-9]{32}", instance):
raise FixtureError("fixture manifest requires a unique creation instance")
self.labels[INSTANCE_LABEL] = instance
self.validate_manifest()
if self.manifest["context"] != context:
raise FixtureError("fixture daemon context changed since creation")
def validate_manifest(self):
m = self.manifest
if not isinstance(m, dict) or m.get("schema_version") != 1 or m.get("owner") != self.owner or m.get("project") != self.project or m.get("labels") != self.labels:
raise FixtureError("fixture manifest owner/project mismatch")
if m.get("environment_json") != str(self.output) or m.get("directory") != str(self.directory):
raise FixtureError("fixture manifest paths mismatch")
if not isinstance(m.get("resources"), list) or not isinstance(m.get("pending"), list):
raise FixtureError("fixture manifest inventory is invalid")
seen = set()
for row in m["resources"]:
identity = (row.get("kind"), row.get("id"))
valid_id = bool(RESOURCE_ID.fullmatch(row.get("id", ""))) if row.get("kind") != "volume" else row.get("id", "").startswith(self.project + "-")
if row.get("kind") not in {"container", "network", "volume", "image"} or not valid_id or row.get("labels") != self.labels or identity in seen:
raise FixtureError("fixture manifest resource identity/labels invalid")
seen.add(identity)
for row in m["pending"]:
if row.get("kind") not in {"container", "network", "volume", "image"} or not row.get("name", "").startswith(self.project + "-"):
raise FixtureError("fixture manifest pending identity invalid")
def save(self):
private_json(self.manifest_path, self.manifest)
def docker(self, *argv, **kwargs):
return self.process(self.docker_prefix + list(argv), **kwargs)
def inspect(self, kind, identity, *, missing=False):
rc, raw = self.docker(kind, "inspect", identity, check=False)
if rc:
# A daemon/permission/transport failure is not proof of absence.
absent = re.search(rb"no such (?:object|container|image|network|volume)\b|(?:network|volume) [^\r\n]+ not found\b", raw, re.I)
if missing and absent:
return None
raise FixtureError("owned fixture resource inspection failed")
try:
rows = json.loads(raw)
if not isinstance(rows, list) or len(rows) != 1:
raise ValueError()
return rows[0]
except (ValueError, TypeError):
raise FixtureError("invalid Docker inspection response") from None
def observed_labels(self, kind, row):
return (row.get("Config", {}).get("Labels") if kind in {"container", "image"} else row.get("Labels")) or {}
def verified(self, kind, identity, *, missing=False):
row = self.inspect(kind, identity, missing=missing)
if row is None:
return None
if any(self.observed_labels(kind, row).get(k) != v for k, v in self.labels.items()):
raise FixtureError("refusing foreign resource; exact owner/project labels are required")
actual = row.get("Name") if kind == "volume" else row.get("Id", "").removeprefix("sha256:")
if actual != identity:
raise FixtureError("resource identity changed; refusing cleanup")
return row
def guard_name(self, kind, name):
# A unique suffix may never adopt even an existing same-owner name on up.
if self.inspect(kind, name, missing=True) is not None:
raise FixtureError("fixture resource name exists; refusing replacement/adoption")
def create(self, kind, name, args, *, result_id=True):
self.guard_name(kind, name)
pending = {"kind": kind, "name": name}
self.manifest["pending"].append(pending)
self.save() # durable intent precedes mutation; interrupted creation is recoverable
_, raw = self.docker(*args)
identity = raw.decode().strip().removeprefix("sha256:") if result_id else name
if kind != "volume" and not RESOURCE_ID.fullmatch(identity):
raise FixtureError("Docker returned an invalid resource identity")
self.verified(kind, identity)
self.manifest["resources"].append({"kind": kind, "id": identity, "labels": self.labels, "name": name})
self.manifest["pending"].remove(pending)
self.save()
return identity
def label_args(self):
return [item for key, value in self.labels.items() for item in ("--label", key + "=" + value)]
def image(self, spec):
if "build" not in spec:
image = spec["image"]
if image not in self.images:
self.docker("pull", *( ["--platform", spec["platform"]] if spec.get("platform") else []), image, timeout=900)
self.images[image] = image
return image
context = str(spec["build"])
if context not in self.images:
name = self.project + "-image-" + str(len(self.images))
self.guard_name("image", name)
pending = {"kind": "image", "name": name}
self.manifest["pending"].append(pending)
self.save()
iid = self.directory / (name + ".iid")
self.docker("build", "--iidfile", str(iid), "--tag", name, *self.label_args(), context, timeout=1200)
identity = iid.read_text().strip().removeprefix("sha256:")
self.verified("image", identity)
self.manifest["resources"].append({"kind": "image", "id": identity, "labels": self.labels, "name": name})
self.manifest["pending"].remove(pending)
self.save()
self.images[context] = identity
return self.images[context]
def substitute(self, value):
for key, replacement in self.tokens.items():
value = value.replace("@" + key + "@", str(replacement))
if re.search(r"@[A-Z_]+@", value):
raise FixtureError("unresolved fixture configuration token")
return value
def start(self, service, spec):
name = self.project + "-" + service
# Guard before pulling/building too; an occupied name is never removed.
self.guard_name("container", name)
image = self.image(spec)
_, image_raw = self.docker("image", "inspect", image)
image_data = json.loads(image_raw)[0]
args = ["container", "create", "--name", name, *self.label_args(), "--network", self.network,
"--network-alias", spec.get("alias", service), "--restart=no", "--log-opt", "max-size=5m", "--log-opt", "max-file=2"]
if spec.get("platform"):
args += ["--platform", spec["platform"]]
if spec.get("user"):
args += ["--user", spec["user"]]
if spec.get("entrypoint"):
args += ["--entrypoint", spec["entrypoint"]]
mounts = []
for entry in spec.get("mounts", []):
source, target = Path(self.substitute(str(entry[0]))), entry[1]
writable = len(entry) == 3 and entry[2] == "writable"
if writable and (service != "mqtt-material" or source != self.directory / "mqtt" or target != "/out"):
raise FixtureError("only run-owned MQTT material output may be mounted writable")
mounts.append((source, target, writable))
# Replace every image-declared volume by an explicitly labelled owned
# volume, including volumes partially covered by a read-only file bind.
for index, target in enumerate((image_data.get("Config", {}).get("Volumes") or {})):
if any(destination == target for _, destination, _ in mounts):
continue
volume_name = name + "-v" + str(index)
volume = self.create("volume", volume_name, ["volume", "create", *self.label_args(), volume_name], result_id=False)
args += ["--mount", f"type=volume,source={volume},target={target}"]
for source, target, writable in mounts:
if not source.exists() or "," in str(source):
raise FixtureError("required fixture mount is missing or unsafe")
args += ["--mount", f"type=bind,source={source},target={target}" + ("" if writable else ",readonly")]
for key, value in spec.get("environment", {}).items():
args += ["--env", key + "=" + self.substitute(value)]
internal_ports = list(spec.get("ports", []))
reserved_ports = {}
if spec.get("same_port"):
# Docker handles the race between releasing this candidate and bind.
# A failed start retains its recorded ID for ownership-safe cleanup.
with socket.socket() as reserve:
reserve.bind(("127.0.0.1", 0))
candidate = reserve.getsockname()[1]
self.tokens["OPC_PORT"] = candidate
internal_ports = [candidate]
args += ["--publish", f"127.0.0.1:{candidate}:{candidate}"]
elif spec.get("stable_ports"):
# Restart tests retain their original .NET endpoint. Choose an owned
# free host port once and bind it explicitly for the container's life.
# A race after release fails start and leaves the exact ID journaled.
for port in internal_ports:
with socket.socket() as reserve:
reserve.bind(("127.0.0.1", 0))
candidate = reserve.getsockname()[1]
reserved_ports[port] = candidate
args += ["--publish", f"127.0.0.1:{candidate}:{port}"]
else:
for port in internal_ports:
args += ["--publish", f"127.0.0.1::{port}"]
command = [self.substitute(item) for item in spec.get("command", [])]
identity = self.create("container", name, args + [image] + command)
self.containers[service] = identity
self.manifest["services"][service] = {"container_id": identity, "ports": {}}
if spec.get("stable_ports"):
self.manifest["services"][service]["stable_ports"] = True
self.save()
self.docker("container", "start", identity)
observed = self.verified("container", identity)
ports = observed.get("NetworkSettings", {}).get("Ports", {})
self.ports[service] = {}
for port in internal_ports:
bindings = ports.get(f"{port}/tcp")
if not bindings or len(bindings) != 1 or bindings[0].get("HostIp") != "127.0.0.1":
raise FixtureError("Docker did not publish exactly one loopback port")
allocated = int(bindings[0]["HostPort"])
if not 1 <= allocated <= 65535:
raise FixtureError("Docker returned an invalid allocated port")
if port in reserved_ports and allocated != reserved_ports[port]:
raise FixtureError("Docker changed the reserved stable fixture publication")
self.ports[service][port] = allocated
self.manifest["services"][service]["ports"] = self.ports[service]
self.save()
self.ready(service)
return identity
def wait(self, probe, timeout=120):
deadline = time.monotonic() + timeout
while True:
try:
if probe():
return
except (OSError, FixtureError):
pass
if time.monotonic() >= deadline:
raise FixtureError("fixture readiness deadline exceeded; inspect private logs")
time.sleep(2)
def execute(self, service, argv, **kwargs):
identity = self.containers[service]
self.verified("container", identity)
return self.docker("container", "exec", *( ["-i"] if kwargs.get("input_bytes") is not None else []), identity, *argv, **kwargs)
def ready(self, service):
if service in {"sql", "sql-blackhole"}:
self.wait(lambda: self.execute(service, ["/opt/mssql-tools18/bin/sqlcmd", "-C", "-S", "localhost", "-U", "sa", "-P", self.tokens["SQL_PASSWORD"], "-Q", "SELECT 1"], check=False, timeout=20)[0] == 0, 360)
elif service == "postgres":
self.wait(lambda: self.execute(service, ["pg_isready", "-h", "127.0.0.1", "-U", "postgres", "-d", "sqlpollfixture"], check=False)[0] == 0)
# pg_isready can observe the temporary init server; TCP psql must work.
command = ["env", "PGPASSWORD=" + self.tokens["PG_PASSWORD"], "psql", "-h", "127.0.0.1", "-U", "postgres", "-d", "sqlpollfixture", "-v", "ON_ERROR_STOP=1", "-v", "app_password=" + self.tokens["PG_PASSWORD"]]
self.wait(lambda: self.execute(service, command + ["-c", "select 1"], check=False)[0] == 0)
self.execute(service, command, input_bytes=(driver("Sql") / "postgres/seed-pg.sql").read_bytes())
elif service == "mysql":
self.wait(lambda: self.execute(service, ["env", "MYSQL_PWD=" + self.tokens["MYSQL_PASSWORD"], "mysqladmin", "ping", "-h", "127.0.0.1", "-uroot", "--silent"], check=False)[0] == 0, 240)
seed = (driver("Sql") / "mysql/seed-mysql.sql").read_text().replace("__APP_PASSWORD__", self.tokens["MYSQL_PASSWORD"])
self.execute(service, ["env", "MYSQL_PWD=" + self.tokens["MYSQL_PASSWORD"], "mysql", "-h", "127.0.0.1", "-uroot"], input_bytes=seed.encode())
elif service == "oracle":
self.wait(lambda: self.execute(service, ["healthcheck.sh"], check=False, timeout=20)[0] == 0, 900)
self.execute(service, ["sqlplus", "-S", "-L", "otopcua/" + self.tokens["ORACLE_PASSWORD"] + "@//127.0.0.1:1521/FREEPDB1"], input_bytes=(driver("Sql") / "oracle/seed-oracle.sql").read_bytes(), timeout=180)
elif service == "mqtt":
self.wait(lambda: self.execute(service, ["mosquitto_pub", "-h", "127.0.0.1", "-p", "1883", "-u", "otopcua", "-P", self.tokens["MQTT_PASSWORD"], "-t", self.tokens["MQTT_PREFIX"] + "/ready", "-m", "ready", "-q", "1"], check=False, timeout=10)[0] == 0)
self.execute(service, ["mosquitto_pub", "-h", "127.0.0.1", "-p", "8883", "--cafile", "/mosquitto/secrets/ca.crt", "-u", "otopcua", "-P", self.tokens["MQTT_PASSWORD"], "-t", self.tokens["MQTT_PREFIX"] + "/ready", "-m", "ready", "-q", "1"])
elif service == "mqtt-publisher":
self.wait(lambda: self.execute("mqtt", ["mosquitto_sub", "-h", "127.0.0.1", "-p", "1883", "-u", "otopcua", "-P", self.tokens["MQTT_PASSWORD"], "-t", self.tokens["MQTT_PREFIX"] + "/retained/seed", "-C", "1", "-W", "5"], check=False, timeout=10)[0] == 0)
elif service.startswith("modbus-"):
port = next(iter(self.ports[service]))
args = ["python", "/fixtures/fc3_probe.py", "--port", str(port), "--deadline", "3"]
if service == "modbus-rtu-over-tcp":
args += ["--framer", "rtu"]
self.wait(lambda: self.execute(service, args, check=False, timeout=10)[0] == 0)
elif service == "mtconnect":
self.wait(lambda: self.execute(service, ["wget", "-q", "-O", "/dev/null", "http://127.0.0.1:5000/probe"], check=False)[0] == 0)
else:
for allocated in self.ports[service].values():
def tcp():
with socket.create_connection(("127.0.0.1", allocated), timeout=2):
return True
self.wait(tcp)
if service == "opc-nat":
cert = self.directory / "opc-nat-server.der"
def copy_certificate():
rc, raw = self.execute(service, ["bash", "-c", "cat /app/pki/own/certs/*.der"], check=False)
if rc or not raw:
return False
cert.write_bytes(raw)
cert.chmod(0o600)
return True
self.wait(copy_certificate, 90)
self.manifest["services"][service]["ready"] = True
self.save()
def mqtt_material(self):
directory = self.directory / "mqtt"
directory.mkdir(mode=0o700)
self.tokens["MQTT_DIR"] = directory
configuration = self.directory / "mosquitto.conf"
# Mosquitto otherwise drops root to uid1883 internally. Keep this
# loopback-only disposable broker as root so host-owned keys/password
# files can remain 0600 rather than opening secret material globally.
configuration.write_text("user root\n" + (driver("Mqtt") / "mosquitto.conf").read_text())
configuration.chmod(0o600)
self.tokens["MQTT_CONFIG"] = configuration
# Broker runs as container root, allowing restricted bind-mounted keys.
self.process(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", str(directory / "ca.key"), "-out", str(directory / "ca.crt"), "-days", "2", "-subj", "/CN=Owned final fixture CA", "-addext", "basicConstraints=critical,CA:TRUE"])
self.process(["openssl", "req", "-newkey", "rsa:2048", "-nodes", "-keyout", str(directory / "server.key"), "-out", str(directory / "server.csr"), "-subj", "/CN=127.0.0.1"])
extensions = directory / "extensions.cnf"
extensions.write_text("subjectAltName=IP:127.0.0.1,DNS:localhost,DNS:mosquitto\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\n")
self.process(["openssl", "x509", "-req", "-in", str(directory / "server.csr"), "-CA", str(directory / "ca.crt"), "-CAkey", str(directory / "ca.key"), "-CAcreateserial", "-out", str(directory / "server.crt"), "-days", "2", "-sha256", "-extfile", str(extensions)])
spec = {"image": "eclipse-mosquitto:2.0.22", "ports": [], "user": f"{os.getuid()}:{os.getgid()}", "mounts": [(directory, "/out", "writable")], "entrypoint": "mosquitto_passwd", "command": ["-b", "-c", "/out/passwd", "otopcua", self.tokens["MQTT_PASSWORD"]]}
self.start("mqtt-material", spec)
_, raw = self.docker("container", "wait", self.containers["mqtt-material"], timeout=60)
if raw.strip() != b"0" or not (directory / "passwd").is_file():
raise FixtureError("MQTT password material generation failed")
for path in directory.iterdir():
if path.is_file():
path.chmod(0o600)
def endpoint(self, service, port=None, scheme=""):
values = self.ports[service]
chosen = values[port] if port is not None else next(iter(values.values()))
return scheme + "127.0.0.1:" + str(chosen)
def environment_document(self):
env = {"OTOPCUA_LOCAL_FIXTURE_MODE": "1"}
if "sql" in self.ports:
endpoint = self.endpoint("sql").replace(":", ",")
env.update(OTOPCUA_CONFIG_TEST_SERVER=endpoint, OTOPCUA_CONFIG_TEST_SA_PASSWORD=self.tokens["SQL_PASSWORD"], SQL_TEST_ENDPOINT=endpoint, SQL_TEST_USER="sa", SQL_TEST_PASSWORD=self.tokens["SQL_PASSWORD"],
HISTORIAN_SQL_TEST_CONNECTION=f"Server={endpoint};User Id=sa;Password={self.tokens['SQL_PASSWORD']};TrustServerCertificate=True;Encrypt=False",
OTOPCUA_HARNESS_USE_SQL="1", OTOPCUA_HARNESS_SQL_HOST=endpoint, OTOPCUA_HARNESS_SQL_PASSWORD=self.tokens["SQL_PASSWORD"])
if "sql-blackhole" in self.ports:
env.update(SQL_BLACKHOLE_ENDPOINT=self.endpoint("sql-blackhole").replace(":", ","), SQL_BLACKHOLE_USER="sa", SQL_BLACKHOLE_PASSWORD=self.tokens["SQL_PASSWORD"],
SQL_BLACKHOLE_CONTAINER_ID=self.containers["sql-blackhole"], SQL_BLACKHOLE_FIXTURE_OWNER=self.owner,
SQL_BLACKHOLE_ENV_JSON=str(self.output), SQL_BLACKHOLE_CONTROL_SCRIPT=str(Path(__file__).resolve()))
for service, prefix, token in (("postgres", "SQL_PG", "PG_PASSWORD"), ("mysql", "SQL_MYSQL", "MYSQL_PASSWORD"), ("oracle", "SQL_ORACLE", "ORACLE_PASSWORD")):
if service in self.ports:
env.update({prefix + "_ENDPOINT": self.endpoint(service), prefix + "_USER": "otopcua", prefix + "_PASSWORD": self.tokens[token]})
if self.odbc_driver and "postgres" in self.ports:
env["SQL_ODBC_CONNECTION_STRING"] = (f"Driver={{{self.odbc_driver}}};Server=127.0.0.1;Port={self.ports['postgres'][5432]};"
f"Database=sqlpollfixture;Uid=otopcua;Pwd={self.tokens['PG_PASSWORD']};")
if "oracle" in self.ports:
env["SQL_ORACLE_SERVICE"] = "FREEPDB1"
if "questdb" in self.ports:
env["HISTORIAN_QUESTDB_TEST_CONNECTION"] = f"Host=127.0.0.1;Port={self.ports['questdb'][8812]};Username=admin;Password=quest;Database=qdb;ServerCompatibilityMode=NoTypeLoading"
if "opc" in self.ports:
env["OPCUA_SIM_ENDPOINT"] = self.endpoint("opc", scheme="opc.tcp://")
if "opc-nat" in self.ports:
env.update(OPCUA_NAT_ENDPOINT=self.endpoint("opc-nat", scheme="opc.tcp://"), OPCUA_NAT_SERVER_CERT=str(self.directory / "opc-nat-server.der"))
if "modbus-standard" in self.ports:
env.update(MODBUS_SIM_ENDPOINT=self.endpoint("modbus-standard"), MODBUS_SIM_PROFILE="standard")
if "modbus-rtu-over-tcp" in self.ports:
env["MODBUS_RTU_SIM_ENDPOINT"] = self.endpoint("modbus-rtu-over-tcp")
if "s7" in self.ports:
env.update(S7_SIM_ENDPOINT=self.endpoint("s7"), S7_SIM_ALLOW_WRITES="1")
command = [sys.executable, str(Path(__file__).resolve()), "control", "--environment-json", str(self.output), "--owner", self.owner, "--service", "s7", "--container-id", self.containers["s7"], "--verb"]
env.update(S7_RECONNECT_BOUNCE_CMD=shlex.join(command + ["restart"]), S7_TIMEOUT_OUTAGE_START_CMD=shlex.join(command + ["pause"]), S7_TIMEOUT_OUTAGE_STOP_CMD=shlex.join(command + ["unpause"]))
if "ab-controllogix" in self.ports:
endpoint = self.endpoint("ab-controllogix")
env.update(AB_SERVER_ENDPOINT=endpoint, AB_SERVER_CONTROLLOGIX_ENDPOINT=endpoint,
AB_SERVER_PROFILE="abserver", AB_SERVER_COMPOSE_PROFILE="controllogix", AB_SERVER_ALLOW_WRITES="1")
if "legacy-slc500" in self.ports:
env.update(AB_LEGACY_ENDPOINT=self.endpoint("legacy-slc500"), AB_LEGACY_CIP_PATH="1,0", AB_SERVER_ALLOW_WRITES="1")
for profile in ("slc500", "micrologix", "plc5"):
if "legacy-" + profile in self.ports:
env["AB_LEGACY_" + profile.upper() + "_ENDPOINT"] = self.endpoint("legacy-" + profile)
if "focas" in self.ports:
env.update(OTOPCUA_FOCAS_SIM_ENDPOINT=self.endpoint("focas"), OTOPCUA_FOCAS_SIM_PROFILE="FWLIB64")
if "mtconnect" in self.ports:
env.update(MTCONNECT_AGENT_ENDPOINT=self.endpoint("mtconnect", scheme="http://"), MTCONNECT_WRITE_TARGET="fixture_writeback")
if "mqtt" in self.ports:
env.update(MQTT_FIXTURE_ENDPOINT=self.endpoint("mqtt", 8883), MQTT_FIXTURE_PLAIN_ENDPOINT=self.endpoint("mqtt", 1883), MQTT_FIXTURE_USERNAME="otopcua", MQTT_FIXTURE_PASSWORD=self.tokens["MQTT_PASSWORD"], MQTT_FIXTURE_CA_CERT=str(self.directory / "mqtt/ca.crt"), MQTT_FIXTURE_TOPIC_PREFIX=self.tokens["MQTT_PREFIX"])
if "ldap" in self.ports:
env.update(OTOPCUA_HARNESS_USE_LDAP="1", OTOPCUA_HARNESS_LDAP_HOST="127.0.0.1", OTOPCUA_HARNESS_LDAP_PORT=str(self.ports["ldap"][3893]))
return env
def profile_documents(self, base):
profiles = {}
for profile in ("dl205", "mitsubishi", "s7_1500", "exception_injection"):
service = "modbus-" + profile.replace("_", "-")
if service in self.ports:
profiles["modbus-" + profile] = {**base, "MODBUS_SIM_ENDPOINT": self.endpoint(service), "MODBUS_SIM_PROFILE": profile}
for profile in ("compactlogix", "micro800", "guardlogix"):
if "ab-" + profile in self.ports:
profiles["ab-" + profile] = {**base, "AB_SERVER_ENDPOINT": self.endpoint("ab-" + profile), "AB_SERVER_COMPOSE_PROFILE": profile}
return profiles
def up(self):
self.prepare(creating=True)
self.tokens = {key: "Final1_" + secrets.token_hex(16) for key in ("SQL_PASSWORD", "PG_PASSWORD", "MYSQL_PASSWORD", "ORACLE_PASSWORD", "MQTT_PASSWORD")}
self.tokens["MQTT_PREFIX"] = "otopcua/final/" + self.owner
specs = definitions()
selected = self.input.get("CI_FIXTURE_SERVICES", "").split(",") if self.input.get("CI_FIXTURE_SERVICES") else list(specs)
if not selected or any(service not in specs for service in selected) or len(set(selected)) != len(selected):
raise FixtureError("unknown or duplicate selected fixture service")
if self.odbc_driver and "postgres" not in selected:
raise FixtureError("the local ODBC gate requires the owned seeded PostgreSQL fixture")
for service, prerequisite in (("mqtt-publisher", "mqtt"), ("mtconnect", "mtconnect-adapter")):
if service in selected and prerequisite not in selected:
raise FixtureError("selected fixture service requires its local prerequisite")
network_name = self.project + "-network"
# Docker may omit host publications on an internal-only network.
# The run owns this bridge and publishes each service on loopback.
self.network = self.create("network", network_name,
["network", "create", "--driver", "bridge", *self.label_args(), network_name])
if "mqtt" in selected:
self.mqtt_material()
for service in selected:
self.start(service, specs[service])
env = self.environment_document()
private_json(self.output, env, exclusive=True)
private_json(self.directory / "profile-environments.json", self.profile_documents(env), exclusive=True)
self.manifest["status"] = "ready"
self.save()
def recover_pending(self):
# A process may die after Docker creates a resource but before its ID is
# journaled. A pending exact name is only a lookup key: labels and immutable
# ID must still be validated before it enters the cleanup inventory.
for pending in self.manifest["pending"]:
row = self.inspect(pending["kind"], pending["name"], missing=True)
if row is None:
continue
if any(self.observed_labels(pending["kind"], row).get(k) != v for k, v in self.labels.items()):
raise FixtureError("pending name belongs to a foreign resource; refusing cleanup")
identity = row["Name"] if pending["kind"] == "volume" else row["Id"].removeprefix("sha256:")
self.manifest["resources"].append({**pending, "id": identity, "labels": self.labels})
self.manifest["pending"] = []
self.save()
def down(self):
self.prepare(creating=False)
self.recover_pending()
self.validate_manifest()
# Validate the entire inventory before removing anything. Then recheck
# each ID immediately before mutation, preventing name substitution.
for row in self.manifest["resources"]:
self.verified(row["kind"], row["id"], missing=True)
order = {"container": 0, "network": 1, "volume": 2, "image": 3}
for row in sorted(self.manifest["resources"], key=lambda item: order[item["kind"]]):
if self.verified(row["kind"], row["id"], missing=True) is None:
continue
argv = [row["kind"], "rm"] + (["--force"] if row["kind"] == "container" else []) + [row["id"]]
self.docker(*argv)
self.manifest["status"] = "removed"
self.save()
def logs(self):
self.prepare(creating=False)
for row in self.manifest["resources"]:
if row["kind"] == "container" and self.verified("container", row["id"], missing=True):
self.docker("container", "logs", "--tail", "200", row["id"], check=False)
def control(self, service, identity, verb, endpoint=None):
if service not in {"s7", "sql-blackhole"} or verb not in {"pause", "unpause", "restart", "verify"}:
raise FixtureError("unsupported local fixture control action")
self.prepare(creating=False)
if self.manifest.get("status") != "ready" or self.manifest.get("services", {}).get(service, {}).get("container_id") != identity:
raise FixtureError("control requires a ready fixture and its exact recorded service ID")
observed = self.verified("container", identity)
def verify_s7_publication(row):
recorded = self.manifest["services"]["s7"]
published = recorded.get("ports", {}).get("1102")
bindings = row.get("NetworkSettings", {}).get("Ports", {}).get("1102/tcp")
if (recorded.get("stable_ports") is not True or type(published) is not int or not 1 <= published <= 65535
or bindings != [{"HostIp": "127.0.0.1", "HostPort": str(published)}]):
raise FixtureError("S7 endpoint does not match its owned stable publication")
if service == "s7":
verify_s7_publication(observed)
if service == "sql-blackhole":
published = self.manifest["services"][service].get("ports", {}).get("1433")
bindings = observed.get("NetworkSettings", {}).get("Ports", {}).get("1433/tcp")
if endpoint != f"127.0.0.1,{published}" or bindings != [{"HostIp": "127.0.0.1", "HostPort": str(published)}]:
raise FixtureError("blackhole endpoint does not match its owned container publication")
if verb != "verify":
self.docker("container", verb, identity, timeout=60)
if service == "s7" and verb == "restart":
verify_s7_publication(self.verified("container", identity))
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=("up", "down", "logs", "control"))
parser.add_argument("--environment-json")
parser.add_argument("--owner")
parser.add_argument("--service")
parser.add_argument("--container-id")
parser.add_argument("--verb")
parser.add_argument("--endpoint")
args = parser.parse_args(argv)
try:
if args.action == "control":
environment = {**os.environ, "CI_FIXTURE_LOCAL_OWNED": "1", "FIXTURE_HOST": "127.0.0.1", "CI_FIXTURE_ENV_JSON": args.environment_json or "", "CI_FIXTURE_SUFFIX": args.owner or ""}
fixtures = OwnedFixtures(environment)
fixtures.control(args.service, args.container_id, args.verb, args.endpoint)
else:
fixtures = OwnedFixtures()
getattr(fixtures, args.action)()
print(json.dumps({"status": args.action + " complete", "environment_json": str(fixtures.output)}))
return 0
except (FixtureError, RigError, OSError, ValueError, KeyError, KeyboardInterrupt):
# Keep journal and logs for an explicit same-owner down after any failure.
print("local owned fixtures failed; inspect the private run directory and use same-owner down", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())
+853
View File
@@ -0,0 +1,853 @@
#!/usr/bin/env python3
"""Final unfiltered solution gate, with explicit local fixture environment and assembly evidence."""
import argparse
import glob
import hashlib
import importlib.util
import json
import math
import os
import platform
from pathlib import Path
import re
import subprocess
import sys
import time
import xml.etree.ElementTree as ET
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[2]
spec = importlib.util.spec_from_file_location("unit_phase", HERE / "run-unit-phase.py")
phase = importlib.util.module_from_spec(spec)
spec.loader.exec_module(phase)
class FinalGateError(RuntimeError):
pass
def inventory(root=ROOT):
"""Inventory all test projects, without relying on an incomplete name suffix."""
projects = []
for path in sorted((root / "tests").rglob("*.csproj")):
tree = ET.fromstring(path.read_text())
props = {item.tag.split("}")[-1]: item.text for group in tree if group.tag.endswith("PropertyGroup") for item in group}
text = path.read_text()
if props.get("IsTestProject", "").lower() != "true" and not any(name in text for name in ("Microsoft.NET.Test.Sdk", "xunit", "NUnit", "MSTest")):
continue
sources = {source for source in path.parent.rglob("*.cs") if not any(part in {"bin", "obj"} for part in source.relative_to(path.parent).parts)}
for item in tree.iter():
if item.tag.rsplit("}", 1)[-1] == "Compile" and item.get("Include"):
sources.update(Path(p).resolve() for p in glob.glob(str(path.parent / item.get("Include").replace("\\", "/")), recursive=True) if Path(p).is_file())
content = "\n".join(source.read_text() for source in sources)
projects.append({"project": str(path.relative_to(root)), "assembly": props.get("AssemblyName") or path.stem,
"framework": props.get("TargetFramework") or props.get("TargetFrameworks"),
"sources": len(sources), "categories": sorted(set(re.findall(r'Trait\(\s*"Category"\s*,\s*"([^"\n]+)"', content))),
"literal_environment": sorted(set(re.findall(r'GetEnvironmentVariable\(\s*"([^"\n]+)"', content))),
"grpc_classes": sorted(set(re.findall(r'class\s+(GrpcData\w*Tests)\b', content)))})
if not projects:
raise FinalGateError("test project inventory is empty")
return projects
REQUIRED_FIXTURES = {"OTOPCUA_CONFIG_TEST_SERVER", "OTOPCUA_CONFIG_TEST_SA_PASSWORD", "SQL_TEST_ENDPOINT", "SQL_TEST_USER", "SQL_TEST_PASSWORD",
"SQL_PG_ENDPOINT", "SQL_PG_PASSWORD", "HISTORIAN_SQL_TEST_CONNECTION", "HISTORIAN_QUESTDB_TEST_CONNECTION", "OPCUA_SIM_ENDPOINT", "OPCUA_NAT_ENDPOINT", "OPCUA_NAT_SERVER_CERT", "OTOPCUA_LOCAL_FIXTURE_MODE", "MODBUS_SIM_ENDPOINT", "MODBUS_RTU_SIM_ENDPOINT", "S7_SIM_ENDPOINT", "S7_SIM_ALLOW_WRITES",
"AB_SERVER_ENDPOINT", "AB_SERVER_CONTROLLOGIX_ENDPOINT", "AB_SERVER_ALLOW_WRITES", "AB_LEGACY_ENDPOINT", "AB_LEGACY_SLC500_ENDPOINT", "AB_LEGACY_MICROLOGIX_ENDPOINT", "AB_LEGACY_PLC5_ENDPOINT",
"OTOPCUA_FOCAS_SIM_ENDPOINT", "OTOPCUA_FOCAS_SIM_PROFILE", "MTCONNECT_AGENT_ENDPOINT", "MTCONNECT_WRITE_TARGET",
"MQTT_FIXTURE_ENDPOINT", "MQTT_FIXTURE_PLAIN_ENDPOINT", "MQTT_FIXTURE_USERNAME", "MQTT_FIXTURE_PASSWORD", "MQTT_FIXTURE_CA_CERT", "MQTT_FIXTURE_TOPIC_PREFIX",
"OTOPCUA_HARNESS_USE_SQL", "OTOPCUA_HARNESS_SQL_HOST", "OTOPCUA_HARNESS_SQL_PASSWORD", "OTOPCUA_HARNESS_USE_LDAP", "OTOPCUA_HARNESS_LDAP_HOST", "OTOPCUA_HARNESS_LDAP_PORT", "HOST_PROBE_OPCUA_ENDPOINT"}
REQUIRED_FIXTURES.update({"SQL_ODBC_CONNECTION_STRING", "SQL_PG_USER", "SQL_MYSQL_ENDPOINT", "SQL_MYSQL_USER", "SQL_MYSQL_PASSWORD",
"SQL_ORACLE_ENDPOINT", "SQL_ORACLE_USER", "SQL_ORACLE_PASSWORD", "SQL_ORACLE_SERVICE", "SQL_BLACKHOLE_ENDPOINT", "SQL_BLACKHOLE_USER",
"SQL_BLACKHOLE_PASSWORD", "SQL_BLACKHOLE_CONTAINER_ID", "SQL_BLACKHOLE_FIXTURE_OWNER", "SQL_BLACKHOLE_ENV_JSON", "SQL_BLACKHOLE_CONTROL_SCRIPT",
"S7_RECONNECT_BOUNCE_CMD", "S7_TIMEOUT_OUTAGE_START_CMD", "S7_TIMEOUT_OUTAGE_STOP_CMD"})
ODBC_DRIVER = Path("/opt/homebrew/opt/psqlodbc/lib/psqlodbcw.so")
ODBC_DRIVER_MANAGER = Path("/opt/homebrew/opt/unixodbc/lib/libodbc.2.dylib")
SDK_LIFECYCLE_RUN = "sdk-lifecycle-diagnostic"
SDK_LIFECYCLE_ASSEMBLY = "ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests"
SDK_LIFECYCLE_CASE = SDK_LIFECYCLE_ASSEMBLY + ".Sdk2LifecycleSoakTests.Repeated_lifecycles_return_resources_to_a_steady_baseline"
SDK_LIFECYCLE_SKIP = "Opt in with OTOPCUA_SDK2_SOAK=1 and an explicit soak mode."
SDK_LIFECYCLE_SECONDS = 90
AB_CIP_ASSEMBLY = "ZB.MOM.WW.OtOpcUa.Driver.AbCip.IntegrationTests"
PROFILE_PROJECTS = {**{"modbus-" + p: "ZB.MOM.WW.OtOpcUa.Driver.Modbus.IntegrationTests" for p in ("dl205", "mitsubishi", "s7_1500", "exception_injection")},
**{"ab-" + p: AB_CIP_ASSEMBLY for p in ("compactlogix", "micro800", "guardlogix")}}
AB_DIFFERENTIAL_RUN = "ab-software-differential"
_TRANSPORT_TESTS = AB_CIP_ASSEMBLY + ".Differential.TransportDifferentialTests."
_LATENCY_TESTS = AB_CIP_ASSEMBLY + ".Differential.PollLatencyComparisonTests."
AB_DIFFERENTIAL_MIX_CASE = AB_CIP_ASSEMBLY + ".Differential.EvidenceTests.Mixed_string_array_and_scalar_reads_travel_as_one_multiple_service_packet"
AB_DIFFERENTIAL_MIX_TAGS = "TestString|String|1;TestArray[1]|DInt|1;TestArray|DInt|16;TestDINT|DInt|1;TestBOOL|Bool|1"
AB_DIFFERENTIAL_LIVE_CASES = frozenset({_TRANSPORT_TESTS + method for method in (
"Browse_listings_decode_to_identical_tag_sets_through_both_enumerators",
"Every_template_decodes_to_an_identical_shape_through_both_readers",
"Every_selected_tag_reads_identically_through_both_transports",
"Libplctag_and_native_are_never_connected_at_the_same_time",
"No_failed_libplctag_tag_is_left_with_a_live_native_callback",
"The_native_side_makes_exactly_one_forward_open_over_the_whole_run",
"The_native_side_closes_its_one_connection_with_exactly_one_forward_close",
)} | {_LATENCY_TESTS + "Native_poll_p95_is_within_ten_percent_of_libplctag", AB_DIFFERENTIAL_MIX_CASE})
AB_DIFFERENTIAL_CASES = AB_DIFFERENTIAL_LIVE_CASES | {_TRANSPORT_TESTS + method for method in (
"The_harness_is_read_only_by_construction",
"The_comparison_flags_every_divergence_and_excuses_only_a_native_type_mismatch",
"A_live_value_is_compared_structurally_and_a_stable_one_by_value",
)} | {_LATENCY_TESTS + "Tag_pick_takes_atomic_scalars_only_and_repeats_a_short_set_visibly"}
AB_DIFFERENTIAL_SKIP = ("AB_DIFF_ENDPOINT is not set — point it at host:port of the one controller to compare "
"(e.g. 10.100.0.35:44818 for ab_server).")
def ab_loopback_port(value):
match = re.fullmatch(r"127\.0\.0\.1:([1-9][0-9]{0,4})", value)
if match and 1 < int(match[1]) <= 65535:
return int(match[1])
raise FinalGateError("AB software fixtures require an explicit owned loopback port")
def child_environment(fixture, inherited=None):
"""Strip ambient application/fixture settings before adding explicit local-owned values."""
if not isinstance(fixture, dict) or not REQUIRED_FIXTURES.issubset(fixture) or any(not isinstance(k, str) or not isinstance(v, str) or not v for k, v in fixture.items()):
raise FinalGateError("required local fixture variables are missing")
if fixture.get("OTOPCUA_LOCAL_FIXTURE_MODE") != "1": raise FinalGateError("local fixture mode must be explicit")
if any(fixture.get(key) != "1" for key in ("OTOPCUA_HARNESS_USE_SQL", "OTOPCUA_HARNESS_USE_LDAP", "S7_SIM_ALLOW_WRITES", "AB_SERVER_ALLOW_WRITES")):
raise FinalGateError("owned software fixture opt-ins must be explicit")
odbc = fixture["SQL_ODBC_CONNECTION_STRING"]
if "Driver={" + str(ODBC_DRIVER) + "}" not in odbc or re.search(r"(?:^|;)\s*DSN\s*=", odbc, re.I):
raise FinalGateError("ODBC requires the explicit installed local driver and no DSN")
allowed_keys = REQUIRED_FIXTURES | {"MODBUS_SIM_PROFILE", "AB_SERVER_PROFILE", "AB_SERVER_COMPOSE_PROFILE", "AB_LEGACY_CIP_PATH"}
if set(fixture) - allowed_keys:
raise FinalGateError("fixture environment contains an unapproved variable")
ab_loopback_port(fixture["AB_SERVER_ENDPOINT"])
ab_loopback_port(fixture["AB_SERVER_CONTROLLOGIX_ENDPOINT"])
# Parse actual endpoint/connection hosts, not incidental occurrences of "localhost"
# in a password or path. The shared rig validator rejects all external hosts.
import rig
try: rig.validate_fixture_endpoints(fixture, local_services={"localhost"})
except rig.RigError as error: raise FinalGateError("a fixture endpoint is not loopback") from error
base = {k: v for k, v in (os.environ if inherited is None else inherited).items() if k in phase.ENV_ALLOWLIST}
base.update(fixture)
base.pop("OTOPCUA_UNIT_ONLY_DISCOVERY", None)
base["AKKA_TEST_TIMEFACTOR"] = "3"
return base
def private_text(path, value):
"""Write empty or populated evidence without secret-writer nonempty semantics."""
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w") as stream: stream.write(value)
def logged_run(name, command, directory, environment, *, timeout=21600):
private_json(directory / (name + ".command.json"), command)
with private_stream(directory / (name + ".stdout.log")) as out, private_stream(directory / (name + ".stderr.log")) as err:
result = subprocess.run(command, cwd=ROOT, env=environment, stdout=out, stderr=err, timeout=timeout)
return result.returncode
def private_stream(path):
return os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w")
def private_json(path, value):
private_text(path, json.dumps(value, indent=2) + "\n")
def macos_odbc_testhost_args():
# VSTest launches a native testhost, where the ODBC driver manager is loaded.
return ["--environment", f"DYLD_LIBRARY_PATH={ODBC_DRIVER_MANAGER.parent}"] if platform.system() == "Darwin" else []
def solution_commands(directory):
solution = "ZB.MOM.WW.OtOpcUa.slnx"
return (["dotnet", "build", solution, "-c", "Release", "--no-restore", "-m:1", "-p:TestTfmsInParallel=false"],
["dotnet", "test", solution, "-c", "Release", "--no-build", "-m:1", "-p:TestTfmsInParallel=false", "--nologo", "--settings", "scripts/ci/ci.runsettings", "--blame-hang", "--blame-hang-timeout", "20m", "--blame-hang-dump-type", "none", "--logger", "trx", *macos_odbc_testhost_args(), "--results-directory", str(directory)])
def discover_project(project, directory, environment, *, expression=None):
directory.mkdir(parents=True, mode=0o700)
command = ["dotnet", "test", project["project"], "-c", "Release", "-m:1", "-p:TestTfmsInParallel=false",
"--no-build", "--list-tests", "--settings", "scripts/ci/ci.runsettings", *macos_odbc_testhost_args()]
if expression is not None:
command.extend(["--filter", expression])
exit_code = logged_run("discovery", command, directory, environment, timeout=1200)
names = phase.discover_names((directory / "discovery.stdout.log").read_text())
if exit_code or not names:
raise FinalGateError("test discovery failed for " + project["assembly"])
return {"assembly": project["assembly"], "tests": names}
def run_profile(project, test, directory, environment, *, selected=None):
expression = "|".join("FullyQualifiedName=" + name for name in sorted(selected)) if selected is not None else None
discovery = discover_project(project, directory, environment, expression=expression)
private_json(directory / "discovery.json", [discovery])
if selected is not None and set(discovery["tests"]) != selected:
raise FinalGateError("supplemental discovery differs from the exact test selection")
profile_test = test.copy()
profile_test[2] = project["project"]
profile_test[profile_test.index("--results-directory") + 1] = str(directory / "trx")
if expression is not None:
profile_test.extend(["--filter", expression])
return logged_run("test", profile_test, directory, environment, timeout=7200)
def differential_environment(base):
"""Enable only the read-only harness against the owned ControlLogix simulator."""
endpoint = base.get("AB_SERVER_ENDPOINT", "")
ab_loopback_port(endpoint)
if base.get("AB_SERVER_COMPOSE_PROFILE") != "controllogix" or base.get("AB_SERVER_CONTROLLOGIX_ENDPOINT") != endpoint:
raise FinalGateError("software differential requires the owned loopback ControlLogix fixture")
environment = {key: value for key, value in base.items() if key in phase.ENV_ALLOWLIST}
environment.update({"OTOPCUA_LOCAL_FIXTURE_MODE": "1",
"AB_SERVER_ENDPOINT": "127.0.0.1:1", "AB_SERVER_CONTROLLOGIX_ENDPOINT": "127.0.0.1:1",
"AB_DIFF_ENDPOINT": endpoint, "AB_DIFF_COUNT_OPENS": "1", "AB_DIFF_FAMILY": "ControlLogix", "AB_DIFF_PATH": "1,0",
"AB_EVID_MIX": "1", "AB_EVID_TAGS": AB_DIFFERENTIAL_MIX_TAGS})
return environment
WORKER_NAME = "ZB.MOM.WW.OtOpcUa.ScriptWorker"
WORKER_PROJECT = "src/Server/" + WORKER_NAME + "/" + WORKER_NAME + ".csproj"
def native_worker_rid(system=None, architecture=None):
system = (platform.system() if system is None else system).lower()
architecture = (platform.machine() if architecture is None else architecture).lower()
os_name = {"darwin": "osx", "linux": "linux", "windows": "win"}.get(system)
cpu = {"arm64": "arm64", "aarch64": "arm64", "x86_64": "x64", "amd64": "x64"}.get(architecture)
if os_name is None or cpu is None:
raise FinalGateError("unsupported native ScriptWorker publishing platform")
return os_name + "-" + cpu
def worker_output_identity(output, rid):
"""Require the named executable, self-contained metadata and matching native RID."""
entry = output / (WORKER_NAME + (".exe" if rid.startswith("win-") else ""))
required = [entry, *(output / (WORKER_NAME + suffix) for suffix in (".dll", ".deps.json", ".runtimeconfig.json"))]
if any(path.is_symlink() or not path.is_file() for path in required) or not os.access(entry, os.X_OK):
raise FinalGateError("published ScriptWorker executable or identity files are missing")
options = json.loads((output / (WORKER_NAME + ".runtimeconfig.json")).read_text()).get("runtimeOptions", {})
dependencies = json.loads((output / (WORKER_NAME + ".deps.json")).read_text())
frameworks = options.get("includedFrameworks")
target = dependencies.get("runtimeTarget", {}).get("name")
if (not isinstance(frameworks, list) or not frameworks or "framework" in options or "frameworks" in options
or not isinstance(target, str) or not target.endswith("/" + rid)
or not any(name.startswith(WORKER_NAME + "/") and value.get("type") == "project"
for name, value in dependencies.get("libraries", {}).items())):
raise FinalGateError("published ScriptWorker is not the expected self-contained native worker")
files = {}
for path in sorted(output.rglob("*")):
if path.is_symlink():
raise FinalGateError("published ScriptWorker contains a symlink")
if path.is_file():
files[path.relative_to(output).as_posix()] = {"sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
"mode": path.stat().st_mode & 0o777}
return entry, files
def prepare_script_worker(directory, *, environment, identity):
"""Publish only to this final run's fresh owned artifact directory."""
directory = Path(directory)
if (not directory.is_absolute() or directory.is_symlink() or not directory.is_dir()
or not isinstance(identity.get("revision"), str) or not identity["revision"]
or not re.fullmatch(r"[0-9a-f]{64}", identity.get("execution_input_sha256", ""))):
raise FinalGateError("ScriptWorker publishing requires an owned final directory and source identity")
rid = native_worker_rid()
output = directory / "script-worker"
output.mkdir(mode=0o700, exist_ok=False)
clean = {key: value for key, value in environment.items() if key in phase.ENV_ALLOWLIST}
command = ["dotnet", "publish", str(ROOT / WORKER_PROJECT), "-c", "Release", "--runtime", rid,
"--self-contained", "true", "-m:1", "-p:UseAppHost=true", "-p:PublishSingleFile=false", "-p:PublishTrimmed=false",
"--output", str(output)]
if logged_run("script-worker-publish", command, directory, clean, timeout=1200):
raise FinalGateError("self-contained ScriptWorker publishing failed")
entry, files = worker_output_identity(output, rid)
private_json(directory / "script-worker.json", {"project": WORKER_PROJECT, "runtime_identifier": rid,
"source_revision": identity["revision"], "execution_input_sha256": identity["execution_input_sha256"],
"entry": str(entry), "files": files})
return {"OTOPCUA_SCRIPTWORKER_TEST_PATH": str(entry)}
def script_worker_identity_matches(directory):
try:
receipt = json.loads((directory / "script-worker.json").read_text())
entry, files = worker_output_identity(directory / "script-worker", receipt["runtime_identifier"])
return receipt["project"] == WORKER_PROJECT and receipt["entry"] == str(entry) and receipt["files"] == files
except (FinalGateError, OSError, ValueError, KeyError, TypeError):
return False
SATURATION_OBSERVER_ENV = "OTOPCUA_SDK2_SATURATION_OBSERVER"
SATURATION_OBSERVER_ASSEMBLY = "ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests"
SATURATION_OBSERVER_METHOD = SATURATION_OBSERVER_ASSEMBLY + ".Sdk2LifecycleSoakTests.Saturation_protocol_actual_observer_drains_and_rejects_extra_foreign_markers"
SATURATION_OBSERVER_TOOLS = ROOT / "scripts/validation/opcua-lifecycle-memory"
SATURATION_OBSERVER_BUILDER = SATURATION_OBSERVER_TOOLS / "build_saturation_observer.py"
DOTNET_TRACE_VERSION = "9.0.661903"
TRACE_LIBRARIES = ("Microsoft.Diagnostics.NETCore.Client.dll", "Microsoft.Diagnostics.Tracing.TraceEvent.dll",
"Microsoft.Diagnostics.FastSerialization.dll")
def saturation_observer_inputs(libraries):
tool_deps = libraries / "dotnet-trace.deps.json"
paths = [SATURATION_OBSERVER_BUILDER, SATURATION_OBSERVER_TOOLS / "SaturationObserver.cs",
tool_deps, *(libraries / name for name in TRACE_LIBRARIES)]
if any(path.is_symlink() or not path.is_file() or not path.stat().st_size for path in paths):
raise FinalGateError("saturation observer requires installed dotnet-trace " + DOTNET_TRACE_VERSION + " libraries")
dependencies = json.loads(tool_deps.read_text())
if "dotnet-trace/" + DOTNET_TRACE_VERSION not in dependencies.get("libraries", {}):
raise FinalGateError("saturation observer dotnet-trace installation has the wrong version")
return {path.name: hashlib.sha256(path.read_bytes()).hexdigest() for path in paths}
def saturation_observer_libraries():
return Path.home() / f".dotnet/tools/.store/dotnet-trace/{DOTNET_TRACE_VERSION}/dotnet-trace/{DOTNET_TRACE_VERSION}/tools/net8.0/any"
def saturation_observer_output(directory, inputs):
package = directory / "saturation-observer"
build = package / "build"
runtime = build / "bin/Release/net10.0"
entry = runtime / "observer.dll"
config = runtime / "observer.runtimeconfig.json"
deps = runtime / "observer.deps.json"
directories = (package, build, runtime.parent.parent, runtime.parent, runtime)
required = (entry, config, deps, *(runtime / name for name in TRACE_LIBRARIES))
if (any(path.is_symlink() or not path.is_dir() for path in directories)
or any(path.is_symlink() or not path.is_file() or not path.stat().st_size for path in required)):
raise FinalGateError("saturation observer portable build is incomplete")
options = json.loads(config.read_text()).get("runtimeOptions", {})
dependencies = json.loads(deps.read_text())
frameworks = options.get("frameworks", [])
if (options.get("tfm") != "net10.0" or "includedFrameworks" in options
or {item.get("name") for item in frameworks if str(item.get("version", "")).startswith("10.")}
!= {"Microsoft.NETCore.App", "Microsoft.AspNetCore.App"}
or dependencies.get("runtimeTarget", {}).get("name") != ".NETCoreApp,Version=v10.0"
or not any(name.startswith("observer/") and item.get("type") == "project" for name, item in dependencies.get("libraries", {}).items())):
raise FinalGateError("saturation observer must be a framework-dependent net10.0 build")
files = {}
for path in sorted(runtime.rglob("*")):
if path.is_symlink():
raise FinalGateError("saturation observer output contains a symlink")
if path.is_file():
files[path.relative_to(runtime).as_posix()] = {"sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
"mode": path.stat().st_mode & 0o777}
if any(files[name]["sha256"] != inputs[name] for name in TRACE_LIBRARIES):
raise FinalGateError("saturation observer did not copy the exact dotnet-trace libraries")
return entry, files
def saturation_observer_receipt(directory, identity, inputs):
entry, files = saturation_observer_output(directory, inputs)
return {"source_revision": identity["revision"], "execution_input_sha256": identity["execution_input_sha256"],
"entry": str(entry), "dotnet_trace_version": DOTNET_TRACE_VERSION, "inputs": inputs, "files": files}
def prepare_saturation_observer(directory, *, environment, identity):
"""Build the portable observer for the two short SDK protocol controls."""
if (not directory.is_absolute() or directory.is_symlink() or not directory.is_dir()
or not identity.get("revision") or not re.fullmatch(r"[0-9a-f]{64}", identity.get("execution_input_sha256", ""))):
raise FinalGateError("saturation observer requires an owned final directory and source identity")
libraries = saturation_observer_libraries()
inputs = saturation_observer_inputs(libraries)
package = directory / "saturation-observer"
package.mkdir(mode=0o700)
clean = {key: value for key, value in environment.items() if key in phase.ENV_ALLOWLIST}
command = [sys.executable, str(SATURATION_OBSERVER_BUILDER), "--output", str(package / "build"), "--libraries", str(libraries)]
if logged_run("saturation-observer-build", command, directory, clean, timeout=1200):
raise FinalGateError("portable saturation observer build failed")
if inputs != saturation_observer_inputs(libraries):
raise FinalGateError("saturation observer inputs changed during build")
receipt = saturation_observer_receipt(directory, identity, inputs)
private_json(directory / "saturation-observer.json", receipt)
return {SATURATION_OBSERVER_ENV: receipt["entry"]}
def saturation_observer_identity_matches(directory, identity, optins):
try:
receipt_path = directory / "saturation-observer.json"
if receipt_path.is_symlink():
return False
receipt = json.loads(receipt_path.read_text())
inputs = saturation_observer_inputs(saturation_observer_libraries())
return (receipt == saturation_observer_receipt(directory, identity, inputs)
and optins.get(SATURATION_OBSERVER_ENV) == receipt["entry"])
except (FinalGateError, OSError, ValueError, KeyError, TypeError, AttributeError):
return False
def saturation_observer_protocol_rows(rows):
selected = [row for row in rows if row["assembly"] == SATURATION_OBSERVER_ASSEMBLY
and row["test"].split("(", 1)[0] == SATURATION_OBSERVER_METHOD]
expected = {f"{SATURATION_OBSERVER_METHOD}(foreignMarker: {marker})" for marker in ("False", "True")}
complete = len(selected) == len(expected) and {row["test"] for row in selected if row["outcome"] == "Passed"} == expected
return {"rows": selected, "passed": complete}
def read_results(directory, projects, *, minimum=12000):
"""Read concrete TRX rows; do not mistake source method names for theory cases."""
assemblies = {}; skipped = []; failures = []; rows = []; total = 0; seen_classes = set()
for path in sorted(Path(directory).rglob("*.trx")):
tree = ET.parse(path).getroot(); definitions = {}
for definition in tree.findall(".//{*}UnitTest"):
method = definition.find("{*}TestMethod")
if method is not None:
assembly = Path(method.get("codeBase", definition.get("storage", "")).replace("\\", "/")).stem
cls = method.get("className", "").split(",")[0]
name = method.get("name", "")
# xUnit lists delayed theories by their method. Its TRX definition retains
# that name and ID while each result carries its concrete argument display.
canonical_name = cls + "." + name
deferred_parent = None
if method.get("adapterTypeName") == "executor://xunit/VsTestRunner3/netcore/" and definition.get("name") == canonical_name:
deferred_parent = canonical_name
definitions[definition.get("id")] = (assembly, cls, name, deferred_parent)
for result in tree.findall("{*}Results/{*}UnitTestResult"):
test_id = result.get("testId")
assembly, cls, method, deferred_parent = definitions.get(test_id, ("", "", "", None))
if not assembly: raise FinalGateError("result has no test assembly identity")
row = assemblies.setdefault(assembly, {"executed": 0, "passed": 0, "failed": 0, "skipped": 0, "files": set()})
row["files"].add(str(path)); outcome = result.get("outcome")
display = result.get("testName", "")
name = display if display.startswith(cls + ".") else cls + "." + method
seen_classes.add((assembly, cls.rsplit(".", 1)[-1]))
message = result.find(".//{*}Message"); reason = message.text if message is not None else "No reason supplied"
item = {"assembly": assembly, "test": name, "outcome": outcome, "reason": reason, "trx": str(path)}
if test_id and deferred_parent and display.startswith(deferred_parent + "(") and display.endswith(")"):
item["deferred_theory"] = {"method": deferred_parent, "test_id": test_id, "execution_id": result.get("executionId")}
rows.append(item)
if outcome == "Passed": row["passed"] += 1; row["executed"] += 1; total += 1
elif outcome == "NotExecuted": row["skipped"] += 1; skipped.append(item)
else: row["failed"] += 1; row["executed"] += 1; total += 1; failures.append(item)
missing = [p["assembly"] for p in projects if p["assembly"] not in assemblies or not assemblies[p["assembly"]]["executed"]]
missing_grpc = sorted({(project["assembly"], name) for project in projects for name in project["grpc_classes"]} - seen_classes)
skipped_grpc = [row for row in skipped if ".GrpcData" in row["test"]]
for row in assemblies.values(): row["files"] = sorted(row["files"])
return {"executed": total, "assemblies": assemblies, "rows": rows, "skipped": skipped, "failures": failures,
"missing_assemblies": missing, "missing_grpc_classes": missing_grpc, "skipped_grpc": skipped_grpc,
"passed": total >= minimum and not failures and not missing and not missing_grpc and not skipped}
def unavailable_records(path):
"""An exact, reviewable decision, never a category or pattern exclusion.
JSON is a list of {assembly,test,reason,kind,requires,evidence,next_gate}.
evidence is an existing absolute private file documenting the observed local
prerequisite check. kind is hardware/proprietary/platform/explicit-unavailable.
The final report retains its SHA256, exact skip reason and next required gate.
"""
if path is None: return {}
items = json.loads(Path(path).read_text()); result = {}
if not isinstance(items, list): raise FinalGateError("unavailable evidence must be a list")
for item in items:
keys = ("assembly", "test", "reason", "kind", "requires", "evidence", "next_gate")
if not isinstance(item, dict) or any(not isinstance(item.get(k), str) or not item[k].strip() for k in keys):
raise FinalGateError("unavailable evidence requires exact identity, reason, prerequisite, evidence and next gate")
if item["kind"] not in {"hardware", "proprietary", "platform", "explicit-unavailable"} or ".GrpcData" in item["test"]:
raise FinalGateError("required feature coverage cannot be marked unavailable")
if any(c in item["test"] for c in ("*", "?")): raise FinalGateError("unavailable test patterns are forbidden")
evidence = Path(item["evidence"])
if not evidence.is_absolute() or not evidence.is_file(): raise FinalGateError("unavailable evidence file is missing")
key = (item["assembly"], item["test"])
if key in result: raise FinalGateError("duplicate unavailable identity")
result[key] = {**item, "evidence_sha256": hashlib.sha256(evidence.read_bytes()).hexdigest()}
return result
def discovery_gaps(expected, rows):
observed = {(row["assembly"], row["test"]) for row in rows}
enumerated = {(assembly, name.split("(", 1)[0]) for assembly, name in expected if "(" in name}
candidates = {}
for row in rows:
if "deferred_theory" in row:
key = (row["assembly"], row["deferred_theory"]["method"])
candidates.setdefault(key, []).append(row)
expansions = []
for parent, cases in sorted(candidates.items()):
if parent not in expected or parent in observed or parent in enumerated:
continue
identities = {(case["trx"], case["deferred_theory"]["test_id"]) for case in cases}
executions = {case["deferred_theory"]["execution_id"] for case in cases}
names = {(case["assembly"], case["test"]) for case in cases}
# Different rows can format to the same display, even within one theory.
if len(identities) != 1 or len(executions) != len(cases) or not all(executions):
continue
trx, test_id = next(iter(identities))
expansions.append({"assembly": parent[0], "method": parent[1], "test_id": test_id, "trx": trx,
"rows": [{"test": case["test"], "outcome": case["outcome"], "execution_id": case["deferred_theory"]["execution_id"]}
for case in sorted(cases, key=lambda case: case["test"])]})
observed.difference_update(names)
observed.add(parent)
return sorted(expected - observed), sorted(observed - expected), expansions
def sdk_lifecycle_receipt(report, discovery, path, revision):
"""Bind the fresh-process diagnostic to its exact discovered and executed case."""
rows = report["rows"]
expected = [{"assembly": SDK_LIFECYCLE_ASSEMBLY, "tests": [SDK_LIFECYCLE_CASE]}]
if discovery != expected or len(rows) != 1:
return None
row = rows[0]
if (row["assembly"], row["test"], row["outcome"]) != (SDK_LIFECYCLE_ASSEMBLY, SDK_LIFECYCLE_CASE, "Passed"):
return None
try:
if path.is_symlink():
return None
events = [json.loads(line) for line in path.read_text().splitlines()]
first, last = events[0], events[-1]
observed = last["seconds"]
cycles = last["cycles"]
if (first["kind"] == "start" and first["mode"] == "diagnostic" and first["build"] == revision
and first["requestedSeconds"] == SDK_LIFECYCLE_SECONDS
and last["kind"] == "complete" and last["mode"] == "diagnostic"
and last["satisfiesTwoHourDuration"] is False
and type(observed) in (int, float) and math.isfinite(observed)
and observed >= SDK_LIFECYCLE_SECONDS and type(cycles) is int and cycles >= 3
and sum(event.get("kind") == "quiescent" for event in events) == cycles):
return {"test": row["test"], "trx": row["trx"], "observed_seconds": observed, "cycles": cycles,
"path": str(path), "sha256": hashlib.sha256(path.read_bytes()).hexdigest()}
except (OSError, ValueError, IndexError, KeyError, TypeError, AttributeError):
return None
return None
def reconcile(baseline, overlays, discovery, profile_discovery, unavailable, *, differential=None,
differential_discovery=None, sdk_lifecycle_verified=False):
"""Preserve baseline12000 independently; overlays only close explicit profile skips."""
profile_reports = {"baseline": baseline, **overlays}
reports = profile_reports.copy()
passed = {(r["assembly"], r["test"]) for report in profile_reports.values() for r in report["rows"] if r["outcome"] == "Passed"}
differential_gaps = {}
differential_passed = set()
if differential is not None:
reports[AB_DIFFERENTIAL_RUN] = differential
selected = {(AB_CIP_ASSEMBLY, name) for name in AB_DIFFERENTIAL_CASES}
discovered = {(d["assembly"], name) for d in differential_discovery for name in d["tests"]}
actual = {(r["assembly"], r["test"]) for r in differential["rows"]}
if (len(differential_discovery) != 1 or selected != discovered or selected != actual or len(actual) != len(differential["rows"])
or differential["missing_assemblies"] or differential["missing_grpc_classes"] or differential["skipped_grpc"]):
differential_gaps = {"missing_discovery": sorted(selected - discovered), "unexpected_discovery": sorted(discovered - selected),
"missing_results": sorted(selected - actual), "unexpected_results": sorted(actual - selected),
"duplicate_rows": len(actual) != len(differential["rows"]), "missing_assemblies": differential["missing_assemblies"],
"missing_grpc_classes": differential["missing_grpc_classes"], "skipped_grpc": differential["skipped_grpc"]}
else:
differential_passed = {(r["assembly"], r["test"]) for r in differential["rows"]
if r["outcome"] == "Passed" and r["test"] in AB_DIFFERENTIAL_LIVE_CASES}
observed = {(r["assembly"], r["test"]) for r in baseline["rows"]}
expected = {(d["assembly"], name) for d in discovery for name in d["tests"]}
missing, unexpected, baseline_expansions = discovery_gaps(expected, baseline["rows"])
decisions = []; unresolved = []; used = set()
for report_name, report in reports.items():
for row in report["skipped"]:
key = (row["assembly"], row["test"])
if (sdk_lifecycle_verified and report_name == "baseline" and key == (SDK_LIFECYCLE_ASSEMBLY, SDK_LIFECYCLE_CASE)
and row["reason"] == SDK_LIFECYCLE_SKIP):
decisions.append({**row, "run": report_name, "disposition": "executed-in-isolated-diagnostic",
"passed_in": [SDK_LIFECYCLE_RUN]})
elif key in unavailable and unavailable[key]["reason"] == row["reason"]:
used.add(key); decisions.append({**row, "run": report_name, "disposition": "unavailable", "evidence": unavailable[key]})
elif report_name != AB_DIFFERENTIAL_RUN and key in differential_passed and row["reason"] == AB_DIFFERENTIAL_SKIP:
decisions.append({**row, "run": report_name, "disposition": "executed-in-software-differential", "passed_in": [AB_DIFFERENTIAL_RUN]})
elif key in passed and ((row["assembly"].endswith(".Driver.Modbus.IntegrationTests") and row["reason"].startswith("MODBUS_SIM_PROFILE")) or
(row["assembly"].endswith(".Driver.AbCip.IntegrationTests") and "AB_SERVER_COMPOSE_PROFILE" in row["reason"])):
decisions.append({**row, "run": report_name, "disposition": "executed-in-profile", "passed_in": [n for n, p in profile_reports.items() if any((r["assembly"], r["test"]) == key and r["outcome"] == "Passed" for r in p["rows"])]})
else: unresolved.append({**row, "run": report_name})
# A project with zero executed tests is permitted only when its entire exact
# discovery set has evidence and concrete NotExecuted rows, with no missing rows.
fully_unavailable = []
missing_assemblies = []
for assembly in baseline["missing_assemblies"]:
names = {key for key in expected if key[0] == assembly}
if names and names <= used and names <= observed: fully_unavailable.append(assembly)
else: missing_assemblies.append(assembly)
failed = [r for p in reports.values() for r in p["failures"]]
unused = sorted(set(unavailable) - used)
overlay_gaps = {}
overlay_expansions = {}
for name, report in overlays.items():
discovered = profile_discovery.get(name, [])
wanted = {(d["assembly"], test) for d in discovered for test in d["tests"]}
missing_overlay, unexpected_overlay, overlay_expansions[name] = discovery_gaps(wanted, report["rows"])
discovery_matches_assembly = len(discovered) == 1 and discovered[0]["assembly"] == PROFILE_PROJECTS.get(name)
if (not discovery_matches_assembly or not wanted or missing_overlay or unexpected_overlay or not report["executed"]
or report["missing_assemblies"] or report["missing_grpc_classes"] or report["skipped_grpc"]):
overlay_gaps[name] = {"missing": missing_overlay, "unexpected": unexpected_overlay,
"executed": report["executed"], "discovery_matches_assembly": discovery_matches_assembly,
"missing_assemblies": report["missing_assemblies"], "missing_grpc_classes": report["missing_grpc_classes"],
"skipped_grpc": report["skipped_grpc"]}
missing_profiles = sorted(set(PROFILE_PROJECTS) - set(overlays))
return {"baseline_executed": baseline["executed"], "overlay_executed": {n: p["executed"] for n, p in overlays.items()},
"skip_decisions": decisions, "unresolved_skips": unresolved, "failures": failed,
"missing_results": missing, "unexpected_results": unexpected, "missing_assemblies": missing_assemblies,
"fully_unavailable_projects": fully_unavailable, "unused_unavailable_evidence": unused,
"missing_grpc_classes": baseline["missing_grpc_classes"], "overlay_discovery_gaps": overlay_gaps, "missing_profiles": missing_profiles,
"deferred_theory_expansions": {"baseline": baseline_expansions, "profiles": overlay_expansions},
"software_differential_discovery_gaps": differential_gaps,
"passed": baseline["executed"] >= 12000 and not any((failed, unresolved, missing, unexpected, missing_assemblies, baseline["missing_grpc_classes"], baseline["skipped_grpc"], unused, overlay_gaps, missing_profiles, differential_gaps))}
def software_optins(directory, revision):
directory.mkdir(mode=0o700)
outputs = {"OTOPCUA_SDK2_SOAK_OUTPUT": directory / "sdk-diagnostic.jsonl", "OTOPCUA_EVENT_PERF_OUT": directory / "folder-events.jsonl", "OTOPCUA_SCRIPT_PERF_OUT": directory / "script-perf.txt"}
if any(path.exists() for path in outputs.values()): raise FinalGateError("software measurement output must be fresh")
return {"OTOPCUA_SDK2_SOAK": "1", "OTOPCUA_SDK2_SOAK_MODE": "diagnostic", "OTOPCUA_SDK2_SOAK_SECONDS": str(SDK_LIFECYCLE_SECONDS),
"OTOPCUA_SDK2_CLOSE_CONTROL": "1", "OTOPCUA_SOAK_BUILD_SHA": revision,
"OTOPCUA_EVENT_PERF": "1", "OTOPCUA_EVENT_PERF_REPORTS": "1000", "OTOPCUA_EVENT_PERF_ROUNDS": "2",
"OTOPCUA_SCRIPT_PERF": "1", "OTOPCUA_SCRIPT_PERF_SECONDS": "10", "HISTORIAN_QUESTDB_STRESS_SECONDS": "60",
"AB_LEASE_SOAK_CYCLES": "100", "OTOPCUA_BENCH": "1", **{k: str(v.resolve()) for k, v in outputs.items()}}
GENERATED_PARTS = {"bin", "obj", "__pycache__"}
RECEIPT_PARTS = {"artifacts", "evidence"}
NON_INPUT_SUFFIXES = {".md", ".rst", ".adoc", ".log", ".jsonl", ".trx", ".diff", ".since",
".env", ".key", ".pem", ".pfx", ".p12", ".p8"}
CODE_SUFFIXES = {".cs", ".csproj", ".py", ".sh", ".ps1", ".psm1", ".js", ".proto", ".razor",
".css", ".axaml", ".props", ".targets", ".rsp"}
def execution_input_path(name):
"""Include the whole executable source/test/harness tree, not review prose or run artifacts."""
if not name or name.startswith("/") or "\\" in name or any(part in {"", ".", ".."} for part in name.split("/")):
raise FinalGateError("unsafe candidate input path")
parts = name.split("/")
suffix = Path(name).suffix.lower()
if parts[0] in {"artifacts", ".playwright-mcp"} or any(part.lower() in GENERATED_PARTS for part in parts[:-1]): return False
if any(part.lower() in RECEIPT_PARTS for part in parts[1:-1]) and suffix not in CODE_SUFFIXES: return False
if any(part.lower() in {"secrets", "private"} for part in parts[:-1]) and suffix not in CODE_SUFFIXES: return False
if suffix in NON_INPUT_SUFFIXES: return False
if parts[0] in {"src", "tests", "scripts", "tools", "ci"}: return True
# These root files select the solution, compiler/package/toolchain and Docker build behavior.
return name == ".config/dotnet-tools.json" or len(parts) == 1 and (name.startswith("Directory.") or name in {
"global.json", "NuGet.config", "nuget.config", "ZB.MOM.WW.OtOpcUa.slnx", ".dockerignore", ".editorconfig", ".gitignore"})
def execution_input_inventory(root, names):
"""Hash actual bytes and mode; index status and HEAD are only provenance."""
files = {}
for name in sorted(set(names)):
if not execution_input_path(name): continue
path = root / name
if any(parent.is_symlink() for parent in (path, *list(path.parents)[:len(name.split("/")) - 1])):
raise FinalGateError("candidate input contains a symlink")
if not path.exists():
continue # a tested deletion remains identical after it is committed
if not path.is_file():
raise FinalGateError("candidate input is not a regular file")
files[name] = {"sha256": hashlib.sha256(path.read_bytes()).hexdigest(), "mode": path.stat().st_mode & 0o777}
if not files: raise FinalGateError("candidate execution input inventory is empty")
return files
def source_identity(root=ROOT):
def git(*args): return subprocess.check_output(["git", *args], cwd=root)
names = [name for name in git("ls-files", "--cached", "--others", "--exclude-standard", "-z").decode().split("\0") if name]
files = execution_input_inventory(root, names)
untracked = git("ls-files", "--others", "--exclude-standard", "-z").decode().split("\0")
return {"revision": git("rev-parse", "HEAD").decode().strip(), "diff_sha256": hashlib.sha256(git("diff", "HEAD", "--binary")).hexdigest(),
"untracked_sha256": {p: files[p]["sha256"] for p in untracked if p in files}, "execution_input_files": files,
"execution_input_sha256": hashlib.sha256(json.dumps(files, sort_keys=True, separators=(",", ":")).encode()).hexdigest()}
def execution_inputs_match(before, after):
digest = before.get("execution_input_sha256")
return isinstance(digest, str) and len(digest) == 64 and bool(before.get("execution_input_files")) and \
bool(after.get("execution_input_files")) and digest == after.get("execution_input_sha256")
def profile_environments(path, base):
documents = json.loads(Path(path).read_text())
if set(documents) != set(PROFILE_PROJECTS): raise FinalGateError("all seven owned profile environments are required")
result = {}
control_port = ab_loopback_port(base["AB_SERVER_CONTROLLOGIX_ENDPOINT"])
if base.get("AB_SERVER_COMPOSE_PROFILE") != "controllogix" or base["AB_SERVER_ENDPOINT"] != base["AB_SERVER_CONTROLLOGIX_ENDPOINT"]:
raise FinalGateError("baseline AB endpoint must be the owned ControlLogix companion")
ab_ports = {control_port}
for name, document in documents.items():
environment = child_environment({**document, "HOST_PROBE_OPCUA_ENDPOINT": base["HOST_PROBE_OPCUA_ENDPOINT"]}, inherited=base)
kind, profile = name.split("-", 1)
endpoint, profile_key = ("MODBUS_SIM_ENDPOINT", "MODBUS_SIM_PROFILE") if kind == "modbus" else ("AB_SERVER_ENDPOINT", "AB_SERVER_COMPOSE_PROFILE")
if environment.get(profile_key) != profile:
raise FinalGateError("fixture environment does not select profile " + name)
allowed = {endpoint, profile_key}
if kind == "ab":
port = ab_loopback_port(environment[endpoint])
if port in ab_ports:
raise FinalGateError("AB profile endpoints and ControlLogix companion must be distinct")
ab_ports.add(port)
if {key for key in document if document[key] != base.get(key)} - allowed:
raise FinalGateError("profile environment modifies unrelated fixture settings")
result[name] = environment
return result
def require_ready_candidate(local):
"""Reject stale or unavailable P10 processes before starting final fixtures."""
import rig
try:
manifest = local.load()
if manifest.get("state") != "ready": raise FinalGateError("P10 rig is not ready")
local.verify_candidate()
return manifest
except rig.RigError:
raise FinalGateError("P10 rig candidate is stale or unavailable; inspect restricted rig diagnostics") from None
def result_artifact_hashes(directory, projects):
files = [directory / name for name in ("inventory.json", "discovery.json", "execution.json",
"software-optins.json", "source-identity.json", "script-worker.json", "test.command.json",
"saturation-observer.json", "saturation-observer-build.command.json")]
supplements = [directory / "profiles" / name for name in PROFILE_PROJECTS] + [directory / AB_DIFFERENTIAL_RUN, directory / SDK_LIFECYCLE_RUN]
diagnostic = directory / "measurements" / "sdk-diagnostic.jsonl"
if diagnostic.is_file():
files.append(diagnostic)
files.extend(supplement / name for supplement in supplements for name in ("discovery.json", "test.command.json"))
discovery_directories = [directory / "discovery" / project["assembly"] for project in projects] + supplements
files.extend(discovery / name for discovery in discovery_directories
for name in ("discovery.command.json", "discovery.stdout.log", "discovery.stderr.log"))
files.extend(directory.rglob("*.trx"))
return {str(path.relative_to(directory)): hashlib.sha256(path.read_bytes()).hexdigest() for path in sorted(files)}
def final_report(directory, unavailable_path=None):
projects = json.loads((directory / "inventory.json").read_text())
discovery = json.loads((directory / "discovery.json").read_text())
profile_discovery = {name: json.loads((directory / "profiles" / name / "discovery.json").read_text()) for name in PROFILE_PROJECTS}
commands = json.loads((directory / "execution.json").read_text())
baseline = read_results(directory / "trx", projects)
overlays = {name: read_results(directory / "profiles" / name / "trx", [p for p in projects if p["assembly"] == assembly], minimum=1)
for name, assembly in PROFILE_PROJECTS.items()}
differential_dir = directory / AB_DIFFERENTIAL_RUN
differential_discovery = json.loads((differential_dir / "discovery.json").read_text())
differential = read_results(differential_dir / "trx", [p for p in projects if p["assembly"] == AB_CIP_ASSEMBLY], minimum=1)
frozen_identity = json.loads((directory / "source-identity.json").read_text())
lifecycle_dir = directory / SDK_LIFECYCLE_RUN
lifecycle_discovery = json.loads((lifecycle_dir / "discovery.json").read_text())
lifecycle = read_results(lifecycle_dir / "trx", [p for p in projects if p["assembly"] == SDK_LIFECYCLE_ASSEMBLY], minimum=1)
lifecycle_receipt = sdk_lifecycle_receipt(lifecycle, lifecycle_discovery,
directory / "measurements" / "sdk-diagnostic.jsonl", frozen_identity["revision"])
report = reconcile(baseline, overlays, discovery, profile_discovery, unavailable_records(unavailable_path),
differential=differential, differential_discovery=differential_discovery, sdk_lifecycle_verified=lifecycle_receipt is not None)
report["sdk_lifecycle_diagnostic"] = lifecycle_receipt
report["sdk_lifecycle_baseline_scope"] = sum(row["disposition"] == "executed-in-isolated-diagnostic"
for row in report["skip_decisions"]) == 1
report["baseline_assemblies"] = baseline["assemblies"]
report["profile_assemblies"] = {name: result["assemblies"] for name, result in overlays.items()}
report["discovered_by_assembly"] = {item["assembly"]: len(item["tests"]) for item in discovery}
report["profile_discovered_by_assembly"] = {name: {item["assembly"]: len(item["tests"]) for item in discovered}
for name, discovered in profile_discovery.items()}
report["software_differential"] = {"executed": differential["executed"], "rows": differential["rows"],
"target": "owned loopback ab_server ControlLogix", "latency_mode": "diagnostic",
"mixed_packet_tags": AB_DIFFERENTIAL_MIX_TAGS.split(";")}
report["command_exit_codes"] = commands
report["command_evidence_complete"] = set(commands) == {"baseline", "baseline12000", AB_DIFFERENTIAL_RUN, SDK_LIFECYCLE_RUN, *PROFILE_PROJECTS}
report["source_identity_matches"] = execution_inputs_match(frozen_identity, source_identity())
frozen = json.loads((directory / "result-artifacts.json").read_text())
report["result_artifacts_match"] = frozen == result_artifact_hashes(directory, projects)
optins = json.loads((directory / "software-optins.json").read_text())
report["software_output_missing"] = [key for key, path in optins.items() if key.endswith(("_OUTPUT", "_OUT")) and (not Path(path).is_file() or not Path(path).stat().st_size)]
report["script_worker_identity_matches"] = script_worker_identity_matches(directory)
report["saturation_observer_identity_matches"] = saturation_observer_identity_matches(directory, frozen_identity, optins)
report["saturation_observer_protocol_controls"] = saturation_observer_protocol_rows(baseline["rows"])
report["limitations"] = ["SDK diagnostic90s and the two short observer protocol controls do not establish full7200s, saturation or qualified late-slope acceptance.",
"The software differential measures simulator parity and diagnostic latency; a physical controller gate is separate.",
"Controller symbol instance ordering across listing pages remains a physical controller evidence requirement.",
"Unavailable rows are unexecuted coverage requiring their recorded next gate; this is not an all-tests-passed claim.",
"Whole-solution gate does not replace P10 scenarios, P11 workloads or independent final Astra review."]
report["passed"] = (report["passed"] and report["command_evidence_complete"] and not any(commands.values())
and report["source_identity_matches"] and report["result_artifacts_match"] and not report["software_output_missing"]
and report["script_worker_identity_matches"] and report["saturation_observer_identity_matches"]
and report["saturation_observer_protocol_controls"]["passed"] and report["sdk_lifecycle_baseline_scope"])
return report
def cleanup_preserving_failure(action, primary_failed):
"""Attempt teardown once; an existing test/setup failure retains precedence."""
try:
action()
except Exception:
if not primary_failed: raise FinalGateError("owned fixture cleanup failed; inspect restricted evidence") from None
return False
return True
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--run-id", required=True)
parser.add_argument("--inventory-only", action="store_true")
parser.add_argument("--unavailable-evidence", type=Path, help="JSON list of exact assembly/test/reason/kind/requires/evidence/next_gate records")
parser.add_argument("--reconcile-only", action="store_true", help="read frozen discovery/TRXs with explicit unavailable evidence; never rebuild or rerun")
args = parser.parse_args(argv)
import rig
if not rig._RUN_PATTERN.fullmatch(args.run_id): raise FinalGateError("invalid run identity")
directory = ROOT / "artifacts" / "grpc-data" / args.run_id / "final"
os.umask(0o077)
if args.reconcile_only:
if args.inventory_only: raise FinalGateError("inventory-only cannot reconcile an existing run")
report = final_report(directory, args.unavailable_evidence)
report["cleanup_succeeded"] = json.loads((directory / "cleanup.json").read_text())["succeeded"]
report["passed"] = report["passed"] and report["cleanup_succeeded"]
path = directory / ("reconciliation-" + str(time.time_ns()) + ".json")
private_json(path, report)
print(json.dumps({"baseline_executed": report["baseline_executed"], "passed": report["passed"], "evidence": str(path)}))
return 0 if report["passed"] else 1
directory.mkdir(parents=True, exist_ok=False, mode=0o700)
projects = inventory(); private_json(directory / "inventory.json", projects)
import fixture_inventory
private_json(directory / "fixture-source-inventory.json", fixture_inventory.generate())
if args.inventory_only: print(str(directory / "inventory.json")); return 0
solution = ET.parse(ROOT / "ZB.MOM.WW.OtOpcUa.slnx").getroot()
included = {item.get("Path", "").replace("\\", "/") for item in solution.iter("Project")}
if any(p["project"] not in included for p in projects): raise FinalGateError("test project absent from final solution")
if not ODBC_DRIVER.is_file(): raise FinalGateError("required local PostgreSQL ODBC driver is missing")
if platform.system() == "Darwin" and not ODBC_DRIVER_MANAGER.is_file():
raise FinalGateError("required local macOS unixODBC manager is missing")
# Validate any supplied decisions before starting expensive prerequisites.
unavailable_records(args.unavailable_evidence)
identity = source_identity(); private_json(directory / "source-identity.json", identity)
local = rig.LocalRig(args.run_id); manifest = require_ready_candidate(local)
env_path = directory / "fixture-environment.json"
setup = {k: v for k, v in os.environ.items() if k in phase.ENV_ALLOWLIST}
setup.update({"CI_FIXTURE_LOCAL_OWNED": "1", "CI_FIXTURE_SUFFIX": args.run_id + "-final", "CI_FIXTURE_ENV_JSON": str(env_path),
"CI_FIXTURE_ODBC_DRIVER": str(ODBC_DRIVER), "FIXTURE_HOST": "127.0.0.1", "DOCKER_CONTEXT": local.context["Name"]})
fixture = ["bash", "scripts/ci/integration-fixtures.sh"]
started = time.monotonic(); report = None; primary_failed = True
try:
if logged_run("fixtures-up", fixture + ["up"], directory, setup, timeout=7200): raise FinalGateError("local prerequisite setup failed")
fixture_environment = json.loads(env_path.read_text())
fixture_environment["HOST_PROBE_OPCUA_ENDPOINT"] = manifest["endpoints"]["control-1.opcua"]["url"]
environment = child_environment(fixture_environment)
profiles = profile_environments(Path(str(env_path) + ".d") / "profile-environments.json", environment)
software_differential = differential_environment(environment)
optins = software_optins(directory / "measurements", identity["revision"])
environment.update({key: value for key, value in optins.items() if key != "OTOPCUA_SDK2_SOAK"})
build, test = solution_commands(directory / "trx")
restore = ["dotnet", "restore", "ZB.MOM.WW.OtOpcUa.slnx", "--disable-parallel", "-m:1"]
if logged_run("restore", restore, directory, environment): raise FinalGateError("final solution restore failed")
if logged_run("build", build, directory, environment): raise FinalGateError("final solution build failed")
worker = prepare_script_worker(directory, environment=environment, identity=identity)
environment.update(worker)
optins.update(worker)
observer = prepare_saturation_observer(directory, environment=environment, identity=identity)
environment.update(observer)
private_json(directory / "software-optins.json", {**optins, **observer})
discovery = [discover_project(project, directory / "discovery" / project["assembly"], environment) for project in projects]
private_json(directory / "discovery.json", discovery)
if not execution_inputs_match(identity, source_identity()): raise FinalGateError("candidate execution inputs changed before the final test command")
commands = {"baseline": logged_run("test", test, directory, environment)}
baseline_trxs = sorted(str(path) for path in (directory / "trx").rglob("*.trx"))
if not baseline_trxs: raise FinalGateError("final solution produced no TRX")
commands["baseline12000"] = logged_run("baseline12000", ["bash", "scripts/ci/assert-not-all-skipped.sh", *baseline_trxs], directory, {**environment, "MIN_EXECUTED": "12000"}, timeout=600)
for name, assembly in PROFILE_PROJECTS.items():
project = next(p for p in projects if p["assembly"] == assembly)
commands[name] = run_profile(project, test, directory / "profiles" / name, {**profiles[name], **optins})
lifecycle_project = next(p for p in projects if p["assembly"] == SDK_LIFECYCLE_ASSEMBLY)
commands[SDK_LIFECYCLE_RUN] = run_profile(lifecycle_project, test, directory / SDK_LIFECYCLE_RUN,
{**environment, "OTOPCUA_SDK2_SOAK": optins["OTOPCUA_SDK2_SOAK"]}, selected={SDK_LIFECYCLE_CASE})
ab_cip_project = next(p for p in projects if p["assembly"] == AB_CIP_ASSEMBLY)
commands[AB_DIFFERENTIAL_RUN] = run_profile(ab_cip_project, test, directory / AB_DIFFERENTIAL_RUN,
software_differential, selected=AB_DIFFERENTIAL_CASES)
private_json(directory / "execution.json", commands)
private_json(directory / "result-artifacts.json", result_artifact_hashes(directory, projects))
report = final_report(directory, args.unavailable_evidence)
report["duration_seconds"] = time.monotonic() - started
primary_failed = not report["passed"]
finally:
def down():
if logged_run("fixtures-down", fixture + ["down"], directory, setup, timeout=900):
raise FinalGateError("owned fixture teardown returned failure")
cleanup = False
try:
cleanup = cleanup_preserving_failure(down, primary_failed)
finally:
private_json(directory / "cleanup.json", {"succeeded": cleanup})
if report is not None:
report["cleanup_succeeded"] = cleanup
report["passed"] = report["passed"] and cleanup
private_json(directory / "results.json", report)
print(json.dumps({"baseline_executed": report["baseline_executed"], "passed": report["passed"], "evidence": str(directory)}))
return 0 if report["passed"] else 1
if __name__ == "__main__":
try: raise SystemExit(main())
except (FinalGateError, OSError, ValueError, KeyError, StopIteration, ET.ParseError, subprocess.SubprocessError) as error:
print("final gate failed: " + (str(error) if isinstance(error, FinalGateError) else "inspect restricted evidence"), file=sys.stderr)
raise SystemExit(2)
+17 -2
View File
@@ -62,7 +62,8 @@ def discover_names(output):
if marker not in output:
return []
names = []
for line in output.split(marker, 1)[1].splitlines():
# VSTest separates records by LF and can print Unicode controls in arguments.
for line in output.split(marker, 1)[1].split("\n"):
value = line.strip()
if line[:1].isspace() and re.match(r"^[\w.+`]+\.[\w`]+(?:\(.*\))?$", value):
names.append(value)
@@ -126,6 +127,14 @@ def validate_trx(directory, started_ns, expected_classes=(), excluded_methods=()
return {"executed": total_executed, "files": summaries, "executed_classes": sorted(executed_classes)}
# These network-free guards live beside their integration fixture implementation.
# No other integration classes or project-wide selector can enter a unit phase.
INTEGRATION_UNIT_GUARDS = {
"tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests.csproj": {"LocalFixtureEndpointGuardTests"},
"tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.IntegrationTests/ZB.MOM.WW.OtOpcUa.Driver.Sql.IntegrationTests.csproj": {"OwnedBlackholeControlGuardTests"},
"tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.IntegrationTests/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.IntegrationTests.csproj": {"AbLegacyFixtureEndpointGuardTests"},
}
def selected_records(manifest, phase, root, case):
if phase not in manifest or not manifest[phase]:
raise GateError(f"unknown or empty phase: {phase}")
@@ -133,11 +142,17 @@ def selected_records(manifest, phase, root, case):
for source in manifest[phase]:
item = dict(source)
project = Path(item["project"])
if project.is_absolute() or ".." in project.parts or project.suffix != ".csproj" or "IntegrationTests" in str(project):
declared = item.get("new_classes", []) + item.get("existing_classes", [])
permitted_guards = INTEGRATION_UNIT_GUARDS.get(project.as_posix(), set())
integration_guards = bool(declared) and set(declared).issubset(permitted_guards) and item.get("integration_unit_guards") is True
if project.is_absolute() or ".." in project.parts or project.suffix != ".csproj" or ("IntegrationTests" in str(project) and not integration_guards):
raise GateError(f"unit project must be an exact repository-relative unit csproj: {project}")
if not (root / project).is_file():
raise GateError(f"missing unit project: {project}")
classes = item.get("new_classes", []) + item.get("existing_classes", [])
if integration_guards:
exact_classes = "|".join("FullyQualifiedName~." + name + "." for name in sorted(set(declared)))
item["filter"] = "Category=Unit&(" + exact_classes + ")"
if case and case not in classes:
continue
if case:
@@ -30,6 +30,18 @@ class UnitPhaseRunnerTests(unittest.TestCase):
self.result_mode = "fresh"
self.result_classes = None
def test_only_declared_network_free_integration_guards_can_run_as_units(self):
project, guards = next(iter(runner.INTEGRATION_UNIT_GUARDS.items()))
path = self.root / project; path.parent.mkdir(parents=True); path.touch()
guard = next(iter(guards))
record = {"project": project, "filter": "Category=Integration", "new_classes": [guard], "existing_classes": []}
with self.assertRaises(runner.GateError): runner.selected_records({"P12": [record]}, "P12", self.root, None)
record["integration_unit_guards"] = True
selected = runner.selected_records({"P12": [record]}, "P12", self.root, None)[0]
self.assertEqual(selected["filter"], "Category=Unit&(FullyQualifiedName~." + guard + ".)")
record["existing_classes"] = ["LiveNetworkTests"]
with self.assertRaises(runner.GateError): runner.selected_records({"P12": [record]}, "P12", self.root, None)
def fake(self, argv, **kwargs):
self.calls.append((argv, kwargs))
if argv[0] == "git":
@@ -86,6 +98,12 @@ class UnitPhaseRunnerTests(unittest.TestCase):
with self.assertRaisesRegex(runner.GateError, "zero"):
self.run_gate()
def test_discovery_preserves_unicode_control_in_theory_arguments(self):
case = 'Example.OracleDialectTests.QuoteIdentifier(ident: "x\u0085y")'
following = "Example.OracleDialectTests.Ordinary"
listing = f"The following Tests are available:\r\n {case}\r\n {following}\r\n"
self.assertEqual([following, case], runner.discover_names(listing))
def test_missing_new_class_cannot_be_masked_by_existing_class(self):
self.listing = "The following Tests are available:\n Example.OldTests.Works\n"
with self.assertRaisesRegex(runner.GateError, "NewTests"):
@@ -0,0 +1,812 @@
import importlib.util
import json
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import Mock, patch
HERE = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(HERE))
spec = importlib.util.spec_from_file_location('final_runner', HERE / 'run-final.py')
runner = importlib.util.module_from_spec(spec)
spec.loader.exec_module(runner)
class FinalRunnerTests(unittest.TestCase):
def worker_identity(self):
return {"revision": "fixture-revision", "execution_input_sha256": "a" * 64}
def fake_worker_publish(self, *, rid="osx-arm64", missing_apphost=False, framework_dependent=False, executable=True):
def publish(name, command, directory, environment, **kwargs):
output = Path(command[command.index("--output") + 1])
output.mkdir(parents=True, exist_ok=True)
apphost = output / ("ZB.MOM.WW.OtOpcUa.ScriptWorker.exe" if rid.startswith("win-") else "ZB.MOM.WW.OtOpcUa.ScriptWorker")
if not missing_apphost:
apphost.write_bytes(b"owned-apphost")
apphost.chmod(0o755 if executable else 0o644)
(output / "ZB.MOM.WW.OtOpcUa.ScriptWorker.dll").write_bytes(b"owned-worker-assembly")
(output / "ZB.MOM.WW.OtOpcUa.ScriptWorker.runtimeconfig.json").write_text(json.dumps({"runtimeOptions":
{"framework" if framework_dependent else "includedFrameworks": [{"name": "Microsoft.NETCore.App", "version": "10.0.0"}]}}))
(output / "ZB.MOM.WW.OtOpcUa.ScriptWorker.deps.json").write_text(json.dumps({
"runtimeTarget": {"name": ".NETCoreApp,Version=v10.0/" + rid},
"libraries": {"ZB.MOM.WW.OtOpcUa.ScriptWorker/1.0.0": {"type": "project"}}}))
return 0
return publish
def test_worker_native_rid_is_bounded_and_rejects_unsupported_platforms(self):
for system, architecture, expected in (("Darwin", "arm64", "osx-arm64"), ("Darwin", "x86_64", "osx-x64"),
("Linux", "aarch64", "linux-arm64"), ("Linux", "x86_64", "linux-x64"),
("Windows", "AMD64", "win-x64"), ("Windows", "ARM64", "win-arm64")):
with self.subTest(system=system, architecture=architecture):
self.assertEqual(runner.native_worker_rid(system, architecture), expected)
for system, architecture in (("Darwin", "unknown"), ("FreeBSD", "x86_64"), ("Linux", "i386")):
with self.subTest(system=system, architecture=architecture), self.assertRaises(runner.FinalGateError):
runner.native_worker_rid(system, architecture)
def test_worker_publish_uses_clean_argv_owned_output_and_verified_identity(self):
with tempfile.TemporaryDirectory(prefix="owned final ") as folder:
directory = Path(folder)
inherited = {"PATH": "/unit/bin", "SQL_TEST_PASSWORD": "must-not-inherit",
"OTOPCUA_SCRIPTWORKER_TEST_PATH": "/foreign/worker", "HTTP_PROXY": "http://foreign"}
with patch.object(runner, "native_worker_rid", return_value="osx-arm64"), \
patch.object(runner, "logged_run", side_effect=self.fake_worker_publish()) as publish:
optins = runner.prepare_script_worker(directory, environment=inherited, identity=self.worker_identity())
name, command, recorded_directory, environment = publish.call_args.args
self.assertEqual(name, "script-worker-publish")
self.assertEqual(command[:2], ["dotnet", "publish"])
self.assertEqual(command[command.index("--runtime") + 1], "osx-arm64")
self.assertEqual(command[command.index("--self-contained") + 1], "true")
self.assertEqual(environment, {"PATH": "/unit/bin"})
apphost = Path(optins["OTOPCUA_SCRIPTWORKER_TEST_PATH"])
self.assertTrue(apphost.is_file())
self.assertTrue(apphost.is_relative_to(directory))
self.assertEqual(recorded_directory, directory)
self.assertTrue(runner.script_worker_identity_matches(directory))
receipt = json.loads((directory / "script-worker.json").read_text())
self.assertEqual(receipt["runtime_identifier"], "osx-arm64")
self.assertEqual(receipt["execution_input_sha256"], self.worker_identity()["execution_input_sha256"])
apphost.write_bytes(b"mutated-worker")
self.assertFalse(runner.script_worker_identity_matches(directory))
def test_worker_publish_rejects_missing_nonexecutable_framework_dependent_or_wrong_rid(self):
for settings in ({"missing_apphost": True}, {"framework_dependent": True}, {"executable": False}, {"rid": "linux-x64"}):
with self.subTest(settings=settings), tempfile.TemporaryDirectory() as folder:
with patch.object(runner, "native_worker_rid", return_value="osx-arm64"), \
patch.object(runner, "logged_run", side_effect=self.fake_worker_publish(**settings)), \
self.assertRaises(runner.FinalGateError):
runner.prepare_script_worker(Path(folder), environment={}, identity=self.worker_identity())
def test_worker_publish_failure_or_reused_output_cannot_supply_a_path(self):
with tempfile.TemporaryDirectory() as folder:
with patch.object(runner, "native_worker_rid", return_value="osx-arm64"), \
patch.object(runner, "logged_run", return_value=1), self.assertRaises(runner.FinalGateError):
runner.prepare_script_worker(Path(folder), environment={}, identity=self.worker_identity())
with patch.object(runner, "logged_run") as publish, self.assertRaises((runner.FinalGateError, FileExistsError)):
runner.prepare_script_worker(Path(folder), environment={}, identity=self.worker_identity())
publish.assert_not_called()
def trace_libraries(self, home, *, version=runner.DOTNET_TRACE_VERSION):
with patch.object(runner.Path, 'home', return_value=home):
libraries = runner.saturation_observer_libraries()
libraries.mkdir(parents=True)
(libraries / 'dotnet-trace.deps.json').write_text(json.dumps({'libraries': {'dotnet-trace/' + version: {'type': 'project'}}}))
for name in runner.TRACE_LIBRARIES:
(libraries / name).write_text(name + ' installed library fixture')
return libraries
def fake_observer_build(self, *, omit=None, portable=True, change_input=False):
def build(name, command, directory, environment, **kwargs):
output = Path(command[command.index('--output') + 1])
libraries = Path(command[command.index('--libraries') + 1])
if output.exists():
self.fail('observer builder must receive a fresh directory')
runtime = output / 'bin/Release/net10.0'
runtime.mkdir(parents=True)
(runtime / 'observer.dll').write_bytes(b'portable observer fixture')
frameworks = [{'name': name, 'version': '10.0.0'} for name in ('Microsoft.NETCore.App', 'Microsoft.AspNetCore.App')]
(runtime / 'observer.runtimeconfig.json').write_text(json.dumps({'runtimeOptions': {'tfm': 'net10.0',
'frameworks' if portable else 'includedFrameworks': frameworks}}))
(runtime / 'observer.deps.json').write_text(json.dumps({'runtimeTarget': {'name': '.NETCoreApp,Version=v10.0'},
'libraries': {'observer/1.0.0': {'type': 'project'}}}))
for library in runner.TRACE_LIBRARIES:
if library != omit:
(runtime / library).write_bytes((libraries / library).read_bytes())
if change_input:
(libraries / runner.TRACE_LIBRARIES[0]).write_bytes(b'changed during build')
return 0
return build
def test_observer_uses_exact_installed_trace_store_and_fresh_portable_owned_output(self):
with tempfile.TemporaryDirectory(prefix='owned observer ') as folder:
directory = Path(folder)
home = directory / 'home'
libraries = self.trace_libraries(home)
self.assertEqual(libraries.relative_to(home).as_posix(),
'.dotnet/tools/.store/dotnet-trace/9.0.661903/dotnet-trace/9.0.661903/tools/net8.0/any')
environment = {'PATH': '/unit/dotnet', 'SQL_TEST_PASSWORD': 'must-not-inherit',
'OTOPCUA_SDK2_SATURATION_CONTROL': '/unowned', 'OTOPCUA_SDK2_SOAK_MODE': 'saturation',
runner.SATURATION_OBSERVER_ENV: '/unowned/observer'}
identity = self.worker_identity()
with patch.object(runner.Path, 'home', return_value=home), \
patch.object(runner, 'logged_run', side_effect=self.fake_observer_build()) as build:
optins = runner.prepare_saturation_observer(directory, environment=environment, identity=identity)
name, command, owner, child_environment = build.call_args.args
self.assertEqual(name, 'saturation-observer-build')
self.assertEqual(command[:2], [sys.executable, str(runner.SATURATION_OBSERVER_BUILDER)])
self.assertEqual(command[2:], ['--output', str(directory / 'saturation-observer/build'), '--libraries', str(libraries)])
self.assertEqual(owner, directory)
self.assertEqual(child_environment, {'PATH': '/unit/dotnet'})
entry = directory / 'saturation-observer/build/bin/Release/net10.0/observer.dll'
self.assertEqual(optins, {runner.SATURATION_OBSERVER_ENV: str(entry)})
self.assertEqual((directory / 'saturation-observer').stat().st_mode & 0o777, 0o700)
receipt_path = directory / 'saturation-observer.json'
self.assertEqual(receipt_path.stat().st_mode & 0o777, 0o600)
receipt = json.loads(receipt_path.read_text())
self.assertEqual(receipt['execution_input_sha256'], identity['execution_input_sha256'])
self.assertEqual(set(receipt['inputs']), {'build_saturation_observer.py', 'SaturationObserver.cs',
'dotnet-trace.deps.json', *runner.TRACE_LIBRARIES})
self.assertTrue(runner.saturation_observer_identity_matches(directory, identity, optins))
self.assertFalse(runner.saturation_observer_identity_matches(directory, {**identity, 'revision': 'foreign'}, optins))
self.assertFalse(runner.saturation_observer_identity_matches(directory, identity, {runner.SATURATION_OBSERVER_ENV: '/unowned'}))
entry.write_bytes(b'changed observer after build')
self.assertFalse(runner.saturation_observer_identity_matches(directory, identity, optins))
def test_observer_rejects_missing_wrong_or_changed_inputs_and_nonportable_output(self):
for settings in ({'omit': runner.TRACE_LIBRARIES[0]}, {'portable': False}, {'change_input': True}):
with self.subTest(settings=settings), tempfile.TemporaryDirectory() as folder:
directory = Path(folder)
self.trace_libraries(directory)
with patch.object(runner.Path, 'home', return_value=directory), \
patch.object(runner, 'logged_run', side_effect=self.fake_observer_build(**settings)), \
self.assertRaises(runner.FinalGateError):
runner.prepare_saturation_observer(directory, environment={}, identity=self.worker_identity())
self.assertFalse((directory / 'saturation-observer.json').exists())
with tempfile.TemporaryDirectory() as folder:
directory = Path(folder)
libraries = self.trace_libraries(directory, version='foreign')
with patch.object(runner.Path, 'home', return_value=directory), patch.object(runner, 'logged_run') as build:
with self.assertRaisesRegex(runner.FinalGateError, 'wrong version'):
runner.prepare_saturation_observer(directory, environment={}, identity=self.worker_identity())
(libraries / runner.TRACE_LIBRARIES[0]).unlink()
with self.assertRaisesRegex(runner.FinalGateError, 'requires installed dotnet-trace'):
runner.prepare_saturation_observer(directory, environment={}, identity=self.worker_identity())
build.assert_not_called()
def test_observer_rejects_failed_build_or_reused_directory(self):
with tempfile.TemporaryDirectory() as folder:
directory = Path(folder)
self.trace_libraries(directory)
with patch.object(runner.Path, 'home', return_value=directory), patch.object(runner, 'logged_run', return_value=1):
with self.assertRaisesRegex(runner.FinalGateError, 'build failed'):
runner.prepare_saturation_observer(directory, environment={}, identity=self.worker_identity())
self.assertFalse((directory / 'saturation-observer.json').exists())
with patch.object(runner.Path, 'home', return_value=directory), patch.object(runner, 'logged_run') as build:
with self.assertRaises(FileExistsError):
runner.prepare_saturation_observer(directory, environment={}, identity=self.worker_identity())
build.assert_not_called()
def test_public_nat_certificate_fixture_drift_is_gated(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder)
certificate = 'tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests/Docker/nat/opc-plc-nat-server.der'
private_key = 'tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests/Docker/nat/private.key'
for name, value in (('src/Feature.cs', b'code'), (certificate, b'public certificate fixture'),
(private_key, b'private test key placeholder')):
path = root / name; path.parent.mkdir(parents=True, exist_ok=True); path.write_bytes(value)
names = ['src/Feature.cs', certificate, private_key]
before = runner.execution_input_inventory(root, names)
self.assertIn(certificate, before)
self.assertNotIn(private_key, before)
(root / certificate).write_bytes(b'changed public certificate fixture')
self.assertNotEqual(before, runner.execution_input_inventory(root, names))
def test_execution_inputs_ignore_prose_and_evidence_but_detect_all_executable_inputs(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder)
contents = {
'src/Feature.cs': b'code', 'src/Secrets/Provider.cs': b'code in a sensitive-named namespace',
'tests/FeatureTests.cs': b'test',
'tests/Golden/frame.bin': b'fixture', 'scripts/validation/grpc-data/runner.py': b'script',
'tests/Artifacts/Fixture.cs': b'fixture source',
'scripts/validation/grpc-data/evidence/validator.py': b'validator source',
'Directory.Build.props': b'<Project />', '.config/dotnet-tools.json': b'{"tools":{}}',
'docs/ReadWriteOperations.md': b'prose',
'scripts/validation/grpc-data/p11-adversarial-evidence.json': b'{}',
'scripts/validation/grpc-data/evidence/report.json': b'{}',
'scripts/validation/grpc-data/secrets/fixture-environment.json': b'private',
}
for name, value in contents.items():
path = root / name; path.parent.mkdir(parents=True, exist_ok=True); path.write_bytes(value)
names = list(contents)
original = runner.execution_input_inventory(root, names)
self.assertEqual(set(original), {'src/Feature.cs', 'src/Secrets/Provider.cs', 'tests/FeatureTests.cs', 'tests/Golden/frame.bin',
'tests/Artifacts/Fixture.cs', 'scripts/validation/grpc-data/evidence/validator.py',
'scripts/validation/grpc-data/runner.py', 'scripts/validation/grpc-data/p11-adversarial-evidence.json',
'Directory.Build.props', '.config/dotnet-tools.json'})
for name in ('docs/ReadWriteOperations.md', 'scripts/validation/grpc-data/evidence/report.json',
'scripts/validation/grpc-data/secrets/fixture-environment.json'):
(root / name).write_bytes(b'changed prose or private data')
self.assertEqual(original, runner.execution_input_inventory(root, names))
for name in ('src/Feature.cs', 'src/Secrets/Provider.cs', 'tests/FeatureTests.cs', 'tests/Golden/frame.bin',
'tests/Artifacts/Fixture.cs', 'scripts/validation/grpc-data/evidence/validator.py',
'scripts/validation/grpc-data/runner.py', 'scripts/validation/grpc-data/p11-adversarial-evidence.json',
'Directory.Build.props', '.config/dotnet-tools.json'):
path = root / name; path.write_bytes(b'changed execution input')
self.assertNotEqual(original, runner.execution_input_inventory(root, names), name)
path.write_bytes(contents[name])
executable = root / 'scripts/validation/grpc-data/runner.py'
executable.chmod(0o755)
self.assertNotEqual(original, runner.execution_input_inventory(root, names))
def test_identical_tree_commit_changes_provenance_not_execution_gate(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder); (root / 'src').mkdir(); (root / 'src/Feature.cs').write_text('same bytes')
state = {'revision': b'old\n', 'diff': b'old patch', 'untracked': b'src/Feature.cs\0'}
def fake_git(command, *, cwd):
self.assertEqual(cwd, root)
if command[1:3] == ['ls-files', '--cached']: return b'src/Feature.cs\0'
if command[1:3] == ['ls-files', '--others']: return state['untracked']
if command[1] == 'rev-parse': return state['revision']
if command[1] == 'diff': return state['diff']
raise AssertionError(command)
with patch.object(runner.subprocess, 'check_output', side_effect=fake_git):
before = runner.source_identity(root)
state.update(revision=b'new\n', diff=b'', untracked=b'')
after = runner.source_identity(root)
self.assertNotEqual(before, after)
self.assertTrue(runner.execution_inputs_match(before, after))
self.assertNotEqual(before['revision'], after['revision'])
self.assertNotEqual(before['untracked_sha256'], after['untracked_sha256'])
(root / 'src/Feature.cs').write_text('changed bytes')
with patch.object(runner.subprocess, 'check_output', side_effect=fake_git):
self.assertFalse(runner.execution_inputs_match(before, runner.source_identity(root)))
def test_committing_an_already_tested_deletion_preserves_input_identity(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder); (root / 'src').mkdir()
live = root / 'src/Live.cs'; live.write_text('live')
deleted = root / 'src/Deleted.cs'; deleted.write_text('old code')
state = {'names': b'src/Live.cs\0src/Deleted.cs\0', 'revision': b'old\n', 'diff': b''}
def fake_git(command, *, cwd):
self.assertEqual(cwd, root)
if command[1:3] == ['ls-files', '--cached']: return state['names']
if command[1:3] == ['ls-files', '--others']: return b''
if command[1] == 'rev-parse': return state['revision']
if command[1] == 'diff': return state['diff']
raise AssertionError(command)
with patch.object(runner.subprocess, 'check_output', side_effect=fake_git):
before_deletion = runner.source_identity(root)
deleted.unlink()
after_deletion = runner.source_identity(root)
self.assertFalse(runner.execution_inputs_match(before_deletion, after_deletion))
state.update(names=b'src/Live.cs\0', revision=b'new\n', diff=b'committed deletion')
after_commit = runner.source_identity(root)
self.assertTrue(runner.execution_inputs_match(after_deletion, after_commit))
self.assertEqual(set(after_deletion['execution_input_files']), {'src/Live.cs'})
def test_execution_input_path_and_symlink_are_rejected_before_reading(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder); (root / 'src').mkdir()
outside = root / 'private.key'; outside.write_text('do not read')
(root / 'src/link.cs').symlink_to(outside)
with self.assertRaisesRegex(runner.FinalGateError, 'symlink'):
runner.execution_input_inventory(root, ['src/link.cs'])
with self.assertRaisesRegex(runner.FinalGateError, 'unsafe candidate input path'):
runner.execution_input_inventory(root, ['src/../private.key'])
with self.assertRaisesRegex(runner.FinalGateError, 'unsafe candidate input path'):
runner.execution_input_inventory(root, [''])
def test_final_preflight_rejects_stale_or_unavailable_ready_rig(self):
import rig
local = Mock()
manifest = {'state': 'ready', 'endpoints': {'control-1.opcua': {'url': 'opc.tcp://127.0.0.1:4840'}}}
local.load.return_value = manifest
self.assertIs(runner.require_ready_candidate(local), manifest)
local.verify_candidate.assert_called_once_with()
local.verify_candidate.reset_mock()
local.load.return_value = {'state': 'seeded'}
with self.assertRaisesRegex(runner.FinalGateError, 'P10 rig is not ready'):
runner.require_ready_candidate(local)
local.verify_candidate.assert_not_called()
local.load.return_value = manifest
local.verify_candidate.side_effect = rig.RigError('private Docker diagnostic')
with self.assertRaisesRegex(runner.FinalGateError, 'stale or unavailable') as stale:
runner.require_ready_candidate(local)
self.assertNotIn('private Docker diagnostic', str(stale.exception))
local.load.side_effect = rig.RigError('private Docker diagnostic')
local.verify_candidate.reset_mock()
with self.assertRaisesRegex(runner.FinalGateError, 'stale or unavailable'):
runner.require_ready_candidate(local)
local.verify_candidate.assert_not_called()
def fixture(self):
result = {key: 'local-value' for key in runner.REQUIRED_FIXTURES}
for key in runner.REQUIRED_FIXTURES:
if key.endswith(("_ENDPOINT", "_HOST")): result[key] = "127.0.0.1:12345"
result["OTOPCUA_LOCAL_FIXTURE_MODE"] = "1"
for key in ('OTOPCUA_HARNESS_USE_SQL', 'OTOPCUA_HARNESS_USE_LDAP', 'S7_SIM_ALLOW_WRITES', 'AB_SERVER_ALLOW_WRITES'):
result[key] = '1'
result.update({
'OTOPCUA_CONFIG_TEST_SERVER': '127.0.0.1,14330', 'SQL_TEST_ENDPOINT': '127.0.0.1,14330',
'SQL_PG_ENDPOINT': '127.0.0.1:15432',
'AB_SERVER_COMPOSE_PROFILE': 'controllogix',
'HISTORIAN_SQL_TEST_CONNECTION': 'Server=127.0.0.1,14330;Password=local;',
'HISTORIAN_QUESTDB_TEST_CONNECTION': 'Host=127.0.0.1;Port=18812;',
'SQL_ODBC_CONNECTION_STRING': 'Driver={/opt/homebrew/opt/psqlodbc/lib/psqlodbcw.so};Server=127.0.0.1;Port=15432;Database=fixture;Uid=fixture;Pwd=local;',
'OPCUA_SIM_ENDPOINT': 'opc.tcp://127.0.0.1:50200',
'OPCUA_NAT_ENDPOINT': 'opc.tcp://127.0.0.1:50210',
'OPCUA_NAT_SERVER_CERT': '/private/run/server.der'})
return result
def test_final_environment_strips_ambient_credentials_and_unit_discovery(self):
env = runner.child_environment(self.fixture(), {'PATH': '/bin', 'AB_DIFFERENTIAL_ENDPOINT': '10.100.0.35',
'OTOPCUA_SCRIPTWORKER_TEST_PATH': '/foreign/worker',
'OTOPCUA_UNIT_ONLY_DISCOVERY': '1', 'SQL_TEST_PASSWORD': 'shared', 'UNRELATED_TOKEN': 'secret',
'DYLD_LIBRARY_PATH': '/foreign/driver'})
self.assertNotIn('OTOPCUA_UNIT_ONLY_DISCOVERY', env)
self.assertNotIn('AB_DIFFERENTIAL_ENDPOINT', env)
self.assertNotIn('UNRELATED_TOKEN', env)
self.assertNotIn('OTOPCUA_SCRIPTWORKER_TEST_PATH', env)
self.assertNotIn('DYLD_LIBRARY_PATH', env)
self.assertEqual(env['SQL_TEST_PASSWORD'], 'local-value')
def test_missing_fixture_and_foreign_host_fail_before_discovery(self):
fixture = self.fixture(); fixture.pop('OPCUA_NAT_SERVER_CERT')
with self.assertRaises(runner.FinalGateError): runner.child_environment(fixture)
for key, value in [('SQL_TEST_ENDPOINT', '10.100.0.35,1433'), ('OPCUA_SIM_ENDPOINT', 'opc.tcp://remote.example:4840'),
('HISTORIAN_SQL_TEST_CONNECTION', 'Server=foreign;Password=x;')]:
fixture = self.fixture(); fixture[key] = value
with self.assertRaises(runner.FinalGateError): runner.child_environment(fixture)
def test_odbc_driver_and_real_mode_cannot_be_implicitly_disabled(self):
for key, value in [('SQL_ODBC_CONNECTION_STRING', 'DSN=shared'), ('OTOPCUA_HARNESS_USE_SQL', '0'), ('OTOPCUA_HARNESS_USE_LDAP', '0')]:
fixture = self.fixture(); fixture[key] = value
with self.assertRaises(runner.FinalGateError): runner.child_environment(fixture)
def test_fixture_cannot_enable_hardware_or_supply_arbitrary_process_options(self):
for key in ('AB_HW_WRITE_APPROVED', 'AB_DIFF_ENDPOINT', 'AB_EVID_IDLE', 'AB_LAT_TAGS', 'AB_DIFFERENTIAL_ENDPOINT', 'LD_PRELOAD', 'DOTNET_STARTUP_HOOKS', runner.SATURATION_OBSERVER_ENV):
fixture = self.fixture(); fixture[key] = '1'
with self.assertRaises(runner.FinalGateError): runner.child_environment(fixture)
def test_full_solution_command_has_no_test_filter_and_is_serial(self):
build, test = runner.solution_commands('/private/results')
self.assertEqual(test[:3], ['dotnet', 'test', 'ZB.MOM.WW.OtOpcUa.slnx'])
self.assertNotIn('--filter', test)
self.assertIn('--no-build', test)
self.assertIn('-m:1', build)
self.assertIn('-m:1', test)
self.assertIn('--no-restore', build)
self.assertIn('--blame-hang', test)
self.assertEqual(test[test.index('--blame-hang-timeout') + 1], '20m')
def trx(self, folder, outcome='Passed', assembly='Example.Tests', cls='Example.GrpcDataExampleTests'):
path = Path(folder) / 'result.trx'
path.write_text(f'''<TestRun><TestDefinitions><UnitTest id="1"><TestMethod codeBase="{assembly}.dll" className="{cls}" name="Case"/></UnitTest></TestDefinitions><Results><UnitTestResult testId="1" outcome="{outcome}"><Output><ErrorInfo><Message>Unavailable platform</Message></ErrorInfo></Output></UnitTestResult></Results></TestRun>''')
return [{'assembly': assembly, 'grpc_classes': ['GrpcDataExampleTests']}]
def test_results_require_each_assembly_nonzero_and_grpc_cases_not_skipped(self):
with tempfile.TemporaryDirectory() as folder:
projects = self.trx(folder)
report = runner.read_results(folder, projects, minimum=1)
self.assertTrue(report['passed'])
self.assertFalse(runner.read_results(folder, projects, minimum=12000)['passed'])
projects.append({'assembly': 'Missing.Tests', 'grpc_classes': []})
self.assertEqual(runner.read_results(folder, projects, minimum=1)['missing_assemblies'], ['Missing.Tests'])
self.trx(folder, outcome='NotExecuted')
report = runner.read_results(folder, projects, minimum=0)
self.assertFalse(report['passed'])
self.assertEqual(report['skipped_grpc'][0]['reason'], 'Unavailable platform')
def test_observer_protocol_controls_require_both_exact_executed_baseline_rows(self):
assembly = runner.SATURATION_OBSERVER_ASSEMBLY
method = runner.SATURATION_OBSERVER_METHOD
rows = [self.report(assembly, name=f'{method}(foreignMarker: {marker})')['rows'][0] for marker in ('False', 'True')]
self.assertEqual(runner.saturation_observer_protocol_rows(rows), {'rows': rows, 'passed': True})
for altered in (rows[:1], rows + rows[:1], [rows[0], {**rows[1], 'outcome': 'NotExecuted'}],
[rows[0], {**rows[1], 'assembly': 'Foreign.Assembly'}], [rows[0], {**rows[1], 'test': method}]):
with self.subTest(altered=altered):
self.assertFalse(runner.saturation_observer_protocol_rows(altered)['passed'])
def test_failed_cases_are_retained_with_evidence(self):
with tempfile.TemporaryDirectory() as folder:
projects = self.trx(folder, outcome='Failed')
report = runner.read_results(folder, projects, minimum=1)
self.assertFalse(report['passed'])
self.assertEqual(report['executed'], 1)
self.assertEqual(report['failures'][0]['test'], 'Example.GrpcDataExampleTests.Case')
def test_inventory_uses_test_sdk_even_without_tests_name_and_records_env(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder); test = root / 'tests' / 'odd'; test.mkdir(parents=True)
(test / 'Odd.csproj').write_text('<Project><PropertyGroup><AssemblyName>Actual.Tests</AssemblyName></PropertyGroup><ItemGroup><PackageReference Include="Microsoft.NET.Test.Sdk"/></ItemGroup></Project>')
(test / 'Cases.cs').write_text('[Trait("Category", "Integration")] class GrpcDataOddTests { var x = Environment.GetEnvironmentVariable("LOCAL_FIXTURE"); }')
inventory = runner.inventory(root)
self.assertEqual(inventory[0]['assembly'], 'Actual.Tests')
self.assertEqual(inventory[0]['grpc_classes'], ['GrpcDataOddTests'])
self.assertEqual(inventory[0]['literal_environment'], ['LOCAL_FIXTURE'])
def test_macos_testhost_uses_explicit_installed_odbc_manager_directory(self):
with patch.object(runner.platform, "system", return_value="Darwin"):
_, test = runner.solution_commands('/private/results')
self.assertEqual(test[test.index('--environment') + 1],
'DYLD_LIBRARY_PATH=/opt/homebrew/opt/unixodbc/lib')
with patch.object(runner.platform, "system", return_value="Linux"):
self.assertEqual(runner.macos_odbc_testhost_args(), [])
def test_sdk_lifecycle_receipt_requires_exact_pass_and_90_seconds(self):
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / 'diagnostic.jsonl'
discovery = [{"assembly": runner.SDK_LIFECYCLE_ASSEMBLY, "tests": [runner.SDK_LIFECYCLE_CASE]}]
row = {"assembly": runner.SDK_LIFECYCLE_ASSEMBLY, "test": runner.SDK_LIFECYCLE_CASE,
"outcome": "Passed", "trx": "diagnostic.trx"}
events = [{"kind": "start", "mode": "diagnostic", "build": "same", "requestedSeconds": 90},
*[{"kind": "quiescent"} for _ in range(3)],
{"kind": "complete", "mode": "diagnostic", "cycles": 3, "seconds": 90.3,
"satisfiesTwoHourDuration": False}]
def write():
path.write_text('\n'.join(json.dumps(event) for event in events) + '\n')
write()
self.assertEqual(runner.sdk_lifecycle_receipt({"rows": [row]}, discovery, path, "same")["cycles"], 3)
self.assertIsNone(runner.sdk_lifecycle_receipt({"rows": [row]}, discovery, path, "different"))
self.assertIsNone(runner.sdk_lifecycle_receipt({"rows": [row, row]}, discovery, path, "same"))
self.assertIsNone(runner.sdk_lifecycle_receipt({"rows": [{**row, "outcome": "Failed"}]}, discovery, path, "same"))
events[-1]["seconds"] = 89.99
write()
self.assertIsNone(runner.sdk_lifecycle_receipt({"rows": [row]}, discovery, path, "same"))
def test_software_optins_are_bounded_explicit_and_fresh(self):
with tempfile.TemporaryDirectory() as folder:
directory = Path(folder) / 'measurements'
env = runner.software_optins(directory, 'abc')
self.assertEqual(env['OTOPCUA_SDK2_SOAK_MODE'], 'diagnostic')
self.assertEqual(env['OTOPCUA_SDK2_SOAK_SECONDS'], '90')
self.assertEqual(env['OTOPCUA_EVENT_PERF'], '1')
self.assertEqual(env['OTOPCUA_SCRIPT_PERF'], '1')
self.assertEqual(env['HISTORIAN_QUESTDB_STRESS_SECONDS'], '60')
for key in ('OTOPCUA_SDK2_SOAK_OUTPUT', 'OTOPCUA_EVENT_PERF_OUT', 'OTOPCUA_SCRIPT_PERF_OUT'):
self.assertTrue(Path(env[key]).is_absolute())
self.assertFalse(Path(env[key]).exists())
with self.assertRaises(FileExistsError): runner.software_optins(directory, 'abc')
def test_profile_documents_require_all_seven_and_reject_unrelated_changes(self):
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / 'profiles.json'
base = runner.child_environment(self.fixture())
documents = {}
for name in runner.PROFILE_PROJECTS:
kind, profile = name.split('-', 1)
key = 'MODBUS_SIM_PROFILE' if kind == 'modbus' else 'AB_SERVER_COMPOSE_PROFILE'
documents[name] = {**self.fixture(), key: profile}
if kind == 'ab':
documents[name]['AB_SERVER_ENDPOINT'] = f'127.0.0.1:{12400 + len(documents)}'
path.write_text(json.dumps(documents))
self.assertEqual(len(runner.profile_environments(path, base)), 7)
micro = documents['ab-micro800']
for wrong in ('remote.example:12400', '127.0.0.1:1', base['AB_SERVER_ENDPOINT']):
documents['ab-micro800'] = {**micro, 'AB_SERVER_ENDPOINT': wrong}
path.write_text(json.dumps(documents))
with self.assertRaises(runner.FinalGateError): runner.profile_environments(path, base)
documents['ab-micro800'] = {**micro, 'AB_SERVER_CONTROLLOGIX_ENDPOINT': '127.0.0.1:12450'}
path.write_text(json.dumps(documents))
with self.assertRaises(runner.FinalGateError): runner.profile_environments(path, base)
documents['ab-micro800'] = micro
dl205 = documents.pop('modbus-dl205')
path.write_text(json.dumps(documents))
with self.assertRaises(runner.FinalGateError): runner.profile_environments(path, base)
documents['modbus-dl205'] = {**dl205, 'SQL_TEST_PASSWORD': 'changed'}
path.write_text(json.dumps(documents))
with self.assertRaises(runner.FinalGateError): runner.profile_environments(path, base)
documents['modbus-dl205'] = {**dl205, 'MODBUS_SIM_PROFILE': 'standard'}
path.write_text(json.dumps(documents))
with self.assertRaisesRegex(runner.FinalGateError, 'does not select profile modbus-dl205'):
runner.profile_environments(path, base)
def test_each_profile_discovers_and_runs_with_the_same_environment_and_frozen_evidence(self):
def run(command, *, env, stdout, **_):
if '--list-tests' in command:
if env.get('OTOPCUA_SDK2_SOAK') == '1':
names = [runner.SDK_LIFECYCLE_CASE]
else:
names = sorted(runner.AB_DIFFERENTIAL_CASES) if '--filter' in command else [f'Example.Cases.Case(profile: "{env["PROFILE"]}")']
stdout.write('The following Tests are available:\n' + ''.join(' ' + name + '\n' for name in names))
return Mock(returncode=0)
with tempfile.TemporaryDirectory() as folder, patch.object(runner.subprocess, 'run', side_effect=run) as process:
directory = Path(folder)
_, baseline_command = runner.solution_commands(directory / 'trx')
for name, assembly in runner.PROFILE_PROJECTS.items():
profile_dir = directory / 'profiles' / name
project = {'project': 'tests/' + assembly + '.csproj', 'assembly': assembly}
environment = {'PROFILE': name, 'PRIVATE_FIXTURE_SECRET': 'never-record'}
self.assertEqual(runner.run_profile(project, baseline_command, profile_dir, environment), 0)
discovery, test = process.call_args_list[-2:]
self.assertIs(discovery.kwargs['env'], environment)
self.assertIs(test.kwargs['env'], environment)
self.assertEqual(discovery.args[0][2], project['project'])
self.assertEqual(test.args[0][2], project['project'])
self.assertNotIn('--filter', discovery.args[0])
self.assertNotIn('--filter', test.args[0])
self.assertEqual(test.args[0][-1], str(profile_dir / 'trx'))
parsed = json.loads((profile_dir / 'discovery.json').read_text())
self.assertEqual(parsed, [{'assembly': assembly, 'tests': [f'Example.Cases.Case(profile: "{name}")']}])
self.assertFalse(any('never-record' in path.read_text() for path in profile_dir.iterdir()))
for name in ('inventory.json', 'discovery.json', 'execution.json', 'software-optins.json', 'source-identity.json',
'script-worker.json', 'test.command.json', 'saturation-observer.json', 'saturation-observer-build.command.json'):
runner.private_json(directory / name, {})
differential_dir = directory / runner.AB_DIFFERENTIAL_RUN
differential_project = {'project': 'tests/AbCip.csproj', 'assembly': runner.AB_CIP_ASSEMBLY}
runner.run_profile(differential_project, baseline_command, differential_dir, {}, selected=runner.AB_DIFFERENTIAL_CASES)
diagnostic_project = {'project': 'tests/OpcUaServer.csproj', 'assembly': runner.SDK_LIFECYCLE_ASSEMBLY}
runner.run_profile(diagnostic_project, baseline_command, directory / runner.SDK_LIFECYCLE_RUN,
{'OTOPCUA_SDK2_SOAK': '1'}, selected={runner.SDK_LIFECYCLE_CASE})
frozen = runner.result_artifact_hashes(directory, [])
for name in runner.PROFILE_PROJECTS:
for filename in ('discovery.json', 'discovery.command.json', 'discovery.stdout.log', 'discovery.stderr.log', 'test.command.json'):
self.assertIn(f'profiles/{name}/{filename}', frozen)
self.assertIn(f'{runner.AB_DIFFERENTIAL_RUN}/discovery.json', frozen)
self.assertIn(f'{runner.SDK_LIFECYCLE_RUN}/discovery.json', frozen)
self.assertIn('saturation-observer.json', frozen)
self.assertIn('saturation-observer-build.command.json', frozen)
(directory / 'profiles/ab-micro800/discovery.json').write_text('[]\n')
self.assertNotEqual(frozen, runner.result_artifact_hashes(directory, []))
def test_differential_uses_only_owned_control_logix_and_exact_read_only_selectors(self):
base = {'PATH': '/unit/dotnet', 'AB_SERVER_ENDPOINT': '127.0.0.1:23456', 'AB_SERVER_COMPOSE_PROFILE': 'controllogix',
'AB_SERVER_CONTROLLOGIX_ENDPOINT': '127.0.0.1:23456',
'AB_SERVER_ALLOW_WRITES': '1', 'AB_DIFF_ENDPOINT': '10.100.0.35:44818', 'AB_LAT_ENFORCE': '1',
'AB_EVID_MIX': '0', 'AB_EVID_TAGS': 'foreign-tag', 'AB_EVID_BROWSE': '1', 'OTHER_PASSWORD': 'unrelated'}
environment = runner.differential_environment(base)
self.assertEqual(environment, {'PATH': base['PATH'], 'OTOPCUA_LOCAL_FIXTURE_MODE': '1', 'AB_SERVER_ENDPOINT': '127.0.0.1:1',
'AB_SERVER_CONTROLLOGIX_ENDPOINT': '127.0.0.1:1',
'AB_DIFF_ENDPOINT': base['AB_SERVER_ENDPOINT'], 'AB_DIFF_COUNT_OPENS': '1',
'AB_DIFF_FAMILY': 'ControlLogix', 'AB_DIFF_PATH': '1,0', 'AB_EVID_MIX': '1',
'AB_EVID_TAGS': 'TestString|String|1;TestArray[1]|DInt|1;TestArray|DInt|16;TestDINT|DInt|1;TestBOOL|Bool|1'})
for override in ({'AB_SERVER_COMPOSE_PROFILE': 'micro800'}, {'AB_SERVER_ENDPOINT': '10.100.0.35:44818'},
{'AB_SERVER_ENDPOINT': '127.0.0.1:1'}, {'AB_SERVER_ENDPOINT': '127.0.0.1:65536'}):
with self.subTest(override=override), self.assertRaises(runner.FinalGateError):
runner.differential_environment({**base, **override})
selected = runner.AB_DIFFERENTIAL_CASES
guard = runner.AB_CIP_ASSEMBLY + '.Differential.TransportDifferentialTests.The_harness_is_read_only_by_construction'
self.assertIn(guard, selected)
self.assertNotIn(guard, runner.AB_DIFFERENTIAL_LIVE_CASES)
self.assertIn(runner.AB_DIFFERENTIAL_MIX_CASE, selected)
self.assertNotIn(runner.AB_CIP_ASSEMBLY + '.Differential.EvidenceTests.Symbol_listing_pages_are_ascending_on_a_real_controller', selected)
self.assertEqual(len(selected), 13)
def run(command, *, stdout, **_):
if '--list-tests' in command:
stdout.write('The following Tests are available:\n' + ''.join(' ' + name + '\n' for name in sorted(discovered)))
return Mock(returncode=0)
project = {'project': 'tests/AbCip.csproj', 'assembly': runner.AB_CIP_ASSEMBLY}
with tempfile.TemporaryDirectory() as folder, patch.object(runner.subprocess, 'run', side_effect=run) as process:
directory = Path(folder)
_, test = runner.solution_commands(directory / 'trx')
discovered = selected
runner.run_profile(project, test, directory / 'valid', environment, selected=selected)
for invocation in process.call_args_list:
command = invocation.args[0]
self.assertEqual(set(command[command.index('--filter') + 1].split('|')),
{'FullyQualifiedName=' + name for name in selected})
self.assertIs(invocation.kwargs['env'], environment)
self.assertNotIn('--filter', test)
discovered = selected | {runner.AB_CIP_ASSEMBLY + '.Unexpected.Writes'}
process.reset_mock()
with self.assertRaisesRegex(runner.FinalGateError, 'exact test selection'):
runner.run_profile(project, test, directory / 'unexpected', environment, selected=selected)
self.assertEqual(process.call_count, 1)
self.assertIn('--list-tests', process.call_args.args[0])
def test_differential_mixed_packet_tags_exist_in_the_owned_control_logix_command(self):
from local_fixtures import definitions
command = definitions()['ab-controllogix']['command']
self.assertIn('--plc=ControlLogix', command)
self.assertIn('--path=1,0', command)
for tag in ('TestString:STRING[1]', 'TestArray:DINT[16]', 'TestDINT:DINT[1]', 'TestBOOL:BOOL[1]'):
self.assertIn('--tag=' + tag, command)
def test_cleanup_preserves_primary_failure_and_propagates_cleanup_only_failure(self):
def failed(): raise RuntimeError('private secret')
self.assertFalse(runner.cleanup_preserving_failure(failed, True))
with self.assertRaisesRegex(runner.FinalGateError, 'owned fixture cleanup failed'):
runner.cleanup_preserving_failure(failed, False)
self.assertTrue(runner.cleanup_preserving_failure(lambda: None, True))
def test_logged_run_uses_restricted_files_and_does_not_record_environment(self):
with tempfile.TemporaryDirectory() as folder:
with patch.object(runner.subprocess, 'run') as process:
process.return_value.returncode = 3
self.assertEqual(runner.logged_run('sample', ['tool'], Path(folder), {'SECRET': 'never-write-this'}), 3)
for path in Path(folder).iterdir():
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
self.assertNotIn('never-write-this', path.read_text())
def report(self, assembly='Example.Tests', outcome='Passed', name='Example.Cases.Case', reason='missing'):
row = {'assembly': assembly, 'test': name, 'outcome': outcome, 'reason': reason, 'trx': '/private/result.trx'}
return {'rows': [row], 'executed': 12000 if outcome == 'Passed' else 0,
'skipped': [row] if outcome == 'NotExecuted' else [], 'failures': [],
'missing_assemblies': [assembly] if outcome == 'NotExecuted' else [], 'missing_grpc_classes': [], 'skipped_grpc': []}
def test_unknown_software_skip_fails_even_when_another_run_passed_same_case(self):
baseline = self.report(outcome='NotExecuted', reason='SQL fixture unreachable')
discovery = [{'assembly': 'Example.Tests', 'tests': ['Example.Cases.Case']}]
result = runner.reconcile(baseline, {'attempt': self.report()}, discovery, {}, {})
self.assertFalse(result['passed'])
self.assertEqual(len(result['unresolved_skips']), 1)
def test_exact_profile_skip_closes_only_with_same_concrete_case_pass(self):
assembly = 'ZB.MOM.WW.OtOpcUa.Driver.Modbus.IntegrationTests'
baseline = self.report(assembly, 'NotExecuted', reason='MODBUS_SIM_PROFILE != dl205')
discovery = [{'assembly': assembly, 'tests': ['Example.Cases.Case']}]
profile_discovery = {'modbus-dl205': discovery}
result = runner.reconcile(baseline, {'modbus-dl205': self.report(assembly)}, discovery, profile_discovery, {})
self.assertEqual(result['unresolved_skips'], [])
self.assertEqual(result['skip_decisions'][0]['disposition'], 'executed-in-profile')
self.assertFalse(result['passed']) # Overlays can never satisfy the baseline12000 floor.
missing = self.report(assembly, name='Example.Cases.Another')
self.assertTrue(runner.reconcile(baseline, {'modbus-dl205': missing}, discovery, profile_discovery, {})['unresolved_skips'])
def test_overlays_require_their_own_exact_rows_and_assembly(self):
profile = 'ab-micro800'
assembly = runner.PROFILE_PROJECTS[profile]
baseline_case = 'Example.Cases.Case(profile: "controllogix")'
baseline = self.report(assembly, name=baseline_case)
discovery = [{'assembly': assembly, 'tests': [baseline_case]}]
profile_discovery = {name: [{'assembly': project, 'tests': [f'Example.Cases.Case(profile: "{name}")']}]
for name, project in runner.PROFILE_PROJECTS.items()}
overlays = {name: self.report(project, name=profile_discovery[name][0]['tests'][0])
for name, project in runner.PROFILE_PROJECTS.items()}
self.assertTrue(runner.reconcile(baseline, overlays, discovery, profile_discovery, {})['passed'])
swapped_discovery = {**profile_discovery, profile: discovery}
report = runner.reconcile(baseline, overlays, discovery, swapped_discovery, {})
self.assertFalse(report['passed'])
self.assertEqual(report['missing_results'], [])
gap = report['overlay_discovery_gaps'][profile]
self.assertEqual(gap['missing'], [(assembly, baseline_case)])
self.assertEqual(gap['unexpected'], [(assembly, overlays[profile]['rows'][0]['test'])])
foreign = assembly.replace('ZB.MOM.WW.OtOpcUa', 'Foreign')
profile_case = profile_discovery[profile][0]['tests'][0]
wrong_discovery = {**profile_discovery, profile: [{'assembly': foreign, 'tests': [profile_case]}]}
wrong_overlays = {**overlays, profile: self.report(foreign, name=profile_case)}
gap = runner.reconcile(baseline, wrong_overlays, discovery, wrong_discovery, {})['overlay_discovery_gaps'][profile]
self.assertFalse(gap['discovery_matches_assembly'])
missing_discovery = dict(profile_discovery)
del missing_discovery[profile]
self.assertFalse(runner.reconcile(baseline, overlays, discovery, missing_discovery, {})['passed'])
def test_differential_credits_only_an_exact_simulator_pass_and_skip_reason(self):
assembly = runner.AB_CIP_ASSEMBLY
test = runner.AB_DIFFERENTIAL_MIX_CASE
skip = self.report(assembly, 'NotExecuted', name=test, reason=runner.AB_DIFFERENTIAL_SKIP)
baseline = {**skip, 'executed': 12000, 'missing_assemblies': []}
discovery = [{'assembly': assembly, 'tests': [test]}]
profile_discovery = {name: [{'assembly': project, 'tests': ['Example.Cases.Pass']}]
for name, project in runner.PROFILE_PROJECTS.items()}
overlays = {name: self.report(project, name='Example.Cases.Pass') for name, project in runner.PROFILE_PROJECTS.items()}
selected = sorted(runner.AB_DIFFERENTIAL_CASES)
differential_discovery = [{'assembly': assembly, 'tests': selected}]
rows = [self.report(assembly, name=case)['rows'][0] for case in selected]
differential = {**self.report(assembly), 'rows': rows, 'executed': len(rows)}
def report(base=baseline, supplemental=differential, discovered=differential_discovery, baseline_discovery=discovery):
return runner.reconcile(base, overlays, baseline_discovery, profile_discovery, {},
differential=supplemental, differential_discovery=discovered)
passed = report()
self.assertTrue(passed['passed'])
self.assertEqual(passed['skip_decisions'][0]['passed_in'], [runner.AB_DIFFERENTIAL_RUN])
self.assertFalse(report(base={**baseline, 'executed': 11999})['passed'])
wrong_reason = self.report(assembly, 'NotExecuted', name=test, reason=runner.AB_DIFFERENTIAL_SKIP + ' unrelated')
self.assertTrue(report(base={**baseline, 'rows': wrong_reason['rows'], 'skipped': wrong_reason['skipped']})['unresolved_skips'])
unrelated_test = test.rsplit('.', 1)[0] + '.Symbol_listing_pages_are_ascending_on_a_real_controller'
unrelated_skip = self.report(assembly, 'NotExecuted', name=unrelated_test, reason=runner.AB_DIFFERENTIAL_SKIP)
self.assertTrue(report(base={**baseline, 'rows': unrelated_skip['rows'], 'skipped': unrelated_skip['skipped']},
baseline_discovery=[{'assembly': assembly, 'tests': [unrelated_test]}])['unresolved_skips'])
invalid_evidence = report(discovered=[{'assembly': assembly, 'tests': selected[:-1]}])
self.assertFalse(invalid_evidence['passed'])
self.assertTrue(invalid_evidence['software_differential_discovery_gaps']['missing_discovery'])
self.assertTrue(invalid_evidence['unresolved_skips'])
duplicate = report(supplemental={**differential, 'rows': rows + rows[:1]})
self.assertTrue(duplicate['software_differential_discovery_gaps']['duplicate_rows'])
os_skip = self.report(assembly, 'NotExecuted', name=test, reason='This OS cannot enumerate TCP connections.')
skipped = report(supplemental={**differential, 'rows': [*os_skip['rows'], *(row for row in rows if row['test'] != test)],
'skipped': os_skip['skipped']})
self.assertFalse(skipped['passed'])
self.assertEqual({row['run'] for row in skipped['unresolved_skips']}, {'baseline', runner.AB_DIFFERENTIAL_RUN})
def test_zero_execution_needs_every_discovered_case_concrete_and_explicitly_unavailable(self):
baseline = self.report(outcome='NotExecuted', reason='Windows required')
discovery = [{'assembly': 'Example.Tests', 'tests': ['Example.Cases.Case']}]
evidence = {('Example.Tests', 'Example.Cases.Case'): {'reason': 'Windows required'}}
result = runner.reconcile(baseline, {}, discovery, {}, evidence)
self.assertEqual(result['fully_unavailable_projects'], ['Example.Tests'])
discovery[0]['tests'].append('Example.Cases.Missing')
result = runner.reconcile(baseline, {}, discovery, {}, evidence)
self.assertEqual(result['missing_assemblies'], ['Example.Tests'])
self.assertEqual(result['missing_results'], [('Example.Tests', 'Example.Cases.Missing')])
def test_unavailable_evidence_rejects_patterns_missing_file_and_feature_waivers(self):
with tempfile.TemporaryDirectory() as folder:
evidence = Path(folder) / 'platform.txt'; evidence.write_text('Observed local macOS; Windows runtime unavailable')
document = Path(folder) / 'unavailable.json'
item = {'assembly': 'Example.Tests', 'test': 'Example.Windows.Case', 'reason': 'Windows required', 'kind': 'platform',
'requires': 'Windows named pipe ACLs', 'evidence': str(evidence), 'next_gate': 'Windows gate with exact test'}
document.write_text(json.dumps([item]))
result = runner.unavailable_records(document)
self.assertIn('evidence_sha256', result[('Example.Tests', 'Example.Windows.Case')])
for field, value in [('test', 'Example.*'), ('test', 'Example.GrpcDataTests.Case'), ('evidence', '/not-present/platform.txt'), ('next_gate', '')]:
document.write_text(json.dumps([{**item, field: value}]))
with self.assertRaises(runner.FinalGateError): runner.unavailable_records(document)
def test_trx_keeps_theory_row_arguments_and_unknown_outcomes_fail(self):
with tempfile.TemporaryDirectory() as folder:
projects = self.trx(folder, cls='Example.Cases')
projects[0]['grpc_classes'] = []
path = Path(folder) / 'result.trx'
path.write_text(path.read_text().replace('outcome="Passed"', 'testName="Example.Cases.Case(value: 42)" outcome="Passed"'))
self.assertEqual(runner.read_results(folder, projects, minimum=1)['rows'][0]['test'], 'Example.Cases.Case(value: 42)')
path.write_text(path.read_text().replace('outcome="Passed"', 'outcome="Inconclusive"'))
self.assertFalse(runner.read_results(folder, projects, minimum=1)['passed'])
def test_xunit_deferred_theory_reconciles_canonical_id_and_keeps_concrete_outcomes(self):
assembly = 'Example.Tests'
parent = 'Example.Cases.Case'
names = [parent + '(value: 42)', parent + '(value: 43)']
identities = {(assembly, name) for name in names}
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / 'result.trx'
projects = [{'assembly': assembly, 'grpc_classes': []}]
definition = (f'<UnitTest id="theory-id" name="{parent}"><TestMethod codeBase="{assembly}.dll"'
' className="Example.Cases" name="Case" adapterTypeName="executor://xunit/VsTestRunner3/netcore/"/></UnitTest>')
results = [f'<UnitTestResult testId="theory-id" testName="{name}" outcome="{outcome}" executionId="{index}"/>'
for index, (name, outcome) in enumerate(zip(names, ('Passed', 'NotExecuted')))]
def read_trx(definitions=definition, rows=results):
path.write_text(f'<TestRun><TestDefinitions>{definitions}</TestDefinitions><Results>{"".join(rows)}</Results></TestRun>')
return runner.read_results(folder, projects, minimum=1)
report = read_trx()
missing, unexpected, expanded = runner.discovery_gaps({(assembly, parent)}, report['rows'])
self.assertEqual((missing, unexpected), ([], []))
self.assertEqual(expanded, [{'assembly': assembly, 'method': parent, 'test_id': 'theory-id', 'trx': str(path),
'rows': [{'test': names[0], 'outcome': 'Passed', 'execution_id': '0'},
{'test': names[1], 'outcome': 'NotExecuted', 'execution_id': '1'}]}])
self.assertEqual(report['skipped'][0]['test'], names[1])
self.assertEqual(report['executed'], 1)
partial_discovery = {(assembly, parent), (assembly, names[0])}
missing, unexpected, expanded = runner.discovery_gaps(partial_discovery, report['rows'])
self.assertEqual((missing, unexpected, expanded), ([(assembly, parent)], [(assembly, names[1])], []))
self.assertEqual(runner.discovery_gaps(identities, report['rows']), ([], [], []))
repeated_display = read_trx(rows=[results[0], results[1].replace(names[1], names[0])])
missing, unexpected, expanded = runner.discovery_gaps({(assembly, parent)}, repeated_display['rows'])
self.assertEqual((missing, unexpected), ([], []))
self.assertEqual([row['execution_id'] for row in expanded[0]['rows']], ['0', '1'])
noncanonical = definition.replace(f'name="{parent}"', f'name="{names[0]}"')
split_id = definition + definition.replace('theory-id', 'different-id')
for label, rejected in (('enumerated definition', read_trx(noncanonical)),
('split ID', read_trx(split_id, [results[0], results[1].replace('theory-id', 'different-id')])),
('duplicate execution', read_trx(rows=[results[0], results[0]]))):
with self.subTest(label=label):
missing, unexpected, expanded = runner.discovery_gaps({(assembly, parent)}, rejected['rows'])
self.assertEqual(missing, [(assembly, parent)])
self.assertTrue(unexpected)
self.assertEqual(expanded, [])
if __name__ == '__main__': unittest.main()
@@ -0,0 +1,448 @@
"""No daemon is contacted: exercise lifecycle decisions against a fake CLI."""
import contextlib
import io
import json
import os
from pathlib import Path
import sys
import tempfile
import unittest
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import local_fixtures as fixtures
class FakeDocker:
def __init__(self):
self.resources = {kind: {} for kind in ("container", "network", "volume", "image")}
self.calls = []
self.sequence = 0
self.fail_start = False
self.dynamic_ports = set()
self.context = {"Name": "desktop", "Endpoints": {"docker": {"Host": "unix:///tmp/local-docker.sock"}}}
def new(self, kind, name, labels=None, *, ports=None):
self.sequence += 1
identity = f"{self.sequence:064x}" if kind != "volume" else name
row = {"Id": identity, "Name": name, "Labels": labels or {}, "Config": {"Labels": labels or {}, "Volumes": {}},
"NetworkSettings": {"Ports": ports or {}}, "State": {"Running": False}}
self.resources[kind][identity] = row
return identity
def find(self, kind, identity):
for key, row in self.resources[kind].items():
if identity in (key, row["Name"]):
return row
return None
def __call__(self, argv, *, check=True, **kwargs):
self.calls.append(list(argv))
args = list(argv)
if args[0] != "docker":
raise AssertionError("unexpected non-Docker command")
args.pop(0)
if args[:1] == ["--context"]:
del args[:2]
if args[:2] == ["context", "inspect"]:
return 0, json.dumps([self.context]).encode()
if args[:1] == ["pull"]:
image = args[-1]
if not self.find("image", image):
self.new("image", image)
return 0, b"pulled\n"
kind, verb = args[:2]
if verb == "inspect":
row = self.find(kind, args[2])
return (0, json.dumps([row]).encode()) if row else (1, ("Error response from daemon: No such " + kind + "\n").encode())
if verb == "create":
labels = {}
for index, item in enumerate(args):
if item == "--label":
key, value = args[index + 1].split("=", 1)
labels[key] = value
if kind == "network":
name = args[-1]
elif kind == "volume":
name = args[-1]
else:
name = args[args.index("--name") + 1]
if self.find(kind, name):
raise AssertionError("attempted to replace a resource")
ports = {}
for index, item in enumerate(args):
if item == "--publish":
host, published, internal = args[index + 1].split(":")
ports[internal + "/tcp"] = [{"HostIp": host, "HostPort": published or str(30000 + self.sequence)}]
identity = self.new(kind, name, labels, ports=ports)
if any(item == "--publish" and args[index + 1].split(":")[1] == "" for index, item in enumerate(args)):
self.dynamic_ports.add(identity)
return 0, (identity + "\n").encode()
if kind == "container" and verb == "start":
row = self.find(kind, args[2])
if self.fail_start:
raise fixtures.FixtureError("port unavailable")
row["State"]["Running"] = True
return 0, (args[2] + "\n").encode()
if kind == "container" and verb in {"pause", "unpause", "restart"}:
row = self.find(kind, args[2])
if row is None:
raise AssertionError("controlled an unknown container")
row["State"]["Paused"] = verb == "pause"
if verb == "restart" and args[2] in self.dynamic_ports:
for bindings in row["NetworkSettings"]["Ports"].values():
for binding in bindings:
binding["HostPort"] = str(int(binding["HostPort"]) + 1000)
return 0, (args[2] + "\n").encode()
if verb == "rm":
identity = args[-1]
if identity not in self.resources[kind]:
raise AssertionError("cleanup must target exact recorded resource ID")
del self.resources[kind][identity]
return 0, (identity + "\n").encode()
raise AssertionError("unexpected fake CLI operation: " + repr(args[:2]))
class NoNetworkFixtures(fixtures.OwnedFixtures):
def ready(self, service):
self.manifest["services"][service]["ready"] = True
self.save()
class FixtureOwnershipTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.directory = Path(self.temp.name)
self.fake = FakeDocker()
def environment(self, owner="run-a"):
return {"CI_FIXTURE_LOCAL_OWNED": "1", "CI_FIXTURE_SUFFIX": owner, "FIXTURE_HOST": "127.0.0.1",
"CI_FIXTURE_ENV_JSON": str(self.directory / (owner + ".json")), "CI_FIXTURE_SERVICES": "sql"}
def subject(self, owner="run-a", **changes):
env = self.environment(owner)
env.update(changes)
return NoNetworkFixtures(env, process=self.fake)
def mutations(self):
return [call for call in self.fake.calls if any(item in {"create", "start", "rm", "pull", "build"} for item in call)]
def s7_spec(self):
spec = dict(fixtures.definitions()["s7"])
spec.pop("build")
spec["image"] = "unit/s7"
return spec
def reserve_port(self, port=52102):
socket = mock.Mock()
socket.__enter__ = mock.Mock(return_value=socket)
socket.__exit__ = mock.Mock(return_value=False)
socket.getsockname.return_value = ("127.0.0.1", port)
return socket
def test_s7_owned_publication_is_reserved_explicitly_and_preserved_across_restart(self):
instance = self.subject(CI_FIXTURE_SERVICES="s7")
spec, reservation = self.s7_spec(), self.reserve_port()
with mock.patch.object(fixtures, "definitions", return_value={"s7": spec}), \
mock.patch.object(fixtures.socket, "socket", return_value=reservation):
instance.up()
identity = instance.containers["s7"]
create = next(call for call in self.fake.calls if "create" in call and "--publish" in call)
self.assertEqual(create[create.index("--publish") + 1], "127.0.0.1:52102:1102")
reservation.bind.assert_called_once_with(("127.0.0.1", 0))
before = fixtures.read_private(instance.output)["S7_SIM_ENDPOINT"]
instance.control("s7", identity, "restart")
bindings = self.fake.resources["container"][identity]["NetworkSettings"]["Ports"]["1102/tcp"]
self.assertEqual(bindings, [{"HostIp": "127.0.0.1", "HostPort": "52102"}])
self.assertEqual(before, "127.0.0.1:52102")
self.assertEqual(fixtures.read_private(instance.output)["S7_SIM_ENDPOINT"], before)
def test_s7_restart_refuses_changed_publication_before_mutation(self):
instance = self.subject(CI_FIXTURE_SERVICES="s7")
spec = self.s7_spec()
with mock.patch.object(fixtures, "definitions", return_value={"s7": spec}), \
mock.patch.object(fixtures.socket, "socket", return_value=self.reserve_port()):
instance.up()
identity = instance.containers["s7"]
self.fake.resources["container"][identity]["NetworkSettings"]["Ports"]["1102/tcp"][0]["HostPort"] = "52999"
before = len(self.fake.calls)
with self.assertRaisesRegex(fixtures.FixtureError, "publication|endpoint"):
instance.control("s7", identity, "restart")
self.assertFalse(any("restart" in call for call in self.fake.calls[before:]))
def test_s7_reserved_port_collision_leaves_owned_id_journaled_for_safe_cleanup(self):
unrelated = self.fake.new("container", "personal-s7", {"keep": "me"})
self.fake.fail_start = True
instance = self.subject(CI_FIXTURE_SERVICES="s7")
spec = self.s7_spec()
with mock.patch.object(fixtures, "definitions", return_value={"s7": spec}), \
mock.patch.object(fixtures.socket, "socket", return_value=self.reserve_port()):
with self.assertRaisesRegex(fixtures.FixtureError, "port"):
instance.up()
self.assertFalse(instance.output.exists())
created = [row["id"] for row in fixtures.read_private(instance.manifest_path)["resources"] if row["kind"] == "container"]
self.assertEqual(len(created), 1)
self.subject().down()
self.assertNotIn(created[0], self.fake.resources["container"])
self.assertIn(unrelated, self.fake.resources["container"])
def test_s7_foreign_labels_are_rejected_before_restart(self):
instance = self.subject(CI_FIXTURE_SERVICES="s7")
spec = self.s7_spec()
with mock.patch.object(fixtures, "definitions", return_value={"s7": spec}), \
mock.patch.object(fixtures.socket, "socket", return_value=self.reserve_port()):
instance.up()
identity = instance.containers["s7"]
self.fake.resources["container"][identity]["Config"]["Labels"] = {"foreign": "owner"}
before = len(self.fake.calls)
with self.assertRaisesRegex(fixtures.FixtureError, "foreign"):
instance.control("s7", identity, "restart")
self.assertFalse(any("restart" in call for call in self.fake.calls[before:]))
def test_s7_restart_rechecks_owned_binding_after_docker_returns(self):
instance = self.subject(CI_FIXTURE_SERVICES="s7")
spec = self.s7_spec()
with mock.patch.object(fixtures, "definitions", return_value={"s7": spec}), \
mock.patch.object(fixtures.socket, "socket", return_value=self.reserve_port()):
instance.up()
identity = instance.containers["s7"]
original = self.fake
def drifting(argv, **kwargs):
result = original(argv, **kwargs)
if "restart" in argv:
original.resources["container"][identity]["NetworkSettings"]["Ports"]["1102/tcp"][0]["HostPort"] = "52999"
return result
instance.process = drifting
with self.assertRaisesRegex(fixtures.FixtureError, "publication|endpoint"):
instance.control("s7", identity, "restart")
def test_nonempty_safe_owner_and_explicit_loopback_required(self):
for changes in ({"CI_FIXTURE_SUFFIX": ""}, {"CI_FIXTURE_SUFFIX": "../other"}, {"FIXTURE_HOST": "10.100.0.35"}, {"FIXTURE_HOST": "localhost"}, {"CI_FIXTURE_LOCAL_OWNED": ""}):
with self.subTest(changes=changes), self.assertRaises(fixtures.FixtureError):
self.subject(**changes)
self.assertFalse(self.fake.calls)
def test_remote_docker_context_refused_before_mutation(self):
self.fake.context["Endpoints"]["docker"]["Host"] = "tcp://127.0.0.1:2375"
with self.assertRaises(fixtures.FixtureError):
self.subject().up()
self.assertEqual([], self.mutations())
def test_foreign_name_is_never_removed_or_adopted(self):
foreign = self.fake.new("container", "grpc-final-run-a-sql", {"foreign": "owner"})
instance = self.subject()
with self.assertRaisesRegex(fixtures.FixtureError, "exists"):
instance.up()
self.assertIn(foreign, self.fake.resources["container"])
self.assertFalse(any("rm" in call or "pull" in call for call in self.fake.calls))
# Explicit teardown cleans the network it did create, preserving the name collision.
self.subject().down()
self.assertIn(foreign, self.fake.resources["container"])
def test_parallel_runs_keep_independent_ids_and_dynamic_loopback_ports(self):
first, second = self.subject(), self.subject("run-b")
first.up()
second.up()
second_ids = {row["id"] for row in second.manifest["resources"]}
self.assertNotEqual(first.containers["sql"], second.containers["sql"])
self.assertNotEqual(first.ports["sql"], second.ports["sql"])
networks = [call for call in self.fake.calls if "network" in call and "create" in call]
self.assertEqual(2, len(networks))
for call in networks:
self.assertIn("--driver", call)
self.assertEqual("bridge", call[call.index("--driver") + 1])
self.assertNotIn("--internal", call)
for call in self.fake.calls:
if "--publish" in call:
binding = call[call.index("--publish") + 1]
self.assertEqual("127.0.0.1::1433", binding)
self.subject().down()
observed = set().union(*(set(rows) for rows in self.fake.resources.values()))
self.assertTrue(second_ids <= observed)
self.subject("run-b").down()
def test_ab_overlays_keep_the_owned_controllogix_companion(self):
families = ("controllogix", "compactlogix", "micro800", "guardlogix")
services = ["ab-" + family for family in families]
specs = {service: {"image": "unit/ab", "ports": [44818]} for service in services}
instance = self.subject(CI_FIXTURE_SERVICES=",".join(services))
with mock.patch.object(fixtures, "definitions", return_value=specs):
instance.up()
endpoints = {}
for service in services:
container = self.fake.resources["container"][instance.containers[service]]
binding = container["NetworkSettings"]["Ports"]["44818/tcp"][0]
endpoints[service] = f'{binding["HostIp"]}:{binding["HostPort"]}'
self.assertEqual(len(services), len(set(endpoints.values())))
base = fixtures.read_private(instance.output)
control = endpoints["ab-controllogix"]
self.assertEqual(base["AB_SERVER_ENDPOINT"], control)
self.assertEqual(base["AB_SERVER_CONTROLLOGIX_ENDPOINT"], control)
overlays = fixtures.read_private(instance.directory / "profile-environments.json")
self.assertEqual(set(overlays), set(services[1:]))
for family, service in zip(families[1:], services[1:]):
self.assertEqual(overlays[service]["AB_SERVER_COMPOSE_PROFILE"], family)
self.assertEqual(overlays[service]["AB_SERVER_ENDPOINT"], endpoints[service])
self.assertEqual(overlays[service]["AB_SERVER_CONTROLLOGIX_ENDPOINT"], control)
def test_failed_port_start_journals_id_and_down_removes_only_that_id(self):
unrelated = self.fake.new("container", "personal-sql", {"keep": "me"})
self.fake.fail_start = True
instance = self.subject()
with self.assertRaisesRegex(fixtures.FixtureError, "port"):
instance.up()
manifest = fixtures.read_private(instance.manifest_path)
created = [row["id"] for row in manifest["resources"] if row["kind"] == "container"]
self.assertEqual(1, len(created))
self.assertFalse(instance.output.exists())
self.subject().down()
removals = [call[-1] for call in self.fake.calls if "rm" in call]
self.assertIn(created[0], removals)
self.assertNotIn(unrelated, removals)
self.assertIn(unrelated, self.fake.resources["container"])
def test_teardown_validates_all_labels_before_any_remove(self):
instance = self.subject()
instance.up()
identity = instance.containers["sql"]
self.fake.resources["container"][identity]["Config"]["Labels"] = {"foreign": "owner"}
with self.assertRaisesRegex(fixtures.FixtureError, "foreign"):
self.subject().down()
self.assertFalse(any("rm" in call for call in self.fake.calls))
def test_same_suffix_cannot_reuse_previous_output(self):
self.subject().up()
count = len(self.fake.calls)
with self.assertRaises(fixtures.FixtureError):
self.subject().up()
self.assertEqual(count, len(self.fake.calls))
def test_pending_creation_recovered_by_labels_then_exact_id(self):
instance = self.subject()
instance.prepare(creating=True)
name = instance.project + "-interrupted"
identity = self.fake.new("container", name, instance.labels)
instance.manifest["pending"].append({"kind": "container", "name": name})
instance.save()
self.subject().down()
self.assertNotIn(identity, self.fake.resources["container"])
self.assertTrue(any(call[-1] == identity and "rm" in call for call in self.fake.calls))
def test_foreign_pending_name_refuses_cleanup(self):
instance = self.subject()
instance.prepare(creating=True)
name = instance.project + "-interrupted"
self.fake.new("container", name, {"foreign": "owner"})
instance.manifest["pending"].append({"kind": "container", "name": name})
instance.save()
with self.assertRaises(fixtures.FixtureError):
self.subject().down()
self.assertFalse(any("rm" in call for call in self.fake.calls))
def test_environment_is_private_allowlisted_and_never_printed(self):
instance = self.subject(SQL_TEST_ENDPOINT="10.100.0.35,14330", SQL_TEST_PASSWORD="do-not-leak", GITHUB_ENV="/tmp/foreign-env")
stdout = io.StringIO()
with contextlib.redirect_stdout(stdout):
instance.up()
self.assertEqual("", stdout.getvalue())
env = fixtures.read_private(instance.output)
self.assertNotIn("do-not-leak", json.dumps(env))
self.assertEqual("127.0.0.1", env["SQL_TEST_ENDPOINT"].split(",")[0])
self.assertEqual(0o600, instance.output.stat().st_mode & 0o777)
self.assertEqual(0o600, instance.manifest_path.stat().st_mode & 0o777)
self.assertEqual(0o700, instance.directory.stat().st_mode & 0o777)
self.assertNotIn("SQL_TEST_PASSWORD", instance.environment)
self.assertNotIn("GITHUB_ENV", instance.environment)
def test_world_readable_or_wrong_owner_manifest_is_refused(self):
instance = self.subject()
instance.up()
instance.manifest_path.chmod(0o644)
with self.assertRaises(fixtures.FixtureError):
self.subject().down()
self.assertFalse(any("rm" in call for call in self.fake.calls))
def test_daemon_inspection_error_is_not_treated_as_missing(self):
instance = self.subject()
instance.up()
real = self.fake
def failing(argv, **kwargs):
if "container" in argv and "inspect" in argv:
return 1, b"Cannot connect to the Docker daemon"
return real(argv, **kwargs)
down = NoNetworkFixtures(self.environment(), process=failing)
with self.assertRaises(fixtures.FixtureError):
down.down()
self.assertFalse(any("rm" in call for call in self.fake.calls))
self.assertEqual("ready", fixtures.read_private(instance.manifest_path)["status"])
def test_control_rechecks_recorded_id_and_foreign_labels(self):
instance = self.subject(CI_FIXTURE_SERVICES="sql-blackhole")
instance.up()
identity = instance.containers["sql-blackhole"]
endpoint = instance.endpoint("sql-blackhole").replace(":", ",")
instance.control("sql-blackhole", identity, "pause", endpoint)
self.assertTrue(self.fake.resources["container"][identity]["State"]["Paused"])
before = len(self.fake.calls)
with self.assertRaises(fixtures.FixtureError):
self.subject().control("sql-blackhole", "f" * 64, "unpause", endpoint)
self.assertFalse(any("unpause" in call for call in self.fake.calls[before:]))
self.fake.resources["container"][identity]["Config"]["Labels"] = {"foreign": "owner"}
with self.assertRaises(fixtures.FixtureError):
self.subject().control("sql-blackhole", identity, "unpause", endpoint)
self.assertFalse(any("unpause" in call for call in self.fake.calls))
def test_blackhole_endpoint_is_verified_before_any_sql_or_control_mutation(self):
instance = self.subject(CI_FIXTURE_SERVICES="sql-blackhole")
instance.up()
identity = instance.containers["sql-blackhole"]
with self.assertRaises(fixtures.FixtureError):
self.subject().control("sql-blackhole", identity, "verify", "127.0.0.1,14330")
self.assertFalse(any("pause" in call or "unpause" in call for call in self.fake.calls))
def test_optional_odbc_driver_uses_only_owned_postgres(self):
library = self.directory / "psqlodbcw.so"
library.write_bytes(b"local-driver-placeholder")
instance = self.subject(CI_FIXTURE_SERVICES="postgres", CI_FIXTURE_ODBC_DRIVER=str(library))
instance.up()
env = fixtures.read_private(instance.output)
connection = env["SQL_ODBC_CONNECTION_STRING"]
self.assertIn("Driver={" + str(library) + "};", connection)
self.assertIn("Server=127.0.0.1;", connection)
self.assertIn("Port=" + str(instance.ports["postgres"][5432]) + ";", connection)
self.assertIn("Pwd=" + env["SQL_PG_PASSWORD"] + ";", connection)
self.assertNotIn("SQL_ODBC_CONNECTION_STRING", instance.environment)
def test_odbc_driver_path_cannot_inject_connection_options(self):
for path in ("relative-driver.so", "/missing-driver.so", "/tmp/driver;Server=foreign.so", "/tmp/driver}foreign.so"):
with self.subTest(path=path), self.assertRaises(fixtures.FixtureError):
self.subject(CI_FIXTURE_ODBC_DRIVER=path)
self.assertFalse(self.fake.calls)
def test_mac_group_kill_refusal_falls_back_to_owned_child(self):
process = fixtures.PrivateProcess(self.directory, dict(os.environ))
with mock.patch.object(fixtures.os, "killpg", side_effect=PermissionError("host denies process groups")):
with self.assertRaises(fixtures.FixtureError):
process([sys.executable, "-c", "import time; time.sleep(30)"], timeout=0.05)
def test_bounded_process_output_and_timeout_are_redacted(self):
process = fixtures.PrivateProcess(self.directory, dict(os.environ))
with mock.patch.object(fixtures, "LIMIT", 128), self.assertRaises(fixtures.FixtureError):
process([sys.executable, "-c", "print('secret'*1000)"])
with self.assertRaises(fixtures.FixtureError):
process([sys.executable, "-c", "import time; time.sleep(30)"], timeout=0.05)
for path in self.directory.glob("*.log"):
self.assertLessEqual(path.stat().st_size, 128)
self.assertEqual(0o600, path.stat().st_mode & 0o777)
def test_ci_dispatch_precedes_legacy_defaults_and_mutation(self):
source = (fixtures.ROOT / "scripts/ci/integration-fixtures.sh").read_text()
dispatch = source.index('if [ "${CI_FIXTURE_LOCAL_OWNED:-}" = "1" ]')
self.assertLess(dispatch, source.index('SQL_PORT="${CI_SQL_PORT'))
self.assertLess(dispatch, source.index('down()'))
if __name__ == "__main__":
unittest.main()
@@ -692,5 +692,34 @@
"GrpcDataProjectedAccessTests"
]
}
],
"P12": [
{
"project": "tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests.csproj",
"filter": "FullyQualifiedName~.LocalFixtureEndpointGuardTests.",
"new_classes": [
"LocalFixtureEndpointGuardTests"
],
"existing_classes": [],
"integration_unit_guards": true
},
{
"project": "tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.IntegrationTests/ZB.MOM.WW.OtOpcUa.Driver.Sql.IntegrationTests.csproj",
"filter": "FullyQualifiedName~.OwnedBlackholeControlGuardTests.",
"new_classes": [
"OwnedBlackholeControlGuardTests"
],
"existing_classes": [],
"integration_unit_guards": true
},
{
"project": "tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.IntegrationTests/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.IntegrationTests.csproj",
"filter": "FullyQualifiedName~.AbLegacyFixtureEndpointGuardTests.",
"new_classes": [
"AbLegacyFixtureEndpointGuardTests"
],
"existing_classes": [],
"integration_unit_guards": true
}
]
}