Implement marqdo-ext-http#3: the explicit @http package now owns a real
loopback domain test instead of only pure encode/parse cases.
- tests/loopback.mq.md performs two real HTTP/1.1 exchanges in one program
through the CLI's generic resource.open("tcp")/read/write/close, building
requests with http.构建请求字节 and parsing responses with
http.解析响应字节; non-ASCII bodies, explicit --allow-net 127.0.0.1 and
--allow-env HTTP_TEST_PORT only.
- scripts/loopback_server.py is a deterministic one-request-per-connection
server that records method/path/body and returns fixed status/bodies.
- scripts/run_cases.py supports kind=loopback (server lifecycle, port env,
grants, request-record assertions) without changing the pure case path.
- tests/cases/loopback.json asserts GET /one -> 200 第一个 and
POST /two -> 201 第二个 plus the request records.
- Evidence: docs/evidence-2026-11-30-loopback-domain-test.md (real CLI rc.6
candidate + Bundle 0.3.0: 2 cases PASS).
No CLI/Host/other-component change, no new Host request, no release.
214 lines
8.1 KiB
Python
Executable File
214 lines
8.1 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Run an explicit-package extension repository's tests with real CLI inputs.
|
|
|
|
Each case builds a throwaway consumer project whose `dependencies.<alias>` path
|
|
points at a copy of this repository's package (`marqdo.yaml` + `index.mq.md`),
|
|
runs `marqdo lock` once, then executes the migrated `.mq.md` test through the
|
|
public `@alias` import. Inputs are explicit: `MARQDO_BIN` (verified CLI) and
|
|
`MARQDO_STDLIB_DIR` (installed Bundle for the remaining `std:` imports, if any).
|
|
Nothing reads a sibling repository or a floating branch.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import json
|
|
import os
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
REPO = Path(__file__).resolve().parents[1]
|
|
CASES = REPO / "tests" / "cases"
|
|
SCHEMA = "marqdo.package-test-case"
|
|
SCHEMA_VERSION = 1
|
|
|
|
|
|
class CaseError(Exception):
|
|
pass
|
|
|
|
|
|
def substitute(value, binary: str, package_root: Path):
|
|
if isinstance(value, dict):
|
|
if set(value) == {"$bin_version"}:
|
|
return subprocess.run([binary, "--version"], capture_output=True, text=True).stdout
|
|
if set(value) == {"$package_root"}:
|
|
return str(package_root)
|
|
return {k: substitute(v, binary, package_root) for k, v in value.items()}
|
|
if isinstance(value, list):
|
|
return [substitute(v, binary, package_root) for v in value]
|
|
return value
|
|
|
|
|
|
def channel_text(events, channel):
|
|
parts = []
|
|
for event in events:
|
|
if event.get("kind") != channel:
|
|
continue
|
|
payload = event["payload"]
|
|
data = base64.b64decode(payload["data_base64"])
|
|
if len(data) != payload["byte_count"]:
|
|
raise CaseError(f"{channel} byte_count mismatch")
|
|
parts.append(data)
|
|
return b"".join(parts).decode()
|
|
|
|
|
|
def consumer_manifest(alias: str) -> str:
|
|
return (
|
|
"project:\n"
|
|
" name: package-test-consumer\n"
|
|
" version: 0.0.0\n"
|
|
' marqdo: ">=3.0.0-beta.1,<4.0.0"\n'
|
|
"dependencies:\n"
|
|
f" {alias}:\n"
|
|
f" path: ./deps/{alias}\n"
|
|
)
|
|
|
|
|
|
class Loopback:
|
|
"""One deterministic loopback HTTP server process for a domain case."""
|
|
|
|
def __init__(self, workdir: Path, requests: int):
|
|
self.record = workdir / "loopback-records.json"
|
|
self.record.unlink(missing_ok=True)
|
|
self.process = subprocess.Popen(
|
|
[
|
|
sys.executable,
|
|
str(REPO / "scripts" / "loopback_server.py"),
|
|
str(self.record),
|
|
str(requests),
|
|
],
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE,
|
|
text=True,
|
|
)
|
|
line = self.process.stdout.readline().strip()
|
|
if not line.isdigit():
|
|
stderr = self.process.stderr.read()
|
|
raise CaseError(f"loopback server did not report a port: {line!r} {stderr}")
|
|
self.port = int(line)
|
|
|
|
def finish(self) -> list[dict]:
|
|
try:
|
|
self.process.wait(timeout=15)
|
|
except subprocess.TimeoutExpired:
|
|
self.process.kill()
|
|
raise CaseError("loopback server did not finish")
|
|
if not self.record.is_file():
|
|
raise CaseError("loopback server wrote no request record")
|
|
return json.loads(self.record.read_text(encoding="utf-8"))
|
|
|
|
|
|
def check_loopback(case: dict, records: list[dict]) -> None:
|
|
expected = case.get("request_asserts", {}).get("requests", [])
|
|
if len(records) != len(expected):
|
|
raise CaseError(f"loopback request count {len(records)} != {len(expected)}")
|
|
for index, (actual, want) in enumerate(zip(records, expected)):
|
|
for key in ("method", "path", "body"):
|
|
if key in want and actual.get(key) != want[key]:
|
|
raise CaseError(
|
|
f"loopback request[{index}] {key} {actual.get(key)!r} != {want[key]!r}"
|
|
)
|
|
|
|
|
|
def run_case(case: dict, binary: str, bundle: Path) -> None:
|
|
name = case["name"]
|
|
alias = case["dep_alias"]
|
|
env = os.environ.copy()
|
|
env["MARQDO_STDLIB_DIR"] = str(bundle)
|
|
for key, value in case.get("env", {}).items():
|
|
env[key] = str(value).replace("$MARQDO_BIN", binary)
|
|
source = REPO / "tests" / case["file"]
|
|
if not source.is_file():
|
|
raise CaseError(f"{name}: missing test source {source}")
|
|
with tempfile.TemporaryDirectory(prefix="mq-package-test-") as tmp:
|
|
workdir = Path(tmp)
|
|
loopback = (
|
|
Loopback(workdir, int(case.get("requests", 2)))
|
|
if case.get("kind") == "loopback"
|
|
else None
|
|
)
|
|
consumer = workdir / "consumer"
|
|
package = consumer / "deps" / alias
|
|
package.mkdir(parents=True)
|
|
shutil.copy2(REPO / "marqdo.yaml", package / "marqdo.yaml")
|
|
shutil.copy2(REPO / "index.mq.md", package / "index.mq.md")
|
|
(consumer / "marqdo.yaml").write_text(consumer_manifest(alias))
|
|
(consumer / "tests").mkdir()
|
|
shutil.copy2(source, consumer / "tests" / case["file"])
|
|
lock = subprocess.run([binary, "lock"], cwd=consumer, env=env, capture_output=True)
|
|
if lock.returncode != 0:
|
|
raise CaseError(f"{name}: marqdo lock failed: {lock.stderr.decode(errors='replace')}")
|
|
args = [str(arg).replace("$MARQDO_BIN", binary) for arg in case.get("args", [])]
|
|
if loopback is not None:
|
|
env["HTTP_TEST_PORT"] = str(loopback.port)
|
|
for host in case.get("grants", []):
|
|
args += ["--allow-net", host]
|
|
for name in case.get("allow_env", []):
|
|
args += ["--allow-env", name]
|
|
result = subprocess.run(
|
|
[binary, "run", str(consumer / "tests" / case["file"]), *args, "--output", "json"],
|
|
cwd=consumer, env=env, input=case.get("stdin", "").encode(), capture_output=True,
|
|
)
|
|
if result.returncode != 0:
|
|
raise CaseError(f"{name}: CLI exited {result.returncode}:\n{result.stderr.decode(errors='replace')}")
|
|
report = json.loads(result.stdout)
|
|
if report.get("run", {}).get("status") != "ok":
|
|
raise CaseError(f"{name}: run status not ok")
|
|
terminal = report["events"][-1]["payload"]
|
|
if terminal.get("status") != "ok":
|
|
raise CaseError(f"{name}: terminal status not ok")
|
|
expected = substitute(case["expected_terminal"], binary, REPO)
|
|
if terminal.get("value") != expected:
|
|
raise CaseError(
|
|
f"{name}: terminal value changed\nexpected: "
|
|
f"{json.dumps(expected, ensure_ascii=False, sort_keys=True)}\nactual: "
|
|
f"{json.dumps(terminal.get('value'), ensure_ascii=False, sort_keys=True)}"
|
|
)
|
|
stdout = channel_text(report["events"], "stdout.chunk")
|
|
if stdout != case.get("expected_stdout", ""):
|
|
raise CaseError(f"{name}: stdout changed: {stdout!r}")
|
|
if loopback is not None:
|
|
check_loopback(case, loopback.finish())
|
|
|
|
|
|
def main() -> int:
|
|
binary = os.environ.get("MARQDO_BIN")
|
|
bundle = os.environ.get("MARQDO_STDLIB_DIR")
|
|
if not binary or not shutil.which(binary):
|
|
print("MARQDO_BIN must point at a verified marqdo executable", file=sys.stderr)
|
|
return 2
|
|
if not bundle or not Path(bundle).is_dir():
|
|
print("MARQDO_STDLIB_DIR must point at an installed Bundle", file=sys.stderr)
|
|
return 2
|
|
bundle = Path(bundle).resolve()
|
|
paths = sorted(CASES.glob("*.json"))
|
|
if not paths:
|
|
print("no test cases", file=sys.stderr)
|
|
return 2
|
|
failures = 0
|
|
ran = 0
|
|
for path in paths:
|
|
case = json.loads(path.read_text())
|
|
if case.get("schema") != SCHEMA or case.get("schema_version") != SCHEMA_VERSION:
|
|
print(f"FAIL {path.name}: unsupported schema", file=sys.stderr)
|
|
failures += 1
|
|
continue
|
|
ran += 1
|
|
try:
|
|
run_case(case, binary, bundle)
|
|
print(f"PASS {case['name']}")
|
|
except (CaseError, json.JSONDecodeError) as error:
|
|
print(f"FAIL {error}", file=sys.stderr)
|
|
failures += 1
|
|
if failures:
|
|
print(f"{failures} of {ran} cases failed", file=sys.stderr)
|
|
return 1
|
|
print(f"{ran} cases passed")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|