fix(verify): --on 단계가 worktree를 지우기 전에 lane별 시험 클래스 목록을 남긴다 #91
@@ -70,7 +70,7 @@ Gradle·Docker는 desktop에서 공유 잠금 아래 돈다(`docs/work/operate.m
|
||||
- main 묶음: `scripts/verify.sh main --no-cache`(`:mainCheck --continue`, `:integrationCheck --continue`, `-p build-logic test`, `scripts/ci/verify-configuration-cache.sh`)
|
||||
- compose·Dockerfile: `verifyComposeProfiles`(PR 안), 실제 기동은 `scripts/verify.sh nightly`의 smoke
|
||||
- 노트북에서 되는 것: `python3 scripts/check-repo-layout.py`, `python3 -m unittest discover -s scripts/tests`
|
||||
- 결과는 `docs/work/reference/gates.md` 4절 표로 적는다: 명령 하나에 한 줄, rc, 시간, 직전 부하, executed·FROM-CACHE 수, 테스트 수(결과 XML 사본에서), 로그 경로.
|
||||
- 결과는 `docs/work/reference/gates.md` 4절 표로 적는다: 명령 하나에 한 줄, rc, 시간, 직전 부하, executed·FROM-CACHE 수, 테스트 수(`verify.sh` 단계는 합계 줄과 `<단계>-classes.tsv`, 손으로 돌린 worktree는 결과 XML 사본에서), 로그 경로.
|
||||
|
||||
## 이 repo에서 정한 것
|
||||
|
||||
|
||||
@@ -63,7 +63,7 @@ paths:
|
||||
- 새 lane: `./gradlew :verifyStrictLaneStages --dry-run`
|
||||
- 변이 확인: 버릴 worktree에서 지키려는 줄을 지우고 그 테스트가 실패하는지 본다. 커밋하지 않는다.
|
||||
- 흔들림: `--tests <클래스> --rerun`을 열 번 돌려 실패 수를 센다. 기준 커밋과 이번 트리에서 세 번씩 돌려 이번 변경 몫인지 가린다. — `docs/work/reference/gates.md` 4절
|
||||
- 테스트 수는 성공한 Gradle 로그에 없다. 결과 XML 사본에서 센다. — 같은 절
|
||||
- 테스트 수는 성공한 Gradle 로그에 없다. `verify.sh`로 보낸 단계는 로그 끝 합계 줄과 `<단계>-classes.tsv`, 손으로 돌린 worktree는 결과 XML 사본에서 센다. — 같은 절
|
||||
|
||||
## 이 repo에서 정한 것
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ description: 이 repo에서 Gradle·Docker·테스트·게이트·성능 측정
|
||||
1. 돌릴 단계를 고른다: 바꾼 것에 맞는 게이트는 `gates.md` 2절, 단계 묶음은 1절의 `scripts/verify.sh` 단계(`leaf <gradle-path>`·`pr`·`main`·`nightly`·`release`·`round`)다. leaf의 Gradle path는 registry `gradle_path`에서 읽는다.
|
||||
2. `scripts/verify.sh <단계> [--no-cache]`를 노트북 저장소 루트에서 돌린다. 스크립트가 커밋하지 않은 변경과 stage한 새 파일을 패치로 desktop에 보내고(미추적 파일이 있으면 이름을 찍고 rc=5로 멈춘다. 보낼 것이면 `git add`, 아니면 지우거나 `.git/info/exclude`에 적는다), 기준 커밋에서 새 worktree를 만들어 트리 해시를 맞추고, 공유 잠금 `flock /tmp/claude-gates/heavy.lock` 아래에서 돌리고, 로그를 desktop `~/<브랜치 이름>-logs/<단계>.log`에 남기고, worktree를 지운다. 오래 걸리는 단계는 background로 두고 끝나면 알림을 받는다.
|
||||
3. 증거로 쓸 실행은 `--no-cache`로 돌린다(`gates.md` 3절). 로그의 `FROM-CACHE`가 0인지 본다.
|
||||
4. 테스트 수는 `verify.sh`가 worktree를 지우기 전에 결과 XML에서 세어 로그 끝에 남긴다(`verify: 테스트 tests=…`). 명령별로 나눈 수가 필요하면 단계 밖에서 손으로 돌려 `gates.md` 4절대로 센다. 실패하면 기준 커밋에서도 돌려 이번 변경 몫인지 가린다(`operate.md` 7절).
|
||||
4. 테스트 수는 `verify.sh`가 worktree를 지우기 전에 결과 XML에서 세어 로그 끝에 남긴다(`verify: 테스트 tests=…`). lane(태스크)별 클래스 목록은 같은 폴더의 `<단계>-classes.tsv`다. 명령별로 나눈 수가 필요하면 단계 밖에서 손으로 돌려 `gates.md` 4절대로 센다. 실패하면 기준 커밋에서도 돌려 이번 변경 몫인지 가린다(`operate.md` 7절).
|
||||
5. 다른 세션이 잠금을 쥐고 있으면 기다린다. 기다리는 동안 다른 일을 하고, 잠금 대기는 완료나 첫 실패에서 끝나는 대기 하나로 둔다.
|
||||
6. 단계 밖의 명령(lane 하나, `spotlessApply`, 탐침)은 `operate.md` 4.1절 「절차」대로 손으로 하고, `--no-daemon`을 붙인다(오래 사는 daemon이 여러 worktree를 받으면 compiler worker가 쌓여 desktop 메모리를 채운다). desktop 기존 checkout의 브랜치와 `stash@{0}`는 건드리지 않는다.
|
||||
7. 보고에는 단계, rc, 직전 부하(로그 첫 줄), 로그 경로, 대상 트리 해시, 캐시 여부를 적는다.
|
||||
|
||||
+1
-1
@@ -57,7 +57,7 @@
|
||||
- 맨 앞에 결과(완료 / 부분 / 못 함)와 브랜치·커밋을 쓴다.
|
||||
- 그다음 변경, 확인(명령 · 실행 위치 · rc · 로그 경로), 범위 밖에서 본 것(위치와 내용, 고치지 않음), 남은 문제를 쓴다. 남은 문제를 숨기지 않는다.
|
||||
- 보고는 쉬운 한국어로 쓴다. 코드·명령·로그 인용만 원문 그대로 둔다.
|
||||
- 숫자(테스트 수, 실패 수, 태스크 이름)는 로그에서 옮긴다. 기억으로 쓰지 않는다. 테스트 수는 성공한 Gradle 로그에 없으니 결과 XML 사본에서 센다([reference/gates.md](reference/gates.md) 4절).
|
||||
- 숫자(테스트 수, 실패 수, 태스크 이름)는 로그에서 옮긴다. 기억으로 쓰지 않는다. 테스트 수는 성공한 Gradle 로그에 없다. `scripts/verify.sh`로 보낸 단계는 로그 끝 합계 줄과 `<단계>-classes.tsv`에서, 손으로 돌린 worktree는 결과 XML 사본에서 센다([reference/gates.md](reference/gates.md) 4절).
|
||||
- 착수할 때 예측(p30·p50·p80과 근거)을, 끝 보고 직전에 실측을 `docs/ledger/estimates.jsonl`에 한 줄씩 더한다(형식 `docs/ledger/README.md`).
|
||||
- 사고 순서 흔적 칸을 둔다(`conventions/work-thinking-order.md` 3절). 다른 세션이 맡긴 일이면 design-docs `conventions/delegation-loop.md` 5절 양식을 쓴다.
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ cd ~/workspace/clean-architecture-backend-template
|
||||
git worktree remove ~/workspace/<작업 이름>
|
||||
```
|
||||
|
||||
- 로그는 desktop `~/<작업 이름>-logs/`에 남기고, 보고에 그 desktop 경로와 rc를 쓴다. 같은 worktree의 다음 실행이 결과 XML을 덮어쓰니, 명령이 끝날 때마다 그 태스크의 `build/test-results/<태스크>/`를 로그 폴더로 복사한다(세는 법은 [reference/gates.md](reference/gates.md) 4절).
|
||||
- 로그는 desktop `~/<작업 이름>-logs/`에 남기고, 보고에 그 desktop 경로와 rc를 쓴다. 같은 worktree의 다음 실행이 결과 XML을 덮어쓰니, 이렇게 손으로 돌린 worktree에서는 명령이 끝날 때마다 그 태스크의 `build/test-results/<태스크>/`를 로그 폴더로 복사한다. 노트북에서 `scripts/verify.sh`로 보낸 단계는 복사하지 않는다. 합계 줄과 클래스 목록 `<단계>-classes.tsv`를 남긴다(세는 법은 [reference/gates.md](reference/gates.md) 4절).
|
||||
- RED 확인용 임시 worktree도 같은 방법으로 만들고 끝나면 지운다.
|
||||
- workflow job이 도구를 내려받아 설치하는 단계(`curl … | sh`, setup action)는 desktop에서 따라 하지 않는다. 소유자 기계를 바꾸는 일이다. 이미 설치된 도구로만 돌리고, 없으면 못 돌림으로 적는다. 도구가 실행 때 받는 데이터(trivy 취약점 DB)는 설치가 아니다. 받아도 되고, 받은 DB의 갱신 시각을 기록에 적는다.
|
||||
- compose를 띄웠으면 지우기 전에 `docker compose … down`을 한다.
|
||||
|
||||
@@ -134,7 +134,9 @@ workflow에만 있는 job: `pr.yml` `done`의 마지막 step과 `main.yml`의 `v
|
||||
- 한 줄은 명령 하나다. `verify.sh` 단계 하나는 Gradle 명령 여럿이다. 명령마다 한 줄을 쓰고 「게이트」 칸에 `main 2/4`처럼 순번을 붙인다. Gradle의 태스크 집계 줄(`BUILD SUCCESSFUL in …`, `N actionable tasks`)은 명령마다 하나씩 나오므로 단계 로그에서 명령별로 나눠 읽는다.
|
||||
- 「실제 실행」 칸은 로그의 `> Task` 줄에서 센다: executed(꼬리 없음), UP-TO-DATE, FROM-CACHE. 테스트 수는 그 명령이 새로 쓴 JUnit XML에서 센다.
|
||||
|
||||
**테스트 수 세기.** 성공한 Gradle 로그(`--console=plain`)에는 테스트 수가 찍히지 않는다. 같은 worktree의 다음 실행(특히 `--tests` 필터 실행)은 같은 leaf의 XML을 덮어쓴다. 그래서 명령이 끝날 때마다 XML을 로그 폴더로 복사하고 사본에서 센다.
|
||||
**테스트 수 세기.** 성공한 Gradle 로그(`--console=plain`)에는 테스트 수가 찍히지 않는다. 노트북에서 `scripts/verify.sh`로 desktop에 보낸 단계(`--on <호스트>`, docs 밖 단계의 기본)는 worktree를 지우기 전에 `scripts/junit-summary.py`가 결과 XML(이번 실행이 쓰거나 캐시에서 되살린 것)을 읽는다. 합계 줄(`verify: 테스트 tests=…`)은 단계 로그 끝에 쓴다. lane(태스크)별 클래스 목록은 `~/<로그 이름>-logs/<단계>-classes.tsv`에 남긴다. 한 줄이 XML 하나이고, 칸은 leaf 경로·태스크·클래스·tests·skipped·failures·errors·time이다. 이때는 XML을 복사하지 않는다.
|
||||
|
||||
`--on here`로 돌렸거나 worktree에서 Gradle을 직접 돌렸을 때만 손으로 복사한다. 같은 worktree의 다음 실행(특히 `--tests` 필터 실행)은 같은 leaf의 XML을 덮어쓴다. 그래서 명령이 끝날 때마다 XML을 로그 폴더로 복사하고 사본에서 센다.
|
||||
|
||||
```bash
|
||||
cp -r <leaf 경로>/build/test-results/<태스크> ~/<작업 이름>-logs/<명령 이름>-xml
|
||||
@@ -160,7 +162,7 @@ for k in tests skipped failures errors; do cat $(find "$x" -name 'TEST-*.xml') |
|
||||
- 못 돌린 것과 이유. 이유 없이 빠진 검증은 HARD-STOP 6 위반이다.
|
||||
- 캐시로 통과한 것. 실행 시간이 짧으면 캐시 재사용인지 적는다.
|
||||
- 집계가 뺀 lane. 입력이 없어 빠진 lane의 이름.
|
||||
- 고친 테스트가 실제로 돌았는지. 큰 집계 안에서 몇 개가 돌았는지 테스트 수로.
|
||||
- 고친 테스트가 실제로 돌았는지. 큰 집계 안에서 몇 개가 돌았는지 테스트 수로. `verify.sh`로 보낸 단계면 `<단계>-classes.tsv`에서 그 클래스의 줄(leaf·태스크·tests)을 옮긴다. 캐시에서 되살린 태스크의 XML도 줄이 되므로, 「돌았다」의 증거는 FROM-CACHE 0인 `--no-cache` 실행의 목록뿐이다.
|
||||
- 보고한 태스크가 로그에 있는지. 로그에서 태스크 이름을 grep해 확인한다.
|
||||
|
||||
## 5. 성능 lane
|
||||
|
||||
Executable
+79
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Totals the JUnit XML under a tree and lists, per lane, the test classes that ran.
|
||||
|
||||
Called by scripts/verify.sh: the script run_remote sends to the host calls it in the throwaway worktree
|
||||
after the stage, before the worktree and its XML are removed. Run on a tree of your own the same way:
|
||||
|
||||
python3 scripts/junit-summary.py <root> [--classes <out.tsv>]
|
||||
|
||||
It reads the files the former find read: TEST-*.xml anywhere below a build/test-results/ folder. stdout
|
||||
gets the total line in the form verify.sh always printed,
|
||||
|
||||
verify: 테스트 tests=N failures=N errors=N skipped=N
|
||||
|
||||
and, with --classes, one TSV row per file (leaf path, task, class, tests, skipped, failures, errors, time;
|
||||
the root project's leaf is ".") and a line naming the file. Only the root testsuite counts, so a test that
|
||||
prints "<testsuite " is not a second suite. A file that cannot be opened, does not parse to the end or whose
|
||||
counts are not numbers is named on stderr and left out of both. A row says a result file was there, not that
|
||||
the test ran in this build: a task restored FROM-CACHE puts its XML back too. The exit stays 0 either way: the stage's rc is what
|
||||
verify.sh reports, and this script only describes the run.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
|
||||
RESULTS = "/build/test-results/"
|
||||
COUNTS = ("tests", "skipped", "failures", "errors")
|
||||
|
||||
|
||||
def result_files(root: Path) -> list[str]:
|
||||
"""Paths relative to root, sorted, of every TEST-*.xml below a build/test-results/ folder."""
|
||||
found = []
|
||||
for directory, _, files in os.walk(root): # like find: symlinked folders are not followed
|
||||
relative = os.path.relpath(directory, root)
|
||||
for name in files:
|
||||
path = name if relative == "." else f"{relative}/{name}"
|
||||
if name.startswith("TEST-") and name.endswith(".xml") and RESULTS in f"/{path}":
|
||||
found.append(path)
|
||||
return sorted(found)
|
||||
|
||||
|
||||
def read(root: Path, path: str) -> list[str] | None:
|
||||
"""The TSV fields of one result file, or None when it cannot be read."""
|
||||
try:
|
||||
suite = ET.parse(root / path).getroot() # parses to the end: a file cut off after the root fails here
|
||||
counts = [int(suite.get(key, "0")) for key in COUNTS]
|
||||
except (OSError, ET.ParseError, ValueError):
|
||||
return None
|
||||
leaf, _, rest = f"/{path}".partition(RESULTS)
|
||||
return [leaf.lstrip("/") or ".", rest.split("/", 1)[0], suite.get("name", ""), *map(str, counts),
|
||||
suite.get("time", "")]
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("root", type=Path)
|
||||
parser.add_argument("--classes", type=Path, help="write one TSV row per result file here")
|
||||
args = parser.parse_args(argv)
|
||||
rows = []
|
||||
for path in result_files(args.root):
|
||||
fields = read(args.root, path)
|
||||
if fields is None:
|
||||
print(f"verify: 읽지 못한 XML {path}", file=sys.stderr)
|
||||
else:
|
||||
rows.append(fields)
|
||||
total = {key: sum(int(row[3 + i]) for row in rows) for i, key in enumerate(COUNTS)}
|
||||
print("verify: 테스트 tests={tests} failures={failures} errors={errors} skipped={skipped}".format(**total))
|
||||
if args.classes:
|
||||
args.classes.write_text("".join("\t".join(row) + "\n" for row in rows), encoding="utf-8")
|
||||
print(f"verify: 클래스 목록 {len(rows)}줄 → {args.classes}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,263 @@
|
||||
"""scripts/junit-summary.py의 시험. JUnit XML마다 TSV 한 줄(leaf, 태스크, 클래스, 숫자)을 남기는지, 합계 줄이
|
||||
scripts/verify.sh가 전에 awk로 찍던 줄과 글자 하나까지 같은지, 읽지 못한 XML을 stderr에 이름으로 찍고 합계에서
|
||||
빼며 rc를 0으로 두는지 본다. 마지막으로 verify.sh `--on <호스트>`가 원격에 보내는 스크립트가 단계 전에 지난 목록을
|
||||
지우고, rc를 받은 뒤 worktree를 지우기 전에 이 스크립트를 부르며, 그 줄이 로그 폴더에 두 파일을 남기는지 본다(ssh는
|
||||
가짜라 Gradle·네트워크를 쓰지 않는다).
|
||||
|
||||
python3 -m unittest discover -s scripts/tests
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SCRIPTS = Path(__file__).resolve().parent.parent
|
||||
SUMMARY = SCRIPTS / "junit-summary.py"
|
||||
VERIFY = SCRIPTS / "verify.sh"
|
||||
|
||||
# The total line scripts/verify.sh printed before it handed the count to junit-summary.py: its heredoc at
|
||||
# 3bfefe69 with the heredoc escapes undone (\\ -> \, \$ -> $). The new line must stay the same for the same tree.
|
||||
FORMER_AWK_TOTAL = r"""find . -path '*/build/test-results/*' -name 'TEST-*.xml' -print0 | xargs -0 -r cat \
|
||||
| grep -o '<testsuite [^>]*' \
|
||||
| awk '{ for (i = 1; i <= NF; i++) if (split($i, kv, "=") == 2) { gsub(/"/, "", kv[2]); n[kv[1]] += kv[2] } }
|
||||
END { printf "verify: 테스트 tests=%d failures=%d errors=%d skipped=%d\n", n["tests"], n["failures"], n["errors"], n["skipped"] }'
|
||||
"""
|
||||
|
||||
|
||||
def suite(name: str, tests: int, skipped: int = 0, failures: int = 0, errors: int = 0, time: str = "0.100",
|
||||
out: str = "") -> str:
|
||||
"""A result file in the form Gradle writes it, one testsuite per class."""
|
||||
return (
|
||||
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||
f'<testsuite name="{name}" tests="{tests}" skipped="{skipped}" failures="{failures}" errors="{errors}" '
|
||||
f'timestamp="2026-11-22T03:00:00.000Z" hostname="desktop" time="{time}">\n'
|
||||
' <properties/>\n'
|
||||
f' <testcase name="works()" classname="{name}" time="{time}"/>\n'
|
||||
f' <system-out><![CDATA[{out}]]></system-out>\n'
|
||||
' <system-err><![CDATA[]]></system-err>\n'
|
||||
'</testsuite>\n'
|
||||
)
|
||||
|
||||
|
||||
GRPC = "src/adapter/inbound/grpc/build/test-results"
|
||||
APP = "src/bootstrap/app/build/test-results"
|
||||
|
||||
# Two leaves, two tasks, three result files: one with a failure, one with two skips, one with an error. No
|
||||
# system-out holds "<testsuite ", which the former awk counted wherever it appeared.
|
||||
RESULTS = {
|
||||
f"{GRPC}/test/TEST-dev.caskeleton.adapter.inbound.grpc.WireTest.xml":
|
||||
suite("dev.caskeleton.adapter.inbound.grpc.WireTest", tests=3, failures=1, time="0.412"),
|
||||
f"{GRPC}/grpcContractTest/TEST-dev.caskeleton.adapter.inbound.grpc.ContractTest.xml":
|
||||
suite("dev.caskeleton.adapter.inbound.grpc.ContractTest", tests=2, skipped=2, time="0.003"),
|
||||
f"{APP}/test/TEST-dev.caskeleton.bootstrap.AppTest.xml":
|
||||
suite("dev.caskeleton.bootstrap.AppTest", tests=4, errors=1, time="1.250"),
|
||||
# Not results, so neither the former find nor the new script reads them: one outside build/test-results,
|
||||
# one inside it without the TEST- name.
|
||||
"src/bootstrap/app/src/test/resources/TEST-dev.caskeleton.bootstrap.Fixture.xml":
|
||||
suite("dev.caskeleton.bootstrap.Fixture", tests=9),
|
||||
f"{APP}/test/results.xml": suite("dev.caskeleton.bootstrap.NotAResult", tests=5),
|
||||
}
|
||||
|
||||
ROWS = (
|
||||
"src/adapter/inbound/grpc\tgrpcContractTest\tdev.caskeleton.adapter.inbound.grpc.ContractTest\t2\t2\t0\t0\t0.003\n"
|
||||
"src/adapter/inbound/grpc\ttest\tdev.caskeleton.adapter.inbound.grpc.WireTest\t3\t0\t1\t0\t0.412\n"
|
||||
"src/bootstrap/app\ttest\tdev.caskeleton.bootstrap.AppTest\t4\t0\t0\t1\t1.250\n"
|
||||
)
|
||||
TOTAL = "verify: 테스트 tests=9 failures=1 errors=1 skipped=2\n"
|
||||
|
||||
|
||||
class TreeTest(unittest.TestCase):
|
||||
|
||||
def setUp(self) -> None:
|
||||
directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(directory.cleanup)
|
||||
self.root = Path(directory.name) / "tree"
|
||||
self.root.mkdir()
|
||||
self.classes = Path(directory.name) / "pr-classes.tsv"
|
||||
|
||||
def write(self, files: dict[str, str]) -> None:
|
||||
for path, text in files.items():
|
||||
target = self.root / path
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(text, encoding="utf-8")
|
||||
|
||||
def summary(self, *extra: str) -> subprocess.CompletedProcess[str]:
|
||||
# As verify.sh calls it: from the worktree root, with the root as ".".
|
||||
return subprocess.run([sys.executable, str(SUMMARY), ".", *extra], cwd=self.root, capture_output=True,
|
||||
text=True, check=False, timeout=60)
|
||||
|
||||
|
||||
class ClassListTest(TreeTest):
|
||||
|
||||
def test_each_result_file_becomes_one_row_with_its_leaf_task_class_and_counts(self) -> None:
|
||||
# given
|
||||
self.write(RESULTS)
|
||||
|
||||
# when
|
||||
self.summary("--classes", str(self.classes))
|
||||
|
||||
# then
|
||||
self.assertEqual(self.classes.read_text(encoding="utf-8"), ROWS)
|
||||
|
||||
def test_a_result_of_the_root_project_is_listed_under_dot(self) -> None:
|
||||
# given
|
||||
self.write({"build/test-results/test/TEST-dev.caskeleton.RootTest.xml": suite("dev.caskeleton.RootTest", 1)})
|
||||
|
||||
# when
|
||||
self.summary("--classes", str(self.classes))
|
||||
|
||||
# then
|
||||
self.assertEqual(self.classes.read_text(encoding="utf-8"), ".\ttest\tdev.caskeleton.RootTest\t1\t0\t0\t0\t0.100\n")
|
||||
|
||||
def test_the_run_prints_the_total_and_where_the_class_list_went(self) -> None:
|
||||
# given
|
||||
self.write(RESULTS)
|
||||
|
||||
# when
|
||||
result = self.summary("--classes", str(self.classes))
|
||||
|
||||
# then
|
||||
self.assertEqual((result.returncode, result.stdout, result.stderr),
|
||||
(0, f"{TOTAL}verify: 클래스 목록 3줄 → {self.classes}\n", ""))
|
||||
|
||||
|
||||
class TotalLineTest(TreeTest):
|
||||
|
||||
def test_the_total_line_is_the_line_the_former_awk_pipeline_printed_for_the_same_tree(self) -> None:
|
||||
for name, files in {"three results and a non-result": RESULTS, "no result at all": {}}.items():
|
||||
with self.subTest(tree=name):
|
||||
# given
|
||||
shutil.rmtree(self.root)
|
||||
self.root.mkdir()
|
||||
self.write(files)
|
||||
former = subprocess.run(["bash", "-c", FORMER_AWK_TOTAL], cwd=self.root, capture_output=True,
|
||||
text=True, check=False, timeout=60).stdout
|
||||
|
||||
# when
|
||||
result = self.summary()
|
||||
|
||||
# then
|
||||
self.assertEqual(result.stdout, former)
|
||||
|
||||
def test_a_testsuite_tag_a_test_printed_is_not_counted(self) -> None:
|
||||
# given: the former awk would have counted this output as a second suite of five tests
|
||||
self.write({f"{APP}/test/TEST-dev.caskeleton.bootstrap.PrintsTest.xml": suite(
|
||||
"dev.caskeleton.bootstrap.PrintsTest", tests=1, out='<testsuite name="Other" tests="5" failures="5"')})
|
||||
|
||||
# when
|
||||
result = self.summary()
|
||||
|
||||
# then
|
||||
self.assertEqual(result.stdout, "verify: 테스트 tests=1 failures=0 errors=0 skipped=0\n")
|
||||
|
||||
def test_an_unreadable_file_is_named_on_stderr_and_left_out_while_the_exit_stays_zero(self) -> None:
|
||||
# given: one broken inside the root start tag, one cut off after the root started, one whose count
|
||||
# is not a number, one that cannot be opened (a link to nothing)
|
||||
broken = f"{APP}/test/TEST-dev.caskeleton.bootstrap.BrokenTest.xml"
|
||||
cut = f"{APP}/test/TEST-dev.caskeleton.bootstrap.CutTest.xml"
|
||||
gone = f"{APP}/test/TEST-dev.caskeleton.bootstrap.GoneTest.xml"
|
||||
wrong = f"{GRPC}/test/TEST-dev.caskeleton.adapter.inbound.grpc.WrongTest.xml"
|
||||
self.write({
|
||||
**RESULTS,
|
||||
broken: '<?xml version="1.0" encoding="UTF-8"?>\n<testsuite name="dev.caskeleton.bootstrap.BrokenTest" tests=',
|
||||
cut: suite("dev.caskeleton.bootstrap.CutTest", tests=7).split(" <system-out>")[0],
|
||||
wrong: suite("dev.caskeleton.adapter.inbound.grpc.WrongTest", tests=1).replace('tests="1"', 'tests="many"'),
|
||||
})
|
||||
(self.root / gone).symlink_to(self.root / "nowhere.xml")
|
||||
|
||||
# when
|
||||
result = self.summary("--classes", str(self.classes))
|
||||
|
||||
# then
|
||||
unreadable = "".join(f"verify: 읽지 못한 XML {path}\n" for path in (wrong, broken, cut, gone))
|
||||
self.assertEqual((result.returncode, result.stdout, result.stderr),
|
||||
(0, f"{TOTAL}verify: 클래스 목록 3줄 → {self.classes}\n", unreadable))
|
||||
|
||||
|
||||
# verify.sh --on <host> pipes its remote script into `ssh <host> bash -s`. This ssh keeps that script and
|
||||
# drops the patch, so the script can be read as verify.sh expanded it.
|
||||
FAKE_SSH = """#!/bin/sh
|
||||
case "$2" in
|
||||
"bash") cat > "$FAKE_SSH_SCRIPT" ;;
|
||||
*) cat > /dev/null ;;
|
||||
esac
|
||||
"""
|
||||
|
||||
GIT_ENV = {
|
||||
**os.environ,
|
||||
"GIT_CONFIG_GLOBAL": os.devnull,
|
||||
"GIT_CONFIG_NOSYSTEM": "1",
|
||||
"GIT_AUTHOR_NAME": "test",
|
||||
"GIT_AUTHOR_EMAIL": "test@example.invalid",
|
||||
"GIT_COMMITTER_NAME": "test",
|
||||
"GIT_COMMITTER_EMAIL": "test@example.invalid",
|
||||
}
|
||||
|
||||
# After the stage's rc is kept and before the script exits (its EXIT trap removes the worktree and the XML).
|
||||
SUMMARY_STEP = re.compile(
|
||||
r"\nrc=\$\{PIPESTATUS\[0\]\}\n(?:#[^\n]*\n)*"
|
||||
r"(python3 scripts/junit-summary\.py \. --classes ~/wiring-logs/pr-classes\.tsv \| tee -a ~/wiring-logs/pr\.log)\n"
|
||||
r'echo "verify: rc=\$rc" \| tee -a ~/wiring-logs/pr\.log\n'
|
||||
r"exit \$rc\n"
|
||||
)
|
||||
|
||||
|
||||
class RemoteScriptWiringTest(TreeTest):
|
||||
|
||||
def setUp(self) -> None:
|
||||
super().setUp()
|
||||
work = self.root.parent
|
||||
repo = work / "repo"
|
||||
(repo / "scripts").mkdir(parents=True)
|
||||
shutil.copy2(VERIFY, repo / "scripts/verify.sh")
|
||||
for args in (["init", "-q", "-b", "main"], ["add", "-A"], ["commit", "-q", "-m", "first"]):
|
||||
subprocess.run(["git", *args], cwd=repo, env=GIT_ENV, check=True, capture_output=True)
|
||||
ssh = work / "ssh"
|
||||
ssh.write_text(FAKE_SSH, encoding="utf-8")
|
||||
ssh.chmod(0o755)
|
||||
self.remote_script = work / "remote.sh"
|
||||
env = {**GIT_ENV, "VERIFY_SSH": str(ssh), "VERIFY_BASE_REF": "HEAD", "FAKE_SSH_SCRIPT": str(self.remote_script)}
|
||||
subprocess.run(["bash", "scripts/verify.sh", "pr", "--on", "fake", "--log", "wiring"], cwd=repo, env=env,
|
||||
check=True, capture_output=True, timeout=60)
|
||||
|
||||
def test_the_remote_script_summarises_after_keeping_the_rc_and_before_it_exits(self) -> None:
|
||||
self.assertRegex(self.remote_script.read_text(encoding="utf-8"), SUMMARY_STEP)
|
||||
|
||||
def test_the_remote_script_drops_the_last_class_list_before_the_stage_runs(self) -> None:
|
||||
# A stage cut off before the summary must not leave the last run's list beside its new log.
|
||||
self.assertRegex(
|
||||
self.remote_script.read_text(encoding="utf-8"),
|
||||
r"\nmkdir -p [^\n]* ~/wiring-logs\nrm -f ~/wiring-logs/pr-classes\.tsv(?: #[^\n]*)?\n(?:[^\n]*\n)*?"
|
||||
r"VERIFY_LOCKED=1 flock ",
|
||||
)
|
||||
|
||||
def test_the_summary_line_it_sends_leaves_the_class_list_and_the_total_in_the_log_folder(self) -> None:
|
||||
# given: the line as sent, run from a worktree that holds the results, with a home of its own
|
||||
line = SUMMARY_STEP.search(self.remote_script.read_text(encoding="utf-8")).group(1)
|
||||
self.write(RESULTS)
|
||||
(self.root / "scripts").mkdir()
|
||||
shutil.copy2(SUMMARY, self.root / "scripts/junit-summary.py")
|
||||
home = self.root.parent / "home"
|
||||
(home / "wiring-logs").mkdir(parents=True)
|
||||
|
||||
# when
|
||||
subprocess.run(["bash", "-c", line], cwd=self.root, env={**os.environ, "HOME": str(home)}, check=True,
|
||||
capture_output=True, timeout=60)
|
||||
|
||||
# then
|
||||
logs = home / "wiring-logs"
|
||||
self.assertEqual(
|
||||
((logs / "pr-classes.tsv").read_text(encoding="utf-8"), (logs / "pr.log").read_text(encoding="utf-8")),
|
||||
(ROWS, f"{TOTAL}verify: 클래스 목록 3줄 → {logs / 'pr-classes.tsv'}\n"),
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+4
-6
@@ -167,15 +167,13 @@ if [ -s /tmp/$id.patch ]; then git apply --binary --index /tmp/$id.patch || exit
|
||||
got=\$(git write-tree)
|
||||
if [ "\$got" != "$tree" ]; then echo "트리 해시가 다르다: 원격 \$got, 여기 $tree" >&2; exit 4; fi
|
||||
mkdir -p "\$(dirname $LOCK)" ~/$log-logs
|
||||
rm -f ~/$log-logs/$stage-classes.tsv # 단계가 합계 전에 끊겨도 지난 실행의 목록이 새 로그 옆에 남지 않는다
|
||||
echo "verify: \$(uptime)" >&2
|
||||
VERIFY_LOCKED=1 flock $LOCK ./scripts/verify.sh $stage $target --on here ${NO_CACHE[*]} 2>&1 | tee ~/$log-logs/$stage.log
|
||||
rc=\${PIPESTATUS[0]}
|
||||
# 새 worktree라 여기 있는 JUnit XML은 모두 이번 실행의 것이다. worktree를 지우기 전에 센다.
|
||||
find . -path '*/build/test-results/*' -name 'TEST-*.xml' -print0 | xargs -0 -r cat \\
|
||||
| grep -o '<testsuite [^>]*' \\
|
||||
| awk '{ for (i = 1; i <= NF; i++) if (split(\$i, kv, "=") == 2) { gsub(/"/, "", kv[2]); n[kv[1]] += kv[2] } }
|
||||
END { printf "verify: 테스트 tests=%d failures=%d errors=%d skipped=%d\\n", n["tests"], n["failures"], n["errors"], n["skipped"] }' \\
|
||||
| tee -a ~/$log-logs/$stage.log
|
||||
# 새 worktree라 여기 있는 JUnit XML은 모두 이번 실행의 것이다. worktree를 지우면 XML도 사라지므로 그 전에 합계를
|
||||
# 로그에 쓰고, lane(태스크)별로 돈 클래스 목록을 로그 폴더에 남긴다(docs/work/reference/gates.md 4절).
|
||||
python3 scripts/junit-summary.py . --classes ~/$log-logs/$stage-classes.tsv | tee -a ~/$log-logs/$stage.log
|
||||
echo "verify: rc=\$rc" | tee -a ~/$log-logs/$stage.log
|
||||
exit \$rc
|
||||
EOF
|
||||
|
||||
Reference in New Issue
Block a user