forked from mtusi2026/mtusi2026lab3
115 lines
6.4 KiB
Python
115 lines
6.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Clone a temporary Git snapshot of the current solution and test that clone.
|
|
|
|
The user's index, branch, commits and remotes are never changed. Ignored local
|
|
state is excluded. This validates the working solution, not the remote fork.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def run(args, cwd, env=None, log=None):
|
|
result = subprocess.run(args, cwd=cwd, env=env, stdout=log or subprocess.PIPE,
|
|
stderr=subprocess.STDOUT, text=True, timeout=600)
|
|
if result.returncode:
|
|
raise RuntimeError("Clean clone command failed; inspect its test log")
|
|
return result.stdout or ""
|
|
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(description=__doc__)
|
|
p.add_argument("--output", type=Path, required=True)
|
|
p.add_argument("--measure-budgets", action="store_true", help="include bounded HTTP measurements in the clone")
|
|
p.add_argument("--pull", choices=("missing", "never", "always"), default="missing")
|
|
args = p.parse_args()
|
|
output = args.output.resolve()
|
|
output.mkdir(parents=True, exist_ok=True)
|
|
names = subprocess.run(["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
|
cwd=ROOT, capture_output=True, check=True).stdout.split(b"\0")
|
|
paths = sorted({os.fsdecode(name) for name in names if name})
|
|
manifest = {}
|
|
summary = {"status": "FAIL", "scope": "temporary Git snapshot of current working tree; not remote HEAD"}
|
|
try:
|
|
with tempfile.TemporaryDirectory(prefix="lab2-clone-") as directory:
|
|
temp = Path(directory)
|
|
# Match the real checkout: an ASCII repository name inside a path
|
|
# with spaces/Unicode. Docker Desktop Bake currently rejects a
|
|
# non-ASCII *repository basename* in its session shared-key header.
|
|
snapshot, clone = temp / "snapshot", temp / "путь с пробелами" / "HighLoad"
|
|
snapshot.mkdir()
|
|
clone.parent.mkdir()
|
|
for name in paths:
|
|
source = ROOT / name
|
|
if not source.is_file() and not source.is_symlink():
|
|
continue
|
|
# Even an accidentally tracked secret must not enter this fixture.
|
|
parts = Path(name).parts
|
|
if name in ("api", "server"):
|
|
continue # Local compiled binaries are not source dependencies.
|
|
if "secrets" in parts or "output" in parts or "evidence" in parts or ".venv" in parts:
|
|
continue
|
|
if Path(name).name.startswith(".env") and name != ".env.example":
|
|
continue
|
|
target = snapshot / name
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
shutil.copy2(source, target, follow_symlinks=False)
|
|
if not source.is_symlink():
|
|
manifest[name] = hashlib.sha256(source.read_bytes()).hexdigest()
|
|
env = os.environ.copy()
|
|
env.update(GIT_AUTHOR_NAME="Lab2 test snapshot", GIT_AUTHOR_EMAIL="lab2-test@localhost",
|
|
GIT_COMMITTER_NAME="Lab2 test snapshot", GIT_COMMITTER_EMAIL="lab2-test@localhost")
|
|
with (output / "clone.log").open("w") as log:
|
|
run(["git", "init", "--initial-branch=main"], snapshot, env, log)
|
|
run(["git", "add", "--all"], snapshot, env, log)
|
|
run(["git", "-c", "commit.gpgsign=false", "commit", "-m", "Temporary acceptance snapshot"], snapshot, env, log)
|
|
run(["git", "clone", "--no-local", str(snapshot), str(clone)], temp, env, log)
|
|
if run(["git", "status", "--porcelain"], clone).strip():
|
|
raise RuntimeError("Clone is not clean")
|
|
for name in (".env", "secrets", ".venv", "student-tests/output"):
|
|
if (clone / name).exists():
|
|
raise RuntimeError("Private local state unexpectedly entered the clone")
|
|
for name in ("restart.sh", "stop-postgres.sh", "start-postgres.sh", "stop-redis.sh", "start-redis.sh", "setup-tests.sh"):
|
|
if not os.access(clone / "scripts" / name, os.X_OK):
|
|
raise RuntimeError("Executable bit lost in clone: " + name)
|
|
with (output / "dependencies.log").open("w") as log:
|
|
run([str(clone / "scripts/setup-tests.sh")], clone, log=log)
|
|
with (output / "verify.log").open("w") as log:
|
|
verify_args = [str(clone / ".venv/bin/python"), "student-tests/stack.py", "verify",
|
|
"--output", str(output / "acceptance"), "--pull", args.pull]
|
|
if args.measure_budgets:
|
|
verify_args.append("--measure-budgets")
|
|
verification = subprocess.run(verify_args,
|
|
cwd=clone, stdout=log, stderr=subprocess.STDOUT, text=True, timeout=1200)
|
|
summary["acceptance_exit"] = verification.returncode
|
|
acceptance_path = output / "acceptance/summary.json"
|
|
if acceptance_path.exists():
|
|
acceptance = json.loads(acceptance_path.read_text())
|
|
summary["bootstrap"] = "PASS" if any(x["check"] == "compose-up" and x["status"] == "PASS" for x in acceptance["results"]) else "FAIL"
|
|
# Fixtures stay ignored; the test runner must not modify source files.
|
|
if run(["git", "status", "--porcelain"], clone).strip():
|
|
raise RuntimeError("Tests changed tracked or unignored files in the clone")
|
|
summary["source_clean_after_tests"] = True
|
|
summary["status"] = "PASS" if verification.returncode == 0 else "FAIL"
|
|
if verification.returncode != 0:
|
|
summary["detail"] = "Clone/bootstrap completed; acceptance tests failed, see acceptance summary"
|
|
summary["source_files"] = len(manifest)
|
|
except (OSError, RuntimeError, subprocess.SubprocessError) as error:
|
|
summary["detail"] = str(error) if isinstance(error, RuntimeError) else type(error).__name__
|
|
(output / "snapshot-manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2))
|
|
(output / "clone-summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2))
|
|
print(summary["status"] + ": " + str(output / "clone-summary.json"))
|
|
return 0 if summary["status"] == "PASS" else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|