Files
clean-architecture-frontend…/scripts/tests/test_verify.py
DongHyeonka 4693d3d902 fix(verify): desktop에 보내는 트리가 같은 크기·같은 초의 수정을 빼지 않는다
문제:
- `scripts/verify.sh`는 index를 `cp`로 복사한 뒤 그 사본에 `git add -A`로
  보낼 트리를 만든다. `cp`는 사본의 mtime을 지금으로 바꾼다.
- git은 stat이 index 기록과 같은 파일 가운데 index 파일보다 늦지 않은
  항목(racy)만 내용을 읽는다. git이 index를 쓴 그 초에 같은 크기로 고친
  파일은 원래 index에서 racy라 `git status`에 보인다. 사본에서는 racy가
  아니어서 `git add -A`가 수정을 뺀다.
- 그러면 desktop은 작업 트리와 다른 트리를 돌리고, 트리 해시 대조도
  통과한다. 양쪽이 같은 (틀린) 트리를 계산하기 때문이다
  (fe-ci-next-3 재현).

고친 것:
- 복사를 `cp -p`로 바꿔 사본이 index의 mtime을 지킨다.
- 시험 `test_an_edit_git_sees_only_by_reading_the_file_is_sent_too`
  (`scripts/tests/test_verify.py`)를 더한다.
  - 파일과 index의 mtime을 1시간 전으로 고정하고, 같은 크기로 고친다.
    시각을 손으로 정해 매번 같은 결과를 낸다. ctime은 고친 초에 따라
    기록과 같기도 달라서 `core.trustctime=false`로 보지 않게 한다.
  - 보낸 트리(summary 첫 줄)가 빈 index로 만든 작업 트리와 같고, 원격이
    고친 내용을 돌렸고, `git status`도 그 수정을 보는지 본다.
- 기존 원격 시험도 기대 트리를 빈 index로 만든다(`working_tree`). 전에는
  `shutil.copy`로 mtime을 버린 사본에서 만들어, 고친 결함과 같은 방식이
  정답 역할을 했다.

버린 안:
- index 사본 없이 빈 index에서 트리를 만들기. 보낼 때마다 추적하는 파일
  전부의 내용을 다시 읽는다. `cp -p`면 racy 항목만 읽는다.

검증:
- RED: 고치기 전 새 시험 3회 모두 실패. 보낸 트리가 HEAD 트리였다.
- GREEN: 고친 뒤 3회 통과. `python3 -m unittest discover -s scripts/tests`
  80개 통과.
- 변이: `cp -p`를 `cp`로 되돌리면 새 시험만 실패한다.
2026-11-20 20:10:35 +09:00

301 lines
18 KiB
Python

