test: add automated regression and mesh proxy coexistence suites
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
"""Validate native mesh/proxy coexistence measurements and compare medians."""
|
||||
import json
|
||||
import math
|
||||
from statistics import median
|
||||
|
||||
PHASES = (("mesh_only", "mesh"), ("proxy_only", "proxy"),
|
||||
("combined_idle_mesh", "mesh"), ("combined_idle_proxy", "proxy"),
|
||||
("concurrent", "mesh"), ("concurrent", "proxy"))
|
||||
FLAGS = ("mesh_survives_proxy_stop", "proxy_survives_mesh_stop",
|
||||
"no_mesh_to_proxy_fallback", "proxy_recovered", "ports_released")
|
||||
|
||||
|
||||
def positive(value):
|
||||
return type(value) in (int, float) and math.isfinite(value) and value > 0
|
||||
|
||||
|
||||
def parse(log, spec):
|
||||
flows, functional = [], []
|
||||
for line in log.splitlines():
|
||||
if not line.startswith("{"):
|
||||
continue
|
||||
record = json.loads(line)
|
||||
if record.get("mode") == "combined_flow":
|
||||
flows.append(record)
|
||||
elif record.get("mode") == "combined_functional":
|
||||
functional.append(record)
|
||||
expected = {(phase, lane, direction, repeat) for phase, lane in PHASES
|
||||
for direction in ("download", "upload") for repeat in range(1, spec["repeats"] + 1)}
|
||||
seen = set()
|
||||
for flow in flows:
|
||||
key = tuple(flow[k] for k in ("phase", "lane", "direction", "repeat"))
|
||||
if key not in expected or key in seen:
|
||||
raise ValueError("unexpected or duplicate joint sample: " + str(key))
|
||||
seen.add(key)
|
||||
if any(not positive(flow[k]) for k in ("bytes", "seconds", "mbps")):
|
||||
raise ValueError("invalid joint transfer measurement")
|
||||
if flow["seconds"] < spec["duration_seconds"] * .8:
|
||||
raise ValueError("joint transfer duration too short")
|
||||
if not math.isclose(flow["mbps"], flow["bytes"] * 8 / flow["seconds"] / 1e6, rel_tol=1e-6):
|
||||
raise ValueError("inconsistent joint transfer rate")
|
||||
overlap = flow["overlap_ms"]
|
||||
if type(overlap) not in (float, int) or not math.isfinite(overlap) or overlap < 0:
|
||||
raise ValueError("invalid joint overlap")
|
||||
if flow["phase"] == "concurrent" and not spec["duration_seconds"] * 800 <= overlap <= flow["seconds"] * 1000:
|
||||
raise ValueError("insufficient concurrent overlap")
|
||||
if seen != expected:
|
||||
raise ValueError(f"missing joint measurements: {len(expected - seen)}")
|
||||
if len(functional) != 1 or any(functional[0].get(key) is not True for key in FLAGS):
|
||||
raise ValueError("joint fault-isolation checks incomplete or failed")
|
||||
for key in ("repeats", "duration_seconds", "rtt_ms", "proxy_limit_mbps"):
|
||||
if functional[0].get(key) != spec[key]:
|
||||
raise ValueError("joint configuration mismatch: " + key)
|
||||
if functional[0].get("udp_probes_per_lane") != spec["repeats"] * 8:
|
||||
raise ValueError("missing UDP probes under concurrent TCP load")
|
||||
groups = []
|
||||
for direction in ("download", "upload"):
|
||||
for phase, lane in PHASES:
|
||||
rates = [f["mbps"] for f in flows if (f["phase"], f["lane"], f["direction"]) == (phase, lane, direction)]
|
||||
groups.append(dict(phase=phase, lane=lane, direction=direction, samples=len(rates),
|
||||
median_mbps=median(rates), min_mbps=min(rates), max_mbps=max(rates)))
|
||||
comparisons, issues = [], []
|
||||
for direction in ("download", "upload"):
|
||||
for lane in ("mesh", "proxy"):
|
||||
rates = {g["phase"]: g["median_mbps"] for g in groups if g["lane"] == lane and g["direction"] == direction}
|
||||
for label, before, after in (("enabled_idle", lane + "_only", "combined_idle_" + lane),
|
||||
("concurrent_vs_idle", "combined_idle_" + lane, "concurrent"),
|
||||
("concurrent_vs_only", lane + "_only", "concurrent")):
|
||||
change = (rates[after] / rates[before] - 1) * 100
|
||||
comparisons.append(dict(lane=lane, direction=direction, comparison=label, change_percent=change))
|
||||
if change < -spec["max_slowdown_percent"]:
|
||||
issues.append(f"{lane}/{direction}/{label}: {change:+.2f}% exceeds {spec['max_slowdown_percent']}% slowdown limit")
|
||||
return dict(measurements=flows, functional=functional[0], summary=groups, comparisons=comparisons, issues=issues)
|
||||
|
||||
|
||||
def markdown(result):
|
||||
lines = ["# Native mesh + sing-box coexistence", "",
|
||||
"Local upstream fixture; real Rust SDK and Go FFI in one process. No system TUN or WAN.", "",
|
||||
"| Phase | Lane | Direction | Samples | Median Mbps | Min | Max |",
|
||||
"|---|---|---|---:|---:|---:|---:|"]
|
||||
for g in result["summary"]:
|
||||
lines.append(f"| {g['phase']} | {g['lane']} | {g['direction']} | {g['samples']} | {g['median_mbps']:.2f} | {g['min_mbps']:.2f} | {g['max_mbps']:.2f} |")
|
||||
lines += ["", "| Lane | Direction | Comparison | Change |", "|---|---|---|---:|"]
|
||||
for c in result["comparisons"]:
|
||||
lines.append(f"| {c['lane']} | {c['direction']} | {c['comparison']} | {c['change_percent']:+.2f}% |")
|
||||
lines += ["", "Functional evidence: `" + json.dumps(result["functional"], sort_keys=True) + "`", ""]
|
||||
lines += result["issues"] or ["All configured joint criteria passed."]
|
||||
return "\n".join(lines) + "\n"
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Parse synthetic speed fixtures and evaluate explicit performance criteria."""
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import statistics
|
||||
|
||||
KEY_FIELDS = ("mode", "target", "entry", "rtt_ms", "mib", "direction")
|
||||
|
||||
|
||||
def positive_number(value):
|
||||
return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) and value > 0
|
||||
|
||||
|
||||
def key(record):
|
||||
return tuple(record[field] for field in KEY_FIELDS)
|
||||
|
||||
|
||||
def parse(text, spec):
|
||||
records = {}
|
||||
for line in text.replace("\r", "\n").splitlines():
|
||||
match = re.fullmatch(r"(sdk|subnet) entry=(sdk|socks|singbox) added_rtt_ms=(\d+) direction=(download|upload) mib=(\d+) mbps=([\d.eE+-]+)", line)
|
||||
if match and spec["mode"] == "mesh":
|
||||
target, entry, rtt, direction, mib, mbps = match.groups()
|
||||
record = dict(mode="mesh", target=target, entry=entry, rtt_ms=int(rtt), mib=int(mib), direction=direction, mbps=float(mbps))
|
||||
elif line.startswith("{"):
|
||||
try:
|
||||
value = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
if spec["mode"] == "mesh" and value.get("mode") == "easytier_encrypted_relay":
|
||||
identity = ("mesh", value["target"], value["entry"], spec["rtt_ms"], spec["mib"], value["direction"])
|
||||
if identity not in records or "wire" in records[identity]:
|
||||
raise ValueError("missing or duplicate throughput sample for wire observation")
|
||||
records[identity]["wire"] = value
|
||||
continue
|
||||
if value.get("mode") != spec["mode"] or spec["mode"] not in ("channel", "udp"):
|
||||
continue
|
||||
record = dict(mode=value["mode"], target="stack", entry="direct", rtt_ms=value["added_rtt_ms"],
|
||||
mib=value["mib"], direction=value["direction"], mbps=value["mbps"], wire=value)
|
||||
else:
|
||||
continue
|
||||
if not positive_number(record["mbps"]):
|
||||
raise ValueError("speed must be finite and greater than zero")
|
||||
if record["rtt_ms"] != spec["rtt_ms"] or record["mib"] != spec["mib"]:
|
||||
raise ValueError("fixture RTT/data size differs from requested parameters")
|
||||
identity = key(record)
|
||||
if identity in records:
|
||||
raise ValueError("duplicate speed sample")
|
||||
record["repeat"] = spec.get("repeat", 1)
|
||||
records[identity] = record
|
||||
expected = {(spec["mode"], spec["target"], entry, spec["rtt_ms"], spec["mib"], direction)
|
||||
for entry in spec["entries"] for direction in ("download", "upload")}
|
||||
if set(records) != expected:
|
||||
raise ValueError("missing/unexpected speed samples; both upload and download are required for every path")
|
||||
for record in records.values():
|
||||
wire = record.get("wire")
|
||||
if wire is None:
|
||||
raise ValueError("missing packet-level observation")
|
||||
if record["mode"] == "mesh":
|
||||
drops = wire.get("udp_session_queue_full_drops")
|
||||
if not isinstance(drops, int) or isinstance(drops, bool) or drops < 0:
|
||||
raise ValueError("missing/invalid UDP session queue-drop count")
|
||||
record["queue_drops"] = drops
|
||||
sender = wire.get("server_wire_at_relay" if record["direction"] == "download" else "client_wire_at_relay", {})
|
||||
else:
|
||||
sender = wire.get("server_wire" if record["direction"] == "download" else "client_wire", {})
|
||||
for field in ("data_packets", "repeated_sequences", "max_data_gap_ms"):
|
||||
number = sender.get(field)
|
||||
if not isinstance(number, int) or isinstance(number, bool) or number < 0:
|
||||
raise ValueError("missing/invalid wire statistic: " + field)
|
||||
if sender["data_packets"] == 0:
|
||||
raise ValueError("no TCP data packets observed")
|
||||
record["repeated_sequences"] = sender["repeated_sequences"]
|
||||
record["max_data_gap_ms"] = sender["max_data_gap_ms"]
|
||||
return list(records.values())
|
||||
|
||||
|
||||
def summarize(results):
|
||||
groups = {}
|
||||
for result in results:
|
||||
for record in result.get("measurements", []):
|
||||
groups.setdefault(key(record), []).append(record)
|
||||
summary = []
|
||||
for identity, records in sorted(groups.items()):
|
||||
speeds = [record["mbps"] for record in records]
|
||||
item = dict(zip(KEY_FIELDS, identity))
|
||||
item.update(samples=len(records), median_mbps=statistics.median(speeds), min_mbps=min(speeds), max_mbps=max(speeds),
|
||||
repeated_sequences=sum(r["repeated_sequences"] for r in records),
|
||||
max_data_gap_ms=max(r["max_data_gap_ms"] for r in records))
|
||||
if identity[0] == "mesh":
|
||||
item["queue_drops"] = sum(r["queue_drops"] for r in records)
|
||||
summary.append(item)
|
||||
return summary
|
||||
|
||||
|
||||
def validate_baseline(value):
|
||||
if not isinstance(value, dict) or not isinstance(value.get("summary"), list) or not value["summary"]:
|
||||
raise ValueError("baseline must be a metrics.json with a nonempty summary")
|
||||
seen = set()
|
||||
for item in value["summary"]:
|
||||
try:
|
||||
identity = key(item)
|
||||
except (KeyError, TypeError) as error:
|
||||
raise ValueError("baseline is missing measurement identity fields") from error
|
||||
if any(not isinstance(item[field], str) or not item[field] for field in ("mode", "target", "entry", "direction")):
|
||||
raise ValueError("baseline path fields must be nonempty strings")
|
||||
if item["direction"] not in ("download", "upload") or any(not isinstance(item[field], int) or isinstance(item[field], bool) for field in ("rtt_ms", "mib")):
|
||||
raise ValueError("baseline direction/RTT/size is invalid")
|
||||
if identity in seen or not positive_number(item.get("median_mbps")):
|
||||
raise ValueError("baseline contains duplicate groups or invalid speed")
|
||||
seen.add(identity)
|
||||
return value["summary"]
|
||||
|
||||
|
||||
def evaluate(summary, policy):
|
||||
issues = []
|
||||
if not summary:
|
||||
return ["no performance measurements"]
|
||||
for item in summary:
|
||||
label = "/".join(str(v) for v in key(item))
|
||||
if item["samples"] != policy["repeats"]:
|
||||
issues.append(label + ": incomplete repeat count")
|
||||
if item["median_mbps"] < policy["min_mbps"]:
|
||||
issues.append(f"{label}: median {item['median_mbps']:.2f} Mbps below {policy['min_mbps']:.2f}")
|
||||
if item.get("queue_drops", 0) > policy["max_queue_drops"]:
|
||||
issues.append(f"{label}: {item['queue_drops']} queue drops exceed {policy['max_queue_drops']}")
|
||||
baseline = policy.get("baseline")
|
||||
if baseline is not None:
|
||||
before = {key(item): item for item in baseline}
|
||||
after = {key(item): item for item in summary}
|
||||
if set(before) != set(after):
|
||||
issues.append("baseline groups differ (mode, target, entry, RTT, size or direction); comparison refused")
|
||||
else:
|
||||
for identity, item in after.items():
|
||||
floor = before[identity]["median_mbps"] * (1 - policy["max_regression_percent"] / 100)
|
||||
if item["median_mbps"] < floor:
|
||||
issues.append(f"{identity}: median {item['median_mbps']:.2f} Mbps exceeds allowed baseline regression")
|
||||
return issues
|
||||
Executable
+350
@@ -0,0 +1,350 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run MeshPort's local regression suites and write CI-friendly reports."""
|
||||
import argparse
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
import xml.etree.ElementTree as ET
|
||||
import performance
|
||||
import coexistence
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
SUITES = ("all", "runner", "sdk", "engine", "client", "macos", "throughput", "speed", "combined")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Step:
|
||||
name: str
|
||||
command: list
|
||||
cwd: Path = ROOT
|
||||
requires: tuple = ()
|
||||
env: dict = field(default_factory=dict)
|
||||
skip: str = ""
|
||||
measurement: dict = field(default_factory=dict)
|
||||
checks: dict = field(default_factory=dict)
|
||||
|
||||
|
||||
def plan(suites, native=False, rtt_ms=58, mib=8, platform=sys.platform, rtts=(0, 58, 100), repeats=3, policy=None, joint=None):
|
||||
selected = set(suites)
|
||||
if "all" in selected:
|
||||
selected.update(("runner", "sdk", "engine", "client", "macos"))
|
||||
steps = []
|
||||
cargo = ["sh", "scripts/cargo-local.sh"]
|
||||
go = ["sh", "scripts/go-local.sh"]
|
||||
if "runner" in selected:
|
||||
steps.append(Step("runner-tests", [sys.executable, "-m", "unittest", "discover", "-s", "scripts/tests", "-p", "*_test.py"]))
|
||||
if "sdk" in selected:
|
||||
steps.append(Step("sdk", cargo + ["test", "--workspace", "--release", "--locked"]))
|
||||
if "engine" in selected:
|
||||
steps.extend([
|
||||
Step("go-race", go + ["test", "-race", "./..."]),
|
||||
Step("go-vet", go + ["vet", "./..."]),
|
||||
Step("go-bridge-build", ["sh", "scripts/build-singbox.sh"]),
|
||||
Step("go-sdk-bridge", cargo + ["test", "-p", "meshport-socks", "--release", "--locked",
|
||||
"--test", "bridge", "singbox_to_meshport_tcp_udp_and_withdrawal", "--", "--ignored"],
|
||||
requires=("go-bridge-build",),
|
||||
env={"MESHPORT_SINGBOX_BIN": str(ROOT / "target/debug/meshport-singbox")}),
|
||||
])
|
||||
if "client" in selected:
|
||||
app = ROOT / "apps/meshport_lab"
|
||||
steps.extend([
|
||||
Step("flutter-dependencies", ["flutter", "pub", "get"], cwd=app),
|
||||
Step("flutter-analyze", ["flutter", "analyze"], cwd=app, requires=("flutter-dependencies",)),
|
||||
])
|
||||
dependencies = ("flutter-dependencies",)
|
||||
env = {}
|
||||
if native:
|
||||
if platform != "darwin":
|
||||
raise ValueError("--native currently requires macOS (the native build script targets macOS)")
|
||||
steps.extend([
|
||||
Step("client-rust-library", cargo + ["build", "-p", "meshport-ffi", "--locked"]),
|
||||
Step("client-go-library", ["sh", "scripts/build-singbox-library.sh", "macos"]),
|
||||
])
|
||||
dependencies += ("client-rust-library", "client-go-library")
|
||||
env = {
|
||||
"MESHPORT_LIBRARY": str(ROOT / "target/debug/libmeshport_ffi.dylib"),
|
||||
"MESHPORT_PROXY_LIBRARY": str(ROOT / "target/debug/libmeshport_proxy.dylib"),
|
||||
}
|
||||
steps.append(Step("flutter-tests", ["flutter", "test"], cwd=app, requires=dependencies, env=env))
|
||||
if "macos" in selected:
|
||||
steps.append(Step("macos-profile-storage", ["sh", "scripts/test-macos-profile-storage.sh"],
|
||||
skip="requires macOS and Xcode command-line tools" if platform != "darwin" else ""))
|
||||
if "throughput" in selected and "speed" not in selected:
|
||||
common = {"MESHPORT_TEST_DELAY_MS": str(rtt_ms // 2), "MESHPORT_TEST_MIB": str(mib)}
|
||||
for mode in ("channel", "udp"):
|
||||
steps.append(Step("tcp-stack-" + mode, cargo + ["test", "-p", "meshport-socks", "--release",
|
||||
"--locked", "--test", "tcp_stack_diagnostic", "sdk_tcp_stack_diagnostic",
|
||||
"--", "--ignored", "--nocapture"], env={**common, "MESHPORT_TEST_LINK": mode},
|
||||
measurement=dict(mode=mode, target="stack", entries=["direct"], rtt_ms=rtt_ms, mib=mib)))
|
||||
steps.append(Step("sdk-throughput", cargo + ["test", "-p", "meshport-socks", "--release", "--locked",
|
||||
"--test", "bridge", "subnet_throughput_diagnostic", "--", "--ignored", "--nocapture"],
|
||||
env={**common, "MESHPORT_TEST_TARGET": "sdk", "MESHPORT_TEST_ENTRIES": "sdk",
|
||||
"MESHPORT_TEST_TRACE_TCP": "1"},
|
||||
measurement=dict(mode="mesh", target="sdk", entries=["sdk"], rtt_ms=rtt_ms, mib=mib)))
|
||||
if "speed" in selected:
|
||||
build = "go-bridge-build" if "engine" in selected else "speed-engine-build"
|
||||
if "engine" not in selected:
|
||||
steps.append(Step(build, ["sh", "scripts/build-singbox.sh"]))
|
||||
measured = []
|
||||
for rtt in rtts:
|
||||
for repeat in range(1, repeats + 1):
|
||||
common = {"MESHPORT_TEST_DELAY_MS": str(rtt // 2), "MESHPORT_TEST_MIB": str(mib)}
|
||||
for mode in ("channel", "udp", "mesh"):
|
||||
name = f"speed-{mode}-{rtt}ms-{repeat}"
|
||||
measured.append(name)
|
||||
spec = dict(mode=mode, target="sdk" if mode == "mesh" else "stack",
|
||||
entries=["sdk", "socks", "singbox"] if mode == "mesh" else ["direct"],
|
||||
rtt_ms=rtt, mib=mib, repeat=repeat)
|
||||
if mode == "mesh":
|
||||
command = cargo + ["test", "-p", "meshport-socks", "--release", "--locked", "--test", "bridge",
|
||||
"subnet_throughput_diagnostic", "--", "--ignored", "--nocapture"]
|
||||
env = {**common, "MESHPORT_TEST_TARGET": "sdk", "MESHPORT_TEST_ENTRIES": "sdk,socks,singbox",
|
||||
"MESHPORT_TEST_TRACE_TCP": "1", "MESHPORT_SINGBOX_BIN": str(ROOT / "target/debug/meshport-singbox")}
|
||||
requires = (build,)
|
||||
else:
|
||||
command = cargo + ["test", "-p", "meshport-socks", "--release", "--locked", "--test", "tcp_stack_diagnostic",
|
||||
"sdk_tcp_stack_diagnostic", "--", "--ignored", "--nocapture"]
|
||||
env = {**common, "MESHPORT_TEST_LINK": mode}
|
||||
requires = ()
|
||||
steps.append(Step(name, command, requires=requires, env=env, measurement=spec))
|
||||
steps.append(Step("speed-check", [], requires=tuple(measured), checks=policy or
|
||||
dict(repeats=repeats, min_mbps=0, max_queue_drops=0, baseline=None, max_regression_percent=20)))
|
||||
if "combined" in selected:
|
||||
if platform != "darwin":
|
||||
raise ValueError("combined currently requires macOS (native Go shared library build)")
|
||||
build = "client-go-library" if "client" in selected and native else "combined-go-library"
|
||||
if build == "combined-go-library":
|
||||
steps.append(Step(build, ["sh", "scripts/build-singbox-library.sh", "macos"]))
|
||||
spec = joint or dict(duration_seconds=2, repeats=3, proxy_limit_mbps=100, max_slowdown_percent=20)
|
||||
spec = {**spec, "rtt_ms": rtt_ms, "mode": "combined"}
|
||||
steps.append(Step("combined-coexistence", cargo + ["test", "-p", "meshport-socks", "--release", "--locked",
|
||||
"--test", "combined", "combined_coexistence", "--", "--ignored", "--nocapture"],
|
||||
requires=(build,), measurement=spec,
|
||||
env={"MESHPORT_PROXY_LIBRARY": str(ROOT / "target/debug/libmeshport_proxy.dylib"),
|
||||
"MESHPORT_TEST_DELAY_MS": str(rtt_ms // 2),
|
||||
"MESHPORT_JOINT_SECONDS": str(spec["duration_seconds"]),
|
||||
"MESHPORT_JOINT_REPEATS": str(spec["repeats"]),
|
||||
"MESHPORT_JOINT_PROXY_MBPS": str(spec["proxy_limit_mbps"])}))
|
||||
return steps
|
||||
|
||||
|
||||
def test_environment(overrides):
|
||||
# Do not inherit user profiles, drain fixtures, old native libraries or
|
||||
# diagnostic knobs. Every optional native/diagnostic input is set explicitly.
|
||||
return {**{key: value for key, value in os.environ.items() if not key.startswith("MESHPORT_")}, **overrides}
|
||||
|
||||
|
||||
def stop_process(process):
|
||||
if process.poll() is not None:
|
||||
return
|
||||
try:
|
||||
if os.name == "posix":
|
||||
os.killpg(process.pid, signal.SIGTERM)
|
||||
else:
|
||||
process.terminate()
|
||||
except ProcessLookupError:
|
||||
return
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
if os.name == "posix":
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
else:
|
||||
process.kill()
|
||||
process.wait()
|
||||
|
||||
|
||||
def execute(step, directory, timeout):
|
||||
log = directory / (step.name + ".log")
|
||||
start = time.monotonic()
|
||||
result = {"name": step.name, "command": step.command, "cwd": str(step.cwd), "log": str(log)}
|
||||
print("RUN " + step.name + " " + shlex.join(step.command), flush=True)
|
||||
process = None
|
||||
try:
|
||||
with log.open("w", encoding="utf-8") as output:
|
||||
process = subprocess.Popen(step.command, cwd=step.cwd, env=test_environment(step.env),
|
||||
stdout=output, stderr=subprocess.STDOUT, start_new_session=os.name == "posix")
|
||||
try:
|
||||
code = process.wait(timeout=timeout)
|
||||
result.update(status="passed" if code == 0 else "failed", exit_code=code)
|
||||
except subprocess.TimeoutExpired:
|
||||
stop_process(process)
|
||||
result.update(status="failed", exit_code=124, reason=f"timeout after {timeout} seconds")
|
||||
except KeyboardInterrupt:
|
||||
stop_process(process)
|
||||
result.update(status="failed", exit_code=130, reason="interrupted")
|
||||
except OSError as error:
|
||||
log.write_text(str(error) + "\n", encoding="utf-8")
|
||||
result.update(status="failed", exit_code=127, reason=str(error))
|
||||
result["seconds"] = round(time.monotonic() - start, 3)
|
||||
if step.measurement and result["status"] == "passed":
|
||||
try:
|
||||
content = log.read_text(encoding="utf-8", errors="replace")
|
||||
if step.measurement.get("mode") == "combined":
|
||||
result["joint_results"] = coexistence.parse(content, step.measurement)
|
||||
if result["joint_results"]["issues"]:
|
||||
result.update(status="failed", command_exit_code=0, exit_code=1,
|
||||
reason="; ".join(result["joint_results"]["issues"]))
|
||||
else:
|
||||
result["measurements"] = performance.parse(content, step.measurement)
|
||||
except (ValueError, KeyError, TypeError) as error:
|
||||
result.update(status="failed", command_exit_code=0, exit_code=1, reason="invalid speed result: " + str(error))
|
||||
print(("PASS " if result["status"] == "passed" else "FAIL ") + step.name + f" ({result['seconds']:.1f}s)", flush=True)
|
||||
if result["status"] == "failed":
|
||||
if "reason" in result:
|
||||
print(result["reason"], flush=True)
|
||||
print("\n".join(log.read_text(encoding="utf-8", errors="replace").splitlines()[-20:]), flush=True)
|
||||
return result
|
||||
|
||||
|
||||
def run(steps, directory, timeout=900, fail_fast=False):
|
||||
directory.mkdir(parents=True, exist_ok=False)
|
||||
results = []
|
||||
stopped = False
|
||||
for step in steps:
|
||||
previous = {result["name"]: result["status"] for result in results}
|
||||
blocked = [name for name in step.requires if previous.get(name) != "passed"]
|
||||
reason = step.skip or ("run stopped after failure" if stopped else "")
|
||||
if not reason and blocked:
|
||||
reason = "prerequisite did not pass: " + ", ".join(blocked)
|
||||
if reason:
|
||||
results.append({"name": step.name, "status": "skipped", "reason": reason, "seconds": 0})
|
||||
print("SKIP " + step.name + " " + reason, flush=True)
|
||||
continue
|
||||
if step.checks:
|
||||
issues = performance.evaluate(performance.summarize(results), step.checks)
|
||||
log = directory / (step.name + ".log")
|
||||
log.write_text("\n".join(issues) + "\n" if issues else "All configured speed criteria passed.\n", encoding="utf-8")
|
||||
result = dict(name=step.name, status="failed" if issues else "passed", exit_code=1 if issues else 0,
|
||||
seconds=0, log=str(log), criteria=step.checks)
|
||||
if issues:
|
||||
result["reason"] = "; ".join(issues)
|
||||
print(("FAIL " if issues else "PASS ") + step.name, flush=True)
|
||||
for issue in issues:
|
||||
print(issue, flush=True)
|
||||
else:
|
||||
result = execute(step, directory, timeout)
|
||||
results.append(result)
|
||||
stopped = stopped or result.get("exit_code") == 130 or (fail_fast and result["status"] == "failed")
|
||||
write_reports(results, directory)
|
||||
write_reports(results, directory)
|
||||
return results
|
||||
|
||||
|
||||
def write_reports(results, directory):
|
||||
for result in results:
|
||||
if "joint_results" in result:
|
||||
(directory / "combined-metrics.json").write_text(json.dumps(result["joint_results"], indent=2) + "\n", encoding="utf-8")
|
||||
(directory / "combined-summary.md").write_text(coexistence.markdown(result["joint_results"]), encoding="utf-8")
|
||||
measurements = [record for result in results for record in result.get("measurements", [])]
|
||||
if measurements:
|
||||
summary = performance.summarize(results)
|
||||
(directory / "metrics.json").write_text(json.dumps(dict(measurements=measurements, summary=summary), ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
table = ["# Local synthetic speed results", "", "RTT is added round-trip delay; these are local fixtures, not WAN speed measurements.", "",
|
||||
"| Path | RTT ms | MiB/direction | Direction | Samples | Median Mbps | Min | Max | Queue drops |",
|
||||
"|---|---:|---:|---|---:|---:|---:|---:|---:|"]
|
||||
for item in summary:
|
||||
path = item["mode"] + "/" + item["target"] + "/" + item["entry"]
|
||||
table.append(f"| {path} | {item['rtt_ms']} | {item['mib']} | {item['direction']} | {item['samples']} | {item['median_mbps']:.2f} | {item['min_mbps']:.2f} | {item['max_mbps']:.2f} | {item.get('queue_drops', 'n/a')} |")
|
||||
(directory / "speed-summary.md").write_text("\n".join(table) + "\n", encoding="utf-8")
|
||||
(directory / "report.json").write_text(json.dumps({"steps": results}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
suite = ET.Element("testsuite", name="meshport", tests=str(len(results)),
|
||||
failures=str(sum(r["status"] == "failed" for r in results)),
|
||||
skipped=str(sum(r["status"] == "skipped" for r in results)))
|
||||
for result in results:
|
||||
case = ET.SubElement(suite, "testcase", name=result["name"], classname="meshport.automation", time=str(result["seconds"]))
|
||||
if result["status"] == "skipped":
|
||||
ET.SubElement(case, "skipped", message=result["reason"])
|
||||
elif result["status"] == "failed":
|
||||
ET.SubElement(case, "failure", message=result.get("reason", f"exit code {result['exit_code']}"))
|
||||
if "log" in result:
|
||||
ET.SubElement(case, "system-out").text = result["log"]
|
||||
ET.ElementTree(suite).write(directory / "junit.xml", encoding="utf-8", xml_declaration=True)
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("suites", nargs="*", metavar="SUITE", help=", ".join(SUITES) + " (default: all)")
|
||||
parser.add_argument("--native", action="store_true", help="build macOS native libraries for Flutter tests")
|
||||
parser.add_argument("--list", action="store_true", help="print commands without running them")
|
||||
parser.add_argument("--fail-fast", action="store_true")
|
||||
parser.add_argument("--timeout", type=int, default=900, help="timeout per command in seconds (default: 900)")
|
||||
parser.add_argument("--rtt-ms", type=int, default=58, help="even simulated RTT, 0..1000, for throughput/combined")
|
||||
parser.add_argument("--joint-seconds", type=int, default=2, help="combined duration per flow, 1..5")
|
||||
parser.add_argument("--joint-repeat", type=int, default=3, help="combined repeats, 1..10")
|
||||
parser.add_argument("--proxy-mbps", type=int, default=100, help="combined proxy fixture limit; 0 means unlimited")
|
||||
parser.add_argument("--max-joint-slowdown-percent", type=float, default=20, help="maximum median slowdown between combined phases")
|
||||
parser.add_argument("--mib", type=int, default=8, help="data per direction in MiB, 1..64, for throughput/speed")
|
||||
parser.add_argument("--rtts-ms", default="0,58,100", help="comma-separated even RTTs for speed matrix")
|
||||
parser.add_argument("--repeat", type=int, default=3, help="speed matrix repeats per RTT, 1..10")
|
||||
parser.add_argument("--min-mbps", type=float, default=0, help="minimum group median for speed checks; default: no absolute floor")
|
||||
parser.add_argument("--max-queue-drops", type=int, default=0, help="maximum queue drops per speed group across repeats")
|
||||
parser.add_argument("--baseline", type=Path, help="previous metrics.json for matching speed groups")
|
||||
parser.add_argument("--max-regression-percent", type=float, default=20, help="maximum median drop from baseline")
|
||||
parser.add_argument("--log-dir", type=Path, help="new report directory; must not already exist")
|
||||
args = parser.parse_args(argv)
|
||||
args.suites = args.suites or ["all"]
|
||||
if set(args.suites) - set(SUITES):
|
||||
parser.error("unknown suite; choose from: " + ", ".join(SUITES))
|
||||
if args.native and not set(args.suites).intersection({"all", "client"}):
|
||||
parser.error("--native requires the client or all suite")
|
||||
if args.timeout <= 0 or not 0 <= args.rtt_ms <= 1000 or args.rtt_ms % 2 or not 1 <= args.mib <= 64:
|
||||
parser.error("timeout must be positive; RTT must be even and 0..1000; MiB must be 1..64")
|
||||
try:
|
||||
import math
|
||||
if not 1 <= args.joint_seconds <= 5 or not 1 <= args.joint_repeat <= 10 or not 0 <= args.proxy_mbps <= 100000:
|
||||
raise ValueError("joint seconds must be 1..5, repeats 1..10, proxy Mbps 0..100000")
|
||||
if not math.isfinite(args.max_joint_slowdown_percent) or not 0 <= args.max_joint_slowdown_percent < 100:
|
||||
raise ValueError("joint slowdown percent must be finite and in 0..<100")
|
||||
if "combined" not in args.suites and (args.joint_seconds != 2 or args.joint_repeat != 3 or args.proxy_mbps != 100 or args.max_joint_slowdown_percent != 20):
|
||||
raise ValueError("joint options require the combined suite")
|
||||
rtts = tuple(int(value) for value in args.rtts_ms.split(","))
|
||||
if not rtts or len(set(rtts)) != len(rtts) or any(not 0 <= value <= 1000 or value % 2 for value in rtts):
|
||||
raise ValueError("speed RTTs must be distinct even integers in 0..1000")
|
||||
if not 1 <= args.repeat <= 10 or not math.isfinite(args.min_mbps) or args.min_mbps < 0 or args.max_queue_drops < 0:
|
||||
raise ValueError("repeat must be 1..10; speed and queue-drop limits must be nonnegative and finite")
|
||||
if not math.isfinite(args.max_regression_percent) or not 0 <= args.max_regression_percent < 100:
|
||||
raise ValueError("maximum regression percent must be finite and in 0..<100")
|
||||
if "speed" not in args.suites and (args.min_mbps != 0 or args.max_queue_drops != 0 or args.repeat != 3 or
|
||||
args.rtts_ms != "0,58,100" or args.max_regression_percent != 20):
|
||||
raise ValueError("matrix/gate options require the speed suite")
|
||||
if args.baseline and "speed" not in args.suites:
|
||||
raise ValueError("--baseline requires the speed suite")
|
||||
baseline = performance.validate_baseline(json.loads(args.baseline.read_text())) if args.baseline else None
|
||||
policy = dict(repeats=args.repeat, min_mbps=args.min_mbps, max_queue_drops=args.max_queue_drops,
|
||||
baseline=baseline, max_regression_percent=args.max_regression_percent)
|
||||
joint = dict(duration_seconds=args.joint_seconds, repeats=args.joint_repeat,
|
||||
proxy_limit_mbps=args.proxy_mbps, max_slowdown_percent=args.max_joint_slowdown_percent)
|
||||
steps = plan(args.suites, args.native, args.rtt_ms, args.mib, rtts=rtts, repeats=args.repeat, policy=policy, joint=joint)
|
||||
except (OSError, json.JSONDecodeError) as error:
|
||||
parser.error("cannot read baseline: " + str(error))
|
||||
except ValueError as error:
|
||||
parser.error(str(error))
|
||||
if args.list:
|
||||
for step in steps:
|
||||
print(step.name + ": " + ("SKIP " + step.skip if step.skip else shlex.join(step.command) if step.command else "evaluate medians, drop counts and optional baseline"))
|
||||
return 0
|
||||
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||
directory = (args.log_dir or ROOT / "outputs/validation/automated-tests" / (stamp + "-" + uuid.uuid4().hex[:8])).resolve()
|
||||
if directory.exists():
|
||||
parser.error("report directory already exists: " + str(directory))
|
||||
print("Reports: " + str(directory), flush=True)
|
||||
results = run(steps, directory, args.timeout, args.fail_fast)
|
||||
counts = {state: sum(r["status"] == state for r in results) for state in ("passed", "failed", "skipped")}
|
||||
print("Summary: " + ", ".join(f"{number} {state}" for state, number in counts.items()), flush=True)
|
||||
print("Report: " + str(directory / "report.json"), flush=True)
|
||||
if any(r.get("exit_code") == 130 for r in results):
|
||||
return 130
|
||||
return 1 if counts["failed"] else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,93 @@
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
import coexistence
|
||||
import test as runner
|
||||
|
||||
SPEC = dict(mode="combined", duration_seconds=2, repeats=3, proxy_limit_mbps=100,
|
||||
rtt_ms=58, max_slowdown_percent=20)
|
||||
|
||||
|
||||
def fixture(concurrent=1):
|
||||
flows = []
|
||||
for phase, lane in coexistence.PHASES:
|
||||
for direction in ("download", "upload"):
|
||||
for repeat in range(1, 4):
|
||||
rate = (60 if lane == "mesh" else 100) * (concurrent if phase == "concurrent" else 1)
|
||||
flows.append(dict(mode="combined_flow", phase=phase, lane=lane, direction=direction,
|
||||
repeat=repeat, bytes=rate * 1e6 / 8 * 2, seconds=2, mbps=rate,
|
||||
overlap_ms=1900 if phase == "concurrent" else 0))
|
||||
functional = dict(mode="combined_functional", **{k: True for k in coexistence.FLAGS},
|
||||
repeats=3, duration_seconds=2, rtt_ms=58, proxy_limit_mbps=100, udp_probes_per_lane=24)
|
||||
return flows + [functional]
|
||||
|
||||
|
||||
def log(records):
|
||||
return "\n".join(json.dumps(r) for r in records)
|
||||
|
||||
|
||||
class CoexistenceTest(unittest.TestCase):
|
||||
def test_complete_results_and_comparisons(self):
|
||||
result = coexistence.parse(log(fixture()), SPEC)
|
||||
self.assertEqual(len(result["measurements"]), 36)
|
||||
self.assertEqual(len(result["summary"]), 12)
|
||||
self.assertEqual(len(result["comparisons"]), 12)
|
||||
self.assertEqual(result["issues"], [])
|
||||
self.assertIn("concurrent_vs_idle", coexistence.markdown(result))
|
||||
|
||||
def test_rejects_missing_duplicate_and_unfinished_results(self):
|
||||
records = fixture()
|
||||
for bad in (records[:-1], records[1:], records + [records[0]], []):
|
||||
with self.subTest(count=len(bad)), self.assertRaises(ValueError):
|
||||
coexistence.parse(log(bad), SPEC)
|
||||
|
||||
def test_rejects_bad_duration_rate_overlap_and_nonfinite_values(self):
|
||||
for replacement in (dict(seconds=.1), dict(mbps=0), dict(bytes=float("nan")),
|
||||
dict(mbps=99), dict(overlap_ms=-1)):
|
||||
records = fixture()
|
||||
records[0].update(replacement)
|
||||
with self.subTest(replacement=replacement), self.assertRaises(ValueError):
|
||||
coexistence.parse(log(records), SPEC)
|
||||
records = fixture()
|
||||
next(r for r in records if r.get("phase") == "concurrent")["overlap_ms"] = 100
|
||||
with self.assertRaises(ValueError):
|
||||
coexistence.parse(log(records), SPEC)
|
||||
|
||||
def test_requires_fault_checks_config_and_concurrent_udp_evidence(self):
|
||||
for replacement in (dict(mesh_survives_proxy_stop=False), dict(proxy_survives_mesh_stop=1),
|
||||
dict(repeats=1), dict(udp_probes_per_lane=1), dict(rtt_ms=0)):
|
||||
records = fixture()
|
||||
records[-1].update(replacement)
|
||||
with self.subTest(replacement=replacement), self.assertRaises(ValueError):
|
||||
coexistence.parse(log(records), SPEC)
|
||||
|
||||
def test_slowdown_fails_command_and_preserves_measurements(self):
|
||||
step = runner.Step("joint", [sys.executable, "-c", "print(" + repr(log(fixture(.5))) + ")"], measurement=SPEC)
|
||||
with tempfile.TemporaryDirectory() as temporary, contextlib.redirect_stdout(io.StringIO()):
|
||||
directory = Path(temporary) / "run"
|
||||
results = runner.run([step], directory)
|
||||
self.assertEqual(results[0]["status"], "failed")
|
||||
self.assertIn("slowdown", results[0]["reason"])
|
||||
self.assertTrue((directory / "combined-summary.md").exists())
|
||||
self.assertEqual(len(json.loads((directory / "combined-metrics.json").read_text())["measurements"]), 36)
|
||||
|
||||
def test_plan_reuses_native_build_and_rejects_unsupported_platform(self):
|
||||
steps = runner.plan(["all", "combined"], native=True, platform="darwin")
|
||||
combined = steps[-1]
|
||||
self.assertEqual(combined.requires, ("client-go-library",))
|
||||
self.assertEqual(combined.env["MESHPORT_JOINT_REPEATS"], "3")
|
||||
self.assertNotIn("combined-go-library", [s.name for s in steps])
|
||||
with self.assertRaises(ValueError):
|
||||
runner.plan(["combined"], platform="linux")
|
||||
with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
|
||||
runner.main(["all", "--proxy-mbps", "0", "--list"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,103 @@
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
import performance
|
||||
import test as runner
|
||||
|
||||
|
||||
def fixture(speed=20, drops=0, entries=("sdk",)):
|
||||
lines = []
|
||||
for entry in entries:
|
||||
for direction in ("download", "upload"):
|
||||
lines.append(f"sdk entry={entry} added_rtt_ms=58 direction={direction} mib=8 mbps={speed}")
|
||||
wire = dict(data_packets=100, repeated_sequences=2, max_data_gap_ms=60)
|
||||
lines.append(json.dumps(dict(mode="easytier_encrypted_relay", target="sdk", entry=entry, direction=direction,
|
||||
client_wire_at_relay=wire, server_wire_at_relay=wire, udp_session_queue_full_drops=drops)))
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
SPEC = dict(mode="mesh", target="sdk", entries=["sdk"], rtt_ms=58, mib=8)
|
||||
|
||||
|
||||
class PerformanceTest(unittest.TestCase):
|
||||
def test_extracts_each_path_and_both_directions(self):
|
||||
entries = ["sdk", "socks", "singbox"]
|
||||
records = performance.parse(fixture(entries=entries), {**SPEC, "entries": entries})
|
||||
self.assertEqual(len(records), 6)
|
||||
self.assertEqual({r["entry"] for r in records}, set(entries))
|
||||
self.assertTrue(all(r["repeated_sequences"] == 2 and r["queue_drops"] == 0 for r in records))
|
||||
|
||||
def test_rejects_missing_duplicate_mismatched_and_zero_results(self):
|
||||
good = fixture()
|
||||
invalid = ["", "\n".join(good.splitlines()[:2]), good + "\n" + good,
|
||||
good.replace("added_rtt_ms=58", "added_rtt_ms=100"), fixture(speed=0),
|
||||
"\n".join(line for line in good.splitlines() if not line.startswith("{"))]
|
||||
for text in invalid:
|
||||
with self.subTest(text=text[:80]), self.assertRaises(ValueError):
|
||||
performance.parse(text, SPEC)
|
||||
|
||||
def test_checks_group_median_drops_and_baseline(self):
|
||||
results = [dict(measurements=performance.parse(fixture(speed=v), SPEC)) for v in (10, 20, 90)]
|
||||
summary = performance.summarize(results)
|
||||
self.assertTrue(all(item["median_mbps"] == 20 and item["samples"] == 3 for item in summary))
|
||||
policy = dict(repeats=3, min_mbps=15, max_queue_drops=0, baseline=None, max_regression_percent=20)
|
||||
self.assertEqual(performance.evaluate(summary, policy), [])
|
||||
self.assertTrue(performance.evaluate(summary, {**policy, "min_mbps": 25}))
|
||||
with_drops = [{**item, "queue_drops": 1} for item in summary]
|
||||
self.assertTrue(performance.evaluate(with_drops, policy))
|
||||
baseline = [{**item, "median_mbps": 30} for item in summary]
|
||||
self.assertTrue(performance.evaluate(summary, {**policy, "baseline": baseline}))
|
||||
mismatch = [{**item, "mib": 2} for item in baseline]
|
||||
self.assertIn("comparison refused", " ".join(performance.evaluate(summary, {**policy, "baseline": mismatch})))
|
||||
|
||||
def test_validates_baseline_and_finite_values(self):
|
||||
records = performance.parse(fixture(), SPEC)
|
||||
summary = performance.summarize([dict(measurements=records)])
|
||||
self.assertEqual(performance.validate_baseline(dict(summary=summary)), summary)
|
||||
for bad in ({}, dict(summary=[]), dict(summary=summary + summary), dict(summary=[{**summary[0], "mode": []}]),
|
||||
dict(summary=[{**summary[0], "median_mbps": float("nan") }])):
|
||||
with self.assertRaises(ValueError):
|
||||
performance.validate_baseline(bad)
|
||||
|
||||
def test_successful_command_with_missing_measurements_is_a_failure(self):
|
||||
step = runner.Step("empty", [sys.executable, "-c", "print('success, but no measurements')"], measurement=SPEC)
|
||||
with tempfile.TemporaryDirectory() as temporary, contextlib.redirect_stdout(io.StringIO()):
|
||||
result = runner.execute(step, Path(temporary), 5)
|
||||
self.assertEqual(result["command_exit_code"], 0)
|
||||
self.assertEqual(result["status"], "failed")
|
||||
|
||||
def test_speed_gate_failure_produces_reports_even_after_command_success(self):
|
||||
spec = dict(SPEC)
|
||||
steps = [runner.Step("measured", [sys.executable, "-c", "print(" + repr(fixture(speed=2)) + ")"], measurement=spec),
|
||||
runner.Step("speed-check", [], requires=("measured",), checks=dict(repeats=1, min_mbps=10,
|
||||
max_queue_drops=0, baseline=None, max_regression_percent=20))]
|
||||
with tempfile.TemporaryDirectory() as temporary, contextlib.redirect_stdout(io.StringIO()):
|
||||
directory = Path(temporary) / "run"
|
||||
results = runner.run(steps, directory)
|
||||
self.assertEqual([r["status"] for r in results], ["passed", "failed"])
|
||||
metrics = json.loads((directory / "metrics.json").read_text())
|
||||
self.assertEqual(metrics["summary"][0]["median_mbps"], 2)
|
||||
self.assertIn("below", (directory / "speed-check.log").read_text())
|
||||
self.assertTrue((directory / "speed-summary.md").exists())
|
||||
|
||||
def test_speed_plan_covers_matrix_and_deduplicates_throughput(self):
|
||||
steps = runner.plan(["speed", "throughput"], rtts=(0, 58, 100), repeats=3)
|
||||
measured = [s for s in steps if s.measurement]
|
||||
self.assertEqual(len(measured), 27)
|
||||
self.assertEqual(steps[-1].name, "speed-check")
|
||||
self.assertEqual(len(steps[-1].requires), 27)
|
||||
|
||||
def test_gate_options_cannot_silently_run_functional_tests_only(self):
|
||||
with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as error:
|
||||
runner.main(["all", "--min-mbps", "10", "--list"])
|
||||
self.assertEqual(error.exception.code, 2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,82 @@
|
||||
import contextlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
spec = importlib.util.spec_from_file_location("meshport_test_runner", Path(__file__).resolve().parents[1] / "test.py")
|
||||
runner = importlib.util.module_from_spec(spec)
|
||||
sys.modules[spec.name] = runner
|
||||
spec.loader.exec_module(runner)
|
||||
|
||||
|
||||
class RunnerTest(unittest.TestCase):
|
||||
def test_default_plan_excludes_throughput_and_native_builds(self):
|
||||
steps = runner.plan(["all"], platform="darwin")
|
||||
names = {step.name for step in steps}
|
||||
self.assertTrue({"sdk", "go-race", "go-vet", "go-sdk-bridge", "flutter-tests", "macos-profile-storage"} <= names)
|
||||
self.assertNotIn("sdk-throughput", names)
|
||||
self.assertNotIn("client-rust-library", names)
|
||||
self.assertIn("sdk", self.list_default())
|
||||
|
||||
def list_default(self):
|
||||
with contextlib.redirect_stdout(io.StringIO()) as output:
|
||||
self.assertEqual(runner.main(["--list"]), 0)
|
||||
return output.getvalue()
|
||||
|
||||
def test_native_tests_depend_on_both_new_libraries(self):
|
||||
step = next(s for s in runner.plan(["client"], native=True, platform="darwin") if s.name == "flutter-tests")
|
||||
self.assertIn("client-rust-library", step.requires)
|
||||
self.assertIn("client-go-library", step.requires)
|
||||
self.assertTrue(step.env["MESHPORT_LIBRARY"].endswith("libmeshport_ffi.dylib"))
|
||||
with self.assertRaises(ValueError):
|
||||
runner.plan(["client"], native=True, platform="linux")
|
||||
|
||||
def test_removes_inherited_profiles_and_diagnostic_inputs(self):
|
||||
with patch.dict(os.environ, {"MESHPORT_DRAIN_PROFILE": "private.json", "MESHPORT_LIBRARY": "old.dylib", "MESHPORT_TEST_DELAY_MS": "999"}):
|
||||
env = runner.test_environment({"MESHPORT_LIBRARY": "new.dylib"})
|
||||
self.assertEqual(env["MESHPORT_LIBRARY"], "new.dylib")
|
||||
self.assertNotIn("MESHPORT_DRAIN_PROFILE", env)
|
||||
self.assertNotIn("MESHPORT_TEST_DELAY_MS", env)
|
||||
|
||||
def test_failure_skips_dependents_but_runs_independent_steps_and_reports(self):
|
||||
steps = [
|
||||
runner.Step("failure", [sys.executable, "-c", "print('失败日志'); raise SystemExit(7)"]),
|
||||
runner.Step("dependent", [sys.executable, "-c", "raise SystemExit(99)"], requires=("failure",)),
|
||||
runner.Step("independent", [sys.executable, "-c", "print('ok')"]),
|
||||
]
|
||||
with tempfile.TemporaryDirectory() as temporary, contextlib.redirect_stdout(io.StringIO()):
|
||||
directory = Path(temporary) / "run"
|
||||
results = runner.run(steps, directory)
|
||||
self.assertEqual([r["status"] for r in results], ["failed", "skipped", "passed"])
|
||||
self.assertEqual(results[0]["exit_code"], 7)
|
||||
self.assertIn("失败日志", (directory / "failure.log").read_text())
|
||||
self.assertEqual(len(json.loads((directory / "report.json").read_text())["steps"]), 3)
|
||||
xml = ET.parse(directory / "junit.xml").getroot()
|
||||
self.assertEqual(xml.attrib["failures"], "1")
|
||||
self.assertEqual(xml.attrib["skipped"], "1")
|
||||
|
||||
def test_fail_fast_and_timeout(self):
|
||||
steps = [runner.Step("timeout", [sys.executable, "-c", "import time; time.sleep(10)"]),
|
||||
runner.Step("later", [sys.executable, "-c", "pass"])]
|
||||
with tempfile.TemporaryDirectory() as temporary, contextlib.redirect_stdout(io.StringIO()):
|
||||
results = runner.run(steps, Path(temporary) / "run", timeout=0.05, fail_fast=True)
|
||||
self.assertEqual(results[0]["exit_code"], 124)
|
||||
self.assertEqual(results[1]["status"], "skipped")
|
||||
|
||||
def test_main_returns_failure_exit_code(self):
|
||||
result = [{"name": "failed", "status": "failed", "exit_code": 3}]
|
||||
with tempfile.TemporaryDirectory() as temporary, patch.object(runner, "run", return_value=result), contextlib.redirect_stdout(io.StringIO()):
|
||||
self.assertEqual(runner.main(["sdk", "--log-dir", str(Path(temporary) / "run")]), 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user