Files
clean-architecture-frontend…/scripts/tests/test_verify.py
T
DongHyeonka 1d3eb901d2 ci(gates): FE-GATE-013을 일회용 systemd 컨테이너 안에서 돌린다
문제: FE-GATE-013의 test:system은 provider sandbox를 실제로 띄운다.
systemd user manager(systemd-run --user --scope)와 cgroup v2 위임,
bubblewrap(--unshare-net 등)이 필요하다. runner의 job 컨테이너는
entrypoint가 sleep이라 systemd가 없고 bwrap도 없어 사전 점검에서 실패한다
(run 56·80·81). desktop 호스트는 다 있지만 Ubuntu 24.04의
apparmor_restrict_unprivileged_userns=1이 비특권 bwrap을 막는다.
그래서 이 게이트는 runner와 desktop 어디서도 초록인 적이 없다.

고른 방법(소유자 결정 2026-11-11 5절 e: 조건이 되는 실행 환경을 찾는다):
- config/ci/system-container.Dockerfile: Ubuntu 24.04(digest 고정) +
  systemd PID 1 + root linger + bubblewrap 등 hostRequirements의 도구.
- scripts/run-in-system-container.sh: 이미지(Dockerfile 해시 태그)가 없으면
  만들고, privileged·자체 cgroup namespace로 띄워 systemd와 root user
  manager를 기다린 뒤, 작업 트리·git 이력·호출한 쪽의 node와 corepack을
  복사해 명령을 root로 돌리고 artifacts/를 되가져온 다음 지운다. root는
  호스트의 userns 제한을 받지 않는다.
- gates.json 게이트 필드 hostEnvironment: "system-container"(FE-GATE-013).
  생성기는 그 게이트의 run 줄에 래퍼를 붙이고, 실행 검사
  (workflowGateExecutionFailures)는 계약이 정한 접두어로 돈 줄만 센다.
  scripts/verify.sh gate·parts·stage도 같은 래퍼로 돌린다.
- CI에서는 runner의 Docker proxy로 안쪽 dind daemon을 쓴다(platform-core
  gitea-runner README가 「남은 위험」으로 적은 길: proxy가 privileged
  컨테이너를 막지 않는다).
- 버린 대안: 전용 VM runner(문서 조건을 그대로 만족하지만 platform-core
  변경과 VM 자원·runner 등록이 필요), 호스트 AppArmor profile(호스트
  userns 제한을 푸는 보안 설정 변경, 소유자 sudo).

위험·한계:
- root로 돌아 「비특권 runner에서 bwrap userns」 조건 자체는 증명하지
  않는다. release 단계 provider job 둘은 아직 job 컨테이너에서 돈다(범위
  밖, 같은 래퍼나 VM runner가 필요).
- runner가 rootless dind로 바뀌면 privileged 컨테이너를 못 띄워 깨진다.
- 래퍼 준비(이미지 확인·기동·복사)에 desktop에서 50~60초가 든다.

검증(desktop): 래퍼로 check-system-test-prerequisites → PASS(root),
tests/system/ci-runner/provider-process-group.test.ts 1개 통과.
python3 -m unittest scripts.tests.test_verify 통과, check:ci PASS(게이트 28),
ci-workflow-generation 시험 통과. 게이트 전체(test:system 116개 포함)는 이
브랜치 끝의 merge 단계에서 돈다.
2026-11-12 00:04:05 +09:00

187 lines
11 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 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; the workflow and verify.sh both run it through
# scripts/run-in-system-container.sh (config/ci/gates.json hostEnvironment).
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(f"run: {wrapper} corepack pnpm ci:gate -- FE-GATE-013", workflow)
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_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}$")
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, 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)
(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")
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"}
temp_index = base / "index"
shutil.copy(project / ".git/index", temp_index)
sh(["git", "add", "-A"], cwd=project, env={"GIT_INDEX_FILE": str(temp_index)})
here = sh(["git", "write-tree"], cwd=project, env={"GIT_INDEX_FILE": str(temp_index)}).stdout.strip()
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)
if __name__ == "__main__":
unittest.main()