"""scripts/verify.sh의 시험. 단계를 계약 파일에서 읽는지, 잘못된 인자를 원격에 보내기 전에 거절하는지,
지금 트리를 원격 worktree로 옮겨 같은 트리에서 돌리고 지우는지를 표준 라이브러리와 git·bash·flock으로 본다.
원격은 가짜 ssh(호스트를 무시하고 이 기계에서 실행)다. pnpm은 돌리지 않는다.
python3 -m unittest discover -s scripts/tests
"""
from __future__ import annotations
import json
import os
import shutil
import subprocess
import tempfile
import time
import unittest
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent.parent
VERIFY = REPO / "scripts/verify.sh"
GIT_ENV = {"GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@example.com", "GIT_COMMITTER_NAME": "t",
"GIT_COMMITTER_EMAIL": "t@example.com", "GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "core.hooksPath",
"GIT_CONFIG_VALUE_0": "/dev/null"}
def sh(args: list[str], cwd: Path, env: dict | None = None, check: bool = True) -> subprocess.CompletedProcess:
result = subprocess.run(args, cwd=cwd, env={**os.environ, **GIT_ENV, **(env or {})}, capture_output=True,
text=True, timeout=60)
if check and result.returncode != 0:
raise AssertionError(f"{args} → {result.returncode}\n{result.stdout}\n{result.stderr}")
return result
def gates() -> dict:
return json.loads((REPO / "config/ci/gates.json").read_text(encoding="utf-8"))
class StagePlanTest(unittest.TestCase):
def test_a_stage_runs_every_gate_the_contract_lists(self) -> None:
for stage in gates()["stages"]:
with self.subTest(stage=stage["id"]):
result = sh([str(VERIFY), stage["id"], "--dry-run"], cwd=REPO)
planned = [line.split(":")[0] for line in result.stdout.splitlines()]
self.assertEqual(planned, stage["gateIds"])
self.assertIn(f"ci:gate {stage['gateIds'][0]}", result.stdout)
def test_parts_runs_each_command_of_the_gate(self) -> None:
contract = gates()
gate = next(g for g in contract["gates"] if g["id"] == "FE-GATE-005")
scripts = {c["id"]: c["script"] for c in contract["commands"]}
result = sh([str(VERIFY), "parts", "FE-GATE-005", "--dry-run"], cwd=REPO)
self.assertEqual([line.split(": ", 1)[1] for line in result.stdout.splitlines()],
[f"corepack pnpm -s {scripts[c]}" for c in gate["commandIds"]])
def test_a_gate_with_a_host_environment_runs_in_it_as_in_the_workflow(self) -> None:
# FE-GATE-013 needs systemd and bubblewrap; verify.sh runs it through
# scripts/run-in-system-container.sh (config/ci/gates.json hostEnvironment), and the workflow's
# ci:gate enters the same wrapper from the job once it has decided the PR selection.
contract = gates()
hosted = [g for g in contract["gates"] if g.get("hostEnvironment") == "system-container"]
self.assertEqual([g["id"] for g in hosted], ["FE-GATE-013"])
scripts = {c["id"]: c["script"] for c in contract["commands"]}
wrapper = "scripts/run-in-system-container.sh"
result = sh([str(VERIFY), "gate", "FE-GATE-013", "FE-GATE-005", "--dry-run"], cwd=REPO)
self.assertEqual(result.stdout.splitlines(), [f"FE-GATE-013: {wrapper} corepack pnpm -s ci:gate FE-GATE-013",
"FE-GATE-005: corepack pnpm -s ci:gate FE-GATE-005"])
result = sh([str(VERIFY), "parts", "FE-GATE-013", "--dry-run"], cwd=REPO)
self.assertEqual([line.split(": ", 1)[1] for line in result.stdout.splitlines()],
[f"{wrapper} corepack pnpm -s {scripts[c]}" for c in hosted[0]["commandIds"]])
workflow = (REPO / ".gitea/workflows/quality-gates.yml").read_text(encoding="utf-8")
self.assertIn("run: corepack pnpm ci:gate -- FE-GATE-013 --enter-host-environment", workflow)
self.assertNotIn(f"run: {wrapper} corepack pnpm ci:gate -- FE-GATE-013", workflow)
# A host that cannot start the container runs the gate here (gates.md 3절).
result = sh([str(VERIFY), "gate", "FE-GATE-013", "--dry-run"], cwd=REPO, env={"VERIFY_HOST_ENVIRONMENT": "off"})
self.assertEqual(result.stdout.splitlines(), ["FE-GATE-013: corepack pnpm -s ci:gate FE-GATE-013"])
def test_parts_passes_each_command_its_arguments_as_ci_gate_does(self) -> None:
# run-ci-gate.ts runs `pnpm <script> ...args`. Without the args FE-GATE-009's
# `review:a11y-manual -- --format-only` checked the release evidence instead and failed.
contract = gates()
commands = {c["id"]: c for c in contract["commands"]}
with_args = [g for g in contract["gates"]
if any(commands[c].get("args") for c in g["commandIds"])]
self.assertTrue(with_args, "the contract has no command with arguments to check")
for gate in with_args:
with self.subTest(gate=gate["id"]):
result = sh([str(VERIFY), "parts", gate["id"], "--dry-run"], cwd=REPO)
expected = []
prefix = ["scripts/run-in-system-container.sh"] if gate.get("hostEnvironment") else []
for command_id in gate["commandIds"]:
command = commands[command_id]
words = [*prefix, "corepack", "pnpm", "-s", command["script"], *command.get("args", [])]
expected.append(" ".join(words))
self.assertEqual([line.split(": ", 1)[1] for line in result.stdout.splitlines()], expected)
def test_parts_passes_a_negative_fixture_only_with_its_registered_diagnostic(self) -> None:
# run-ci-gate.ts passes an expect=fail command only when it exits with its code and prints its
# diagnostic. parts saw the exit code alone, so a checker broken into an unrelated exit 1 (a
# TypeError) still counted as its negative fixture passing.
contract = gates()
commands = {c["id"]: c for c in contract["commands"]}
gate = next(g for g in contract["gates"] if g["id"] == "FE-GATE-029")
negatives = [commands[c] for c in gate["commandIds"] if commands[c].get("expect") == "fail"]
self.assertTrue(any(c.get("expectedDiagnosticId") for c in negatives))
with tempfile.TemporaryDirectory() as tmp:
fake = Path(tmp) / "corepack"
# Answers `corepack pnpm -s <script> ...args` as the contract registers that command:
# pass commands exit 0, negative fixtures exit with their code and print DIAGNOSTIC_MODE.
fake.write_text(f"""#!/usr/bin/env python3
import json, os, sys
script, args = sys.argv[3], sys.argv[4:]
for command in json.load(open({str(REPO / "config/ci/gates.json")!r}))["commands"]:
if command["script"] == script and command.get("args", []) == args:
break
else:
sys.exit(97)
if command.get("expect") != "fail":
sys.exit(0)
if os.environ["DIAGNOSTIC_MODE"] == "registered":
print("checker refused the fixture:", command.get("expectedDiagnosticId", ""))
else:
print("TypeError: Cannot read properties of undefined")
sys.exit(command.get("expectedExitCode", 1))
""", encoding="utf-8")
fake.chmod(0o755)
env = {"PATH": f"{tmp}:{os.environ['PATH']}"}
wrong = sh([str(VERIFY), "parts", "FE-GATE-029", "--on", "here"], cwd=REPO, check=False,
env={**env, "DIAGNOSTIC_MODE": "unrelated"})
self.assertEqual(wrong.returncode, 1, wrong.stdout + wrong.stderr)
self.assertIn("diagnostic", wrong.stderr)
right = sh([str(VERIFY), "parts", "FE-GATE-029", "--on", "here"], cwd=REPO, check=False,
env={**env, "DIAGNOSTIC_MODE": "registered"})
self.assertEqual(right.returncode, 0, right.stdout + right.stderr)
def test_arguments_after_the_separator_go_to_the_one_script_or_command_as_given(self) -> None:
result = sh([str(VERIFY), "script", "test:sample-removal", "--dry-run", "--", "--feature=invoice-feature"],
cwd=REPO)
self.assertEqual(result.stdout.strip(),
"test:sample-removal: corepack pnpm -s test:sample-removal --feature=invoice-feature")
result = sh([str(VERIFY), "exec", "--dry-run", "--", "node", "scripts/run-vitest.ts", "run", "tests/a b.test.ts"],
cwd=REPO)
self.assertEqual(result.stdout.strip(), r"exec node: node scripts/run-vitest.ts run tests/a\ b.test.ts")
def test_wrong_arguments_are_refused_here_before_anything_is_sent(self) -> None:
with tempfile.TemporaryDirectory() as folder:
calls = Path(folder) / "calls"
fake_ssh = Path(folder) / "ssh"
fake_ssh.write_text(f'#!/bin/sh\necho "$@" >> {calls}\n', encoding="utf-8")
fake_ssh.chmod(0o755)
for args in (["nope"], ["gate", "FE-GATE-999"], ["parts"], ["gate"], ["merge", "extra"], ["docs", "x"],
["script", "a", "b", "--", "--x"], ["exec"], ["exec", "--"], ["script", "--", "x"]):
with self.subTest(args=args):
result = sh([str(VERIFY), *args], cwd=REPO, env={"VERIFY_SSH": str(fake_ssh)}, check=False)
self.assertEqual(result.returncode, 2, result.stderr)
self.assertFalse(calls.exists(), "a refused command must not reach the remote host")
class CiEnvironmentTest(unittest.TestCase):
def test_the_ci_env_names_the_head_commit_and_its_time(self) -> None:
# parts and script run the gate commands without ci:gate, which would otherwise set SOURCE_DATE_EPOCH.
script = (f'eval "$(sed -n "/^ci_env()/,/^}}/p" {VERIFY})"; ci_env; '
'echo "$CI $VITE_COMMIT_SHA $SOURCE_DATE_EPOCH $CI_RUNNER_IMAGE"')
ci, sha, epoch, image = sh(["bash", "-c", script], cwd=REPO).stdout.split()
self.assertEqual(ci, "true")
self.assertEqual(sha, sh(["git", "rev-parse", "HEAD"], cwd=REPO).stdout.strip())
self.assertEqual(epoch, sh(["git", "log", "-1", "--format=%ct"], cwd=REPO).stdout.strip())
self.assertRegex(image, r"@sha256:[0-9a-f]{64}$")
def remote_project(base: Path) -> tuple[Path, Path, Path, dict]:
"""A project with an origin and a clone of it as the remote checkout, and the env that sends a run there."""
project, bare, remote, logs = (base / name for name in ("project", "origin.git", "remote", "logs"))
(project / "scripts").mkdir(parents=True)
(project / "config/ci").mkdir(parents=True)
shutil.copy(VERIFY, project / "scripts/verify.sh")
shutil.copy(REPO / "config/ci/gates.json", project / "config/ci/gates.json")
shutil.copy(REPO / ".nvmrc", project / ".nvmrc")
(project / "scripts/check-work-docs.py").write_text("print('docs checked')\n", encoding="utf-8")
sh(["git", "init", "-q", "-b", "main"], cwd=project)
sh(["git", "add", "-A"], cwd=project)
sh(["git", "commit", "-q", "-m", "init"], cwd=project)
sh(["git", "clone", "-q", "--bare", str(project), str(bare)], cwd=base)
sh(["git", "remote", "add", "origin", str(bare)], cwd=project)
sh(["git", "fetch", "-q", "origin"], cwd=project)
sh(["git", "clone", "-q", str(bare), str(remote)], cwd=base)
fake_ssh = base / "fake-ssh"
fake_ssh.write_text('#!/bin/sh\nshift\nexec bash -c "$*"\n', encoding="utf-8")
fake_ssh.chmod(0o755)
env = {"VERIFY_SSH": str(fake_ssh), "VERIFY_REMOTE_REPO": str(remote), "VERIFY_LOCK": str(base / "lock"),
"VERIFY_LOG_ROOT": str(logs), "VERIFY_NODE_BIN": "/nonexistent"}
return project, remote, logs, env
class ReleaseIdTest(unittest.TestCase):
"""The build a run makes is named as in CI, with a fixed ref: never after the branch the checkout is on.
The ref used to be the checkout's branch. A long branch name made a release id the home page could not wrap at
320 px, so FE-GATE-008 passed detached and failed on the branch, on the same tree.
"""
def test_a_long_branch_and_a_detached_checkout_build_the_same_release_id(self) -> None:
with tempfile.TemporaryDirectory() as folder:
base = Path(folder)
project, _, _, env = remote_project(base)
# Stands in for the remote's node bin: the gate's `corepack pnpm -s ci:gate` records what it was given.
tools, seen = base / "bin", base / "release-ids"
tools.mkdir()
(tools / "corepack").write_text('#!/bin/sh\nprintf "%s\\n" "$RELEASE_ID" >> "$SEEN_RELEASE_IDS"\n',
encoding="utf-8")
(tools / "corepack").chmod(0o755)
# VERIFY_RUN is cleared: a caller's own run number must not reach the expected value.
env = {**env, "VERIFY_NODE_BIN": str(tools), "VERIFY_INSTALL": "0", "SEEN_RELEASE_IDS": str(seen),
"VERIFY_RUN": ""}
gate = gates()["gates"][0]["id"]
sh(["git", "switch", "-q", "-c", "fix/" + "a-branch-name-that-keeps-going-" * 4 + "on"], cwd=project)
sh(["scripts/verify.sh", "gate", gate, "--on", "build-host"], cwd=project, env=env)
sh(["git", "switch", "-q", "--detach"], cwd=project)
sh(["scripts/verify.sh", "gate", gate, "--on", "build-host"], cwd=project, env=env)
# .gitea/workflows/quality-gates.yml: "${{ gitea.ref }}-${{ gitea.run_id }}-${{ gitea.run_attempt }}"
self.assertEqual(seen.read_text(encoding="utf-8").splitlines(), ["refs/heads/verify-1-1"] * 2)
def working_tree(project: Path, base: Path) -> str:
"""작업 트리의 트리 해시. 빈 index에서 만들어 index의 stat 기록에 기대지 않는다."""
fresh_index = base / "fresh-index"
fresh_index.unlink(missing_ok=True)
sh(["git", "add", "-A"], cwd=project, env={"GIT_INDEX_FILE": str(fresh_index)})
return sh(["git", "write-tree"], cwd=project, env={"GIT_INDEX_FILE": str(fresh_index)}).stdout.strip()
class RemoteTransportTest(unittest.TestCase):
"""--on <호스트>: the patch lands in a fresh worktree, the tree matches, the run is logged, the worktree goes."""
def test_the_working_tree_is_run_remotely_on_the_same_tree_and_cleaned_up(self) -> None:
with tempfile.TemporaryDirectory() as folder:
base = Path(folder)
project, remote, logs, env = remote_project(base)
(project / "notes.md").write_text("커밋 안 한 새 파일\n", encoding="utf-8")
with (project / "scripts/check-work-docs.py").open("a", encoding="utf-8") as handle:
handle.write("print('changed here')\n")
here = working_tree(project, base)
result = sh(["scripts/verify.sh", "docs", "--on", "build-host", "--log", "t"], cwd=project, env=env,
check=False)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
summary = (logs / "t/summary.txt").read_text(encoding="utf-8")
self.assertTrue(summary.startswith(f"tree {here} commit "), summary)
self.assertIn("rc=0", summary)
self.assertIn("changed here", (logs / "t/run.log").read_text(encoding="utf-8"))
self.assertFalse((logs / "t/install.log").exists(), "a laptop stage installs nothing")
worktrees = sh(["git", "worktree", "list"], cwd=remote).stdout.strip().splitlines()
self.assertEqual(len(worktrees), 1, worktrees)
self.assertEqual(sh(["git", "status", "--porcelain"], cwd=remote).stdout, "")
self.assertEqual((logs / "t/changes.patch").read_text(encoding="utf-8"), "")
made = sh(["scripts/verify.sh", "exec", "--on", "build-host", "--log", "t2", "--apply-back", "--", "bash", "-c",
"echo made > made.txt && echo more >> notes.md"], cwd=project,
env={**env, "VERIFY_INSTALL": "0"}, check=False)
self.assertEqual(made.returncode, 0, made.stdout + made.stderr)
self.assertEqual((project / "made.txt").read_text(encoding="utf-8"), "made\n")
self.assertEqual((project / "notes.md").read_text(encoding="utf-8"), "커밋 안 한 새 파일\nmore\n")
self.assertIn("2개를 이 작업 트리에 얹었다", made.stderr)
missing = sh(["scripts/verify.sh", "docs", "--on", "build-host"], cwd=project,
env={**env, "VERIFY_REMOTE_REPO": str(base / "missing")}, check=False)
self.assertEqual(missing.returncode, 4)
def test_an_edit_git_sees_only_by_reading_the_file_is_sent_too(self) -> None:
"""fe-ci-next-3. 같은 크기로 고친 파일의 stat이 index 기록과 같으면, git은 index 파일보다 늦지 않은 항목(racy)만
내용을 읽어 수정을 본다. 보낼 트리를 만드는 index 사본이 mtime을 잃으면 그 항목이 racy가 아니게 되어 사본의
`git add -A`가 수정을 빼고, 원격은 작업 트리와 다른 트리를 같은 트리라며 돌렸다."""
with tempfile.TemporaryDirectory() as folder:
base = Path(folder)
project, _, logs, env = remote_project(base)
edited = project / "scripts/check-work-docs.py"
# 시각을 손으로 정해 매번 같은 결과를 낸다. ctime은 고친 초에 따라 기록과 같기도 달라서 보지 않게 한다.
sh(["git", "config", "core.trustctime", "false"], cwd=project)
old = int(time.time()) - 3600
os.utime(edited, (old, old))
sh(["git", "update-index", "--refresh"], cwd=project)
edited.write_text("print('docs changed')\n", encoding="utf-8")
os.utime(edited, (old, old))
# git이 index를 쓴 그 초에 파일을 같은 크기로 고친 상태다.
os.utime(project / ".git/index", (old, old))
result = sh(["scripts/verify.sh", "docs", "--on", "build-host", "--log", "t"], cwd=project, env=env,
check=False)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
summary = (logs / "t/summary.txt").read_text(encoding="utf-8")
self.assertTrue(summary.startswith(f"tree {working_tree(project, base)} commit "), summary)
self.assertIn("docs changed", (logs / "t/run.log").read_text(encoding="utf-8"))
self.assertEqual(sh(["git", "status", "--porcelain"], cwd=project).stdout, " M scripts/check-work-docs.py\n")
if __name__ == "__main__":
unittest.main()