255 lines
12 KiB
Python
255 lines
12 KiB
Python
#!/usr/bin/env python3
|
|
"""Run only the explicit gRPC data unit selectors, with fail-closed evidence."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import shlex
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from datetime import datetime, timezone
|
|
import uuid
|
|
import xml.etree.ElementTree as ET
|
|
|
|
|
|
class GateError(Exception):
|
|
def __init__(self, message, exit_code=1):
|
|
super().__init__(message)
|
|
self.exit_code = exit_code if exit_code > 0 else 128 - exit_code
|
|
|
|
|
|
# Deliberately permit toolchain/OS identity only. No ambient fixture credentials,
|
|
# connection strings, Docker context or arbitrary application configuration pass.
|
|
ENV_ALLOWLIST = frozenset({
|
|
"PATH", "HOME", "USER", "LOGNAME", "SHELL", "TMPDIR", "TMP", "TEMP",
|
|
"LANG", "LC_ALL", "LC_CTYPE", "SYSTEMROOT", "SystemRoot", "WINDIR",
|
|
"COMSPEC", "PATHEXT", "USERPROFILE", "LOCALAPPDATA", "APPDATA",
|
|
"DOTNET_ROOT", "DOTNET_ROOT_X64", "DOTNET_ROOT_ARM64", "DOTNET_CLI_HOME",
|
|
"DOTNET_MULTILEVEL_LOOKUP", "DOTNET_ROLL_FORWARD", "NUGET_PACKAGES",
|
|
"MSBuildSDKsPath", "MSBUILD_EXE_PATH", "SSL_CERT_FILE", "SSL_CERT_DIR",
|
|
})
|
|
|
|
|
|
def unit_environment(inherited=None):
|
|
source = os.environ if inherited is None else inherited
|
|
env = {key: value for key, value in source.items() if key in ENV_ALLOWLIST}
|
|
env.update({
|
|
"AKKA_TEST_TIMEFACTOR": "3", "OTOPCUA_UNIT_ONLY_DISCOVERY": "1",
|
|
"OTOPCUA_CONFIG_TEST_SERVER": "127.0.0.1,1",
|
|
"OTOPCUA_CONFIG_TEST_SA_PASSWORD": "UnitOnly_Unavailable_9!",
|
|
"OTOPCUA_CONFIG_CONNECTION": "Server=127.0.0.1,1;Database=unit_only;User Id=sa;Password=UnitOnly_Unavailable_9!;Connect Timeout=1;Encrypt=False;",
|
|
"OTOPCUA_TEST_SERVER": "opc.tcp://127.0.0.1:1",
|
|
"OTOPCUA_OPCPLC_ENDPOINT": "opc.tcp://127.0.0.1:1",
|
|
})
|
|
return env
|
|
|
|
|
|
def write_json(path, value):
|
|
path.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8")
|
|
|
|
|
|
def class_matches(name, class_name):
|
|
# Restrict the class component, so FooTests does not accept FooTestsExtra.
|
|
stem = name.split("(", 1)[0]
|
|
return stem.startswith(class_name + ".") or ("." + class_name + ".") in stem
|
|
|
|
|
|
def discover_names(output):
|
|
marker = "The following Tests are available:"
|
|
if marker not in output:
|
|
return []
|
|
names = []
|
|
for line in output.split(marker, 1)[1].splitlines():
|
|
value = line.strip()
|
|
if line[:1].isspace() and re.match(r"^[\w.+`]+\.[\w`]+(?:\(.*\))?$", value):
|
|
names.append(value)
|
|
return sorted(set(names))
|
|
|
|
|
|
def command(project, expression, directory, discovery=False):
|
|
argv = ["dotnet", "test", project, "-c", "Release", "-m:1",
|
|
"-p:TestTfmsInParallel=false", "--settings", "scripts/ci/ci.runsettings",
|
|
"--filter", expression, "--results-directory", str(directory)]
|
|
return argv + (["--list-tests"] if discovery else ["--logger", "trx;LogFileName=results.trx"])
|
|
|
|
|
|
def validate_trx(directory, started_ns, expected_classes=()):
|
|
files = list(directory.rglob("*.trx"))
|
|
if not files:
|
|
raise GateError("missing TRX result")
|
|
total_executed = 0
|
|
summaries = []
|
|
executed_classes = set()
|
|
for path in files:
|
|
if path.stat().st_mtime_ns < started_ns:
|
|
raise GateError(f"stale TRX result: {path.name}")
|
|
try:
|
|
root = ET.parse(path).getroot()
|
|
counters = root.find(".//{*}ResultSummary/{*}Counters")
|
|
results = root.findall(".//{*}UnitTestResult")
|
|
if counters is None or not results:
|
|
raise ValueError("missing counters or results")
|
|
counts = {key: int(value) for key, value in counters.attrib.items()}
|
|
executed = counts.get("executed", 0)
|
|
if executed <= 0:
|
|
raise ValueError("zero executed tests")
|
|
if counts.get("failed", 0) or counts.get("error", 0) or counts.get("timeout", 0) or counts.get("aborted", 0):
|
|
raise ValueError("test failures")
|
|
if counts.get("notExecuted", 0) or counts.get("total", 0) != executed:
|
|
raise ValueError("unexpected skipped tests")
|
|
if any(result.get("outcome") != "Passed" for result in results):
|
|
raise ValueError("failed or unexpected skipped result")
|
|
if len(results) != executed or counts.get("passed", 0) != executed:
|
|
raise ValueError("inconsistent executed/passed results")
|
|
definitions = {}
|
|
for unit in root.findall(".//{*}TestDefinitions/{*}UnitTest"):
|
|
method = unit.find("{*}TestMethod")
|
|
if method is not None:
|
|
definitions[unit.get("id")] = method.get("className", "").split(",", 1)[0]
|
|
for result in results:
|
|
class_name = definitions.get(result.get("testId"), "")
|
|
for expected in expected_classes:
|
|
if class_name == expected or class_name.endswith("." + expected):
|
|
executed_classes.add(expected)
|
|
total_executed += executed
|
|
summaries.append({"file": str(path), "counters": counts})
|
|
except (ET.ParseError, ValueError) as exc:
|
|
raise GateError(f"invalid TRX {path.name}: {exc}") from exc
|
|
absent = set(expected_classes) - executed_classes
|
|
if absent:
|
|
raise GateError("missing executed required classes in TRX: " + ", ".join(sorted(absent)))
|
|
return {"executed": total_executed, "files": summaries, "executed_classes": sorted(executed_classes)}
|
|
|
|
|
|
def selected_records(manifest, phase, root, case):
|
|
if phase not in manifest or not manifest[phase]:
|
|
raise GateError(f"unknown or empty phase: {phase}")
|
|
records = []
|
|
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):
|
|
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 case and case not in classes:
|
|
continue
|
|
if case:
|
|
item["filter"] = f'({item["filter"]})&(FullyQualifiedName~.{case}.)'
|
|
item["new_classes"] = [case] if case in item.get("new_classes", []) else []
|
|
item["existing_classes"] = [case] if case in item.get("existing_classes", []) else []
|
|
records.append(item)
|
|
if not records:
|
|
raise GateError(f"unknown class for {phase}: {case}")
|
|
return records
|
|
|
|
|
|
def run_phase(manifest, phase, root, case=None, dry_run=False, invoke=subprocess.run, environ=None):
|
|
root = Path(root).resolve()
|
|
records = selected_records(manifest, phase, root, case)
|
|
run_id = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S.%fZ") + "-" + uuid.uuid4().hex[:12]
|
|
directory = root / "artifacts" / "grpc-data" / run_id / "unit" / phase
|
|
if dry_run:
|
|
for index, item in enumerate(records):
|
|
target = directory / f'{index:02d}-{Path(item["project"]).stem}'
|
|
print(shlex.join(command(item["project"], item["filter"], target, True)))
|
|
print(shlex.join(command(item["project"], item["filter"], target)))
|
|
return directory
|
|
directory.mkdir(parents=True, exist_ok=False)
|
|
env = unit_environment(environ)
|
|
report = {"phase": phase, "case": case, "run_id": run_id, "status": "running", "projects": []}
|
|
started = time.monotonic()
|
|
def child(argv, target, label):
|
|
tick = time.monotonic()
|
|
result = invoke(argv, cwd=str(root), env=env, capture_output=True, text=True, shell=False)
|
|
(target / f"{label}.stdout.log").write_text(result.stdout or "", encoding="utf-8")
|
|
(target / f"{label}.stderr.log").write_text(result.stderr or "", encoding="utf-8")
|
|
if result.returncode:
|
|
raise GateError(f"{label} exited {result.returncode}; see {target}", result.returncode)
|
|
return result, time.monotonic() - tick
|
|
try:
|
|
identity = {}
|
|
for label, args in (("sha", ["rev-parse", "HEAD"]), ("status", ["status", "--porcelain=v1"]), ("diff", ["diff", "HEAD", "--binary"])):
|
|
result = invoke(["git", *args], cwd=str(root), env=env, capture_output=True, text=True, shell=False)
|
|
if result.returncode:
|
|
raise GateError(f"git {label} failed", result.returncode)
|
|
identity[label if label != "diff" else "diff_sha256"] = (result.stdout.strip() if label != "diff" else hashlib.sha256(result.stdout.encode()).hexdigest())
|
|
untracked = invoke(["git", "ls-files", "--others", "--exclude-standard", "-z"],
|
|
cwd=str(root), env=env, capture_output=True, text=True, shell=False)
|
|
if untracked.returncode:
|
|
raise GateError("git untracked identity failed", untracked.returncode)
|
|
identity["untracked_sha256"] = {
|
|
name: hashlib.sha256((root / name).read_bytes()).hexdigest()
|
|
for name in untracked.stdout.split("\0") if name and (root / name).is_file()
|
|
}
|
|
report["identity"] = identity
|
|
for index, item in enumerate(records):
|
|
target = directory / f'{index:02d}-{Path(item["project"]).stem}'
|
|
target.mkdir()
|
|
entry = {"project": item["project"], "filter": item["filter"],
|
|
"new_classes": item.get("new_classes", []), "existing_classes": item.get("existing_classes", [])}
|
|
report["projects"].append(entry)
|
|
tick = time.monotonic()
|
|
listing = command(item["project"], item["filter"], target, True)
|
|
entry["discovery_argv"] = listing
|
|
result, entry["discovery_seconds"] = child(listing, target, "discovery")
|
|
names = discover_names(result.stdout or "")
|
|
if case:
|
|
names = [name for name in names if class_matches(name, case)]
|
|
required_classes = item.get("new_classes", []) + item.get("existing_classes", [])
|
|
mapping = {name: [test for test in names if class_matches(test, name)] for name in required_classes}
|
|
write_json(target / "discovery.json", {
|
|
"filter": item["filter"], "tests": names,
|
|
"new_classes": {name: mapping[name] for name in item.get("new_classes", [])},
|
|
"existing_classes": {name: mapping[name] for name in item.get("existing_classes", [])},
|
|
})
|
|
if not names:
|
|
raise GateError(f"zero discovered tests for {item['project']}")
|
|
absent = [name for name, tests in mapping.items() if not tests]
|
|
if absent:
|
|
raise GateError(f"missing required classes: {', '.join(absent)}")
|
|
expression = item["filter"]
|
|
execution = command(item["project"], expression, target)
|
|
entry["execution_filter"] = expression
|
|
entry["execution_argv"] = execution
|
|
before = time.time_ns()
|
|
_, entry["execution_seconds"] = child(execution, target, "execution")
|
|
entry["trx"] = validate_trx(target, before, required_classes)
|
|
entry["duration_seconds"] = time.monotonic() - tick
|
|
report["status"] = "passed"
|
|
return directory
|
|
except (GateError, OSError) as exc:
|
|
report["status"] = "failed"
|
|
report["error"] = str(exc)
|
|
if isinstance(exc, GateError):
|
|
raise
|
|
raise GateError(str(exc)) from exc
|
|
finally:
|
|
report["duration_seconds"] = time.monotonic() - started
|
|
write_json(directory / "run.json", report)
|
|
print(f"Unit phase evidence: {directory}")
|
|
|
|
|
|
def main(argv=None):
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("phase")
|
|
parser.add_argument("--case", help="Exact manifest class name")
|
|
parser.add_argument("--dry-run", action="store_true")
|
|
args = parser.parse_args(argv)
|
|
root = Path(__file__).resolve().parents[3]
|
|
try:
|
|
manifest = json.loads(Path(__file__).with_name("unit-phases.json").read_text())
|
|
run_phase(manifest, args.phase, root, args.case, args.dry_run)
|
|
return 0
|
|
except (GateError, ValueError, KeyError, OSError) as exc:
|
|
print(f"Unit phase failed: {exc}", file=sys.stderr)
|
|
return exc.exit_code if isinstance(exc, GateError) else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|