stdin을 읽는 가짜가 smoke 하나라, </dev/null을 단계 pipeline에서 빼고 smoke 호출에만 붙인 변이가 시험을 통과한다. 그 변이에서는 다른 자식이 stdin을 읽으면 실패가 다시 바깥 rc=0으로 끝난다. 가짜 gradlew가 env로 고르면 stdin을 읽게 하고, smoke가 없는 pr에서 exit 3 한 경우를 더한다. smoke 시험 둘은 이름을 자식 이름에 맞춘다. 검증(노트북, 가짜 ssh·Gradle·smoke): - smoke로 옮긴 변이: 고치기 전 시험 rc=0, 이 시험 rc=1(실패 1). - </dev/null을 뺀 변이,fd14ea428,7b0265420: 각각 rc=1(실패 5). - python3 -m unittest discover -s scripts/tests: rc=0(353개). - scripts/verify.sh docs: rc=0. Refs: REV-BE-0050
499 lines
22 KiB
Python
499 lines
22 KiB
Python
"""scripts/verify.sh `--on <호스트>`의 시험. 원격으로 보내는 패치가 추적 파일의 변경과 stage한 새 파일뿐인지,
|
|
미추적 파일이 있으면 아무것도 보내지 않고 이름을 찍고 멈추는지(rc=5), 트리 줄이 HEAD 트리와 같은지 말하는지,
|
|
index를 쓴 그 초에 같은 크기로 고친 파일도 보내는지 본다.
|
|
|
|
ssh는 가짜다. 패치를 받는 호출(`cat > /tmp/<id>.patch`)이면 받은 것을 파일에 쓰고, 원격 실행(`bash -s`)이면 입력을
|
|
버리고 0으로 끝난다. Gradle·네트워크를 쓰지 않는다. 가짜 ssh와 그 기록은 시험 repo 밖에 두어 미추적 파일로 잡히지
|
|
않게 한다.
|
|
|
|
RemoteLogTest의 ssh는 받은 명령을 이 머신에서 그대로 돌린다(HOME과 잠금 파일은 임시 경로). 원격 스크립트가 시험
|
|
repo의 clone에서 worktree를 만들고 잠금 아래에서 단계를 돌린다. 단계의 Gradle은 받은 인자를 찍는 가짜 `gradlew`다.
|
|
원격 로그의 첫 줄이 보낸 트리와 기준의 전체 해시를 적는지, 다른 프로세스가 잠금을 쥔 동안 지난 로그와 클래스 목록이
|
|
그대로인지, 기다리다 client가 끊겼거나 잠금을 얻지 못한 실행이 그것을 바꾸지 않는지, 단계와 합계가 배타 잠금 안에서
|
|
도는지, 단계의 rc가 그대로 나가는지, 단계가 stdin을 읽어도 합계·rc 줄과 그 rc로 끝나는지 본다. 잠금 대기는 Linux
|
|
`/proc/locks`의 대기 줄(`->`)로 안다.
|
|
|
|
python3 -m unittest discover -s scripts/tests
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import contextlib
|
|
import fcntl
|
|
import os
|
|
import re
|
|
import shutil
|
|
import signal
|
|
import subprocess
|
|
import tempfile
|
|
import time
|
|
import unittest
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
SCRIPT = ROOT / "scripts/verify.sh"
|
|
|
|
# The developer's global git settings (hooks, signing, excludes) must not reach the throwaway repository.
|
|
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",
|
|
}
|
|
|
|
FAKE_SSH = """#!/bin/sh
|
|
printf '%s\\n' "$*" >> "$FAKE_SSH_CALLS"
|
|
case "$2" in
|
|
"cat > "*) cat > "$FAKE_SSH_PATCH" ;;
|
|
*) cat > /dev/null ;;
|
|
esac
|
|
"""
|
|
|
|
|
|
class ThrowawayRepoTest(unittest.TestCase):
|
|
"""A repository whose first commit holds this verify.sh, a tracked document and a .gitignore for build/, and
|
|
a folder outside it for the ssh stand-in and what it keeps."""
|
|
|
|
def setUp(self) -> None:
|
|
directory = tempfile.TemporaryDirectory()
|
|
self.addCleanup(directory.cleanup)
|
|
self.repo = Path(directory.name) / "repo"
|
|
self.outside = Path(directory.name) / "outside"
|
|
self.outside.mkdir()
|
|
self.git("init", "-q", "-b", "main", str(self.repo), cwd=Path(directory.name))
|
|
(self.repo / "scripts").mkdir()
|
|
shutil.copy2(SCRIPT, self.repo / "scripts/verify.sh")
|
|
self.write("docs/guide.md", "# guide\n")
|
|
self.write(".gitignore", "build/\n")
|
|
self.git("add", "-A")
|
|
self.git("commit", "-q", "-m", "first")
|
|
self.ssh = self.outside / "ssh"
|
|
|
|
def git(self, *args: str, cwd: Path | None = None) -> str:
|
|
return subprocess.run(["git", *args], cwd=cwd or self.repo, env=GIT_ENV, check=True,
|
|
capture_output=True, text=True).stdout.strip()
|
|
|
|
def write(self, path: str, text: str) -> None:
|
|
target = self.repo / path
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
target.write_text(text, encoding="utf-8")
|
|
|
|
def working_tree(self) -> str:
|
|
"""작업 트리의 트리 해시. 빈 index에서 만들어 index의 stat 기록에 기대지 않는다."""
|
|
index = self.outside / "fresh-index"
|
|
index.unlink(missing_ok=True)
|
|
env = {**GIT_ENV, "GIT_INDEX_FILE": str(index)}
|
|
subprocess.run(["git", "add", "-A"], cwd=self.repo, env=env, check=True, capture_output=True)
|
|
return subprocess.run(["git", "write-tree"], cwd=self.repo, env=env, check=True, capture_output=True,
|
|
text=True).stdout.strip()
|
|
|
|
|
|
class RemoteVerifyTest(ThrowawayRepoTest):
|
|
|
|
def setUp(self) -> None:
|
|
super().setUp()
|
|
self.ssh.write_text(FAKE_SSH, encoding="utf-8")
|
|
self.ssh.chmod(0o755)
|
|
self.calls = self.outside / "calls"
|
|
self.patch = self.outside / "patch"
|
|
|
|
def verify(self, *extra: str) -> subprocess.CompletedProcess[str]:
|
|
env = {**GIT_ENV, "VERIFY_SSH": str(self.ssh), "VERIFY_BASE_REF": "HEAD",
|
|
"FAKE_SSH_CALLS": str(self.calls), "FAKE_SSH_PATCH": str(self.patch)}
|
|
return subprocess.run(["bash", "scripts/verify.sh", "pr", "--on", "fake", *extra], cwd=self.repo, env=env,
|
|
capture_output=True, text=True, timeout=60)
|
|
|
|
def sent_patch(self) -> str:
|
|
return self.patch.read_text(encoding="utf-8")
|
|
|
|
def test_an_untracked_file_stops_it_before_anything_is_sent(self) -> None:
|
|
self.write("probe-untracked.txt", "left behind\n")
|
|
|
|
result = self.verify()
|
|
|
|
self.assertEqual(5, result.returncode, result.stderr)
|
|
self.assertIn("probe-untracked.txt", result.stderr)
|
|
self.assertFalse(self.calls.exists(), "ssh must not be called")
|
|
|
|
def test_include_untracked_sends_the_untracked_file(self) -> None:
|
|
self.write("probe-untracked.txt", "meant to go\n")
|
|
|
|
result = self.verify("--include-untracked")
|
|
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
self.assertIn("probe-untracked.txt", self.sent_patch())
|
|
|
|
def test_a_tracked_change_is_sent_and_the_tree_line_says_it_differs_from_head(self) -> None:
|
|
self.write("docs/guide.md", "# guide\n\nchanged line\n")
|
|
|
|
result = self.verify()
|
|
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
self.assertIn("+changed line", self.sent_patch())
|
|
self.assertIn("다름", result.stderr)
|
|
|
|
def test_a_staged_new_file_is_sent(self) -> None:
|
|
self.write("docs/new.md", "# new\n")
|
|
self.git("add", "docs/new.md")
|
|
|
|
result = self.verify()
|
|
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
self.assertIn("docs/new.md", self.sent_patch())
|
|
|
|
def test_an_ignored_file_does_not_stop_it_and_is_not_sent(self) -> None:
|
|
self.write("build/output.txt", "generated\n")
|
|
|
|
result = self.verify()
|
|
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
self.assertNotIn("build/output.txt", self.sent_patch())
|
|
|
|
def test_a_file_listed_in_info_exclude_does_not_stop_it_and_is_not_sent(self) -> None:
|
|
self.write("notes/mine.txt", "personal\n")
|
|
(self.repo / ".git/info").mkdir(parents=True, exist_ok=True)
|
|
(self.repo / ".git/info/exclude").write_text("notes/\n", encoding="utf-8")
|
|
|
|
result = self.verify()
|
|
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
self.assertNotIn("notes/mine.txt", self.sent_patch())
|
|
|
|
def test_an_edit_git_sees_only_by_reading_the_file_is_sent_too(self) -> None:
|
|
"""REV-BE-0012. 같은 크기로 고친 파일의 stat이 index 기록과 같으면, git은 index 파일보다 늦지 않은 항목(racy)만
|
|
내용을 읽어 수정을 본다. 보낼 트리를 만드는 index 사본이 mtime을 잃으면 그 항목이 racy가 아니게 되어 사본의
|
|
`git add`가 수정을 빼고, 원격은 HEAD 트리를 작업 트리라며 돌린다. 프론트 #77 시험을 옮겼다."""
|
|
edited = self.repo / "docs/guide.md"
|
|
# 시각을 손으로 정해 매번 같은 결과를 낸다. ctime은 고친 초에 따라 기록과 같기도 달라서 보지 않게 한다.
|
|
self.git("config", "core.trustctime", "false")
|
|
old = int(time.time()) - 3600
|
|
os.utime(edited, (old, old))
|
|
self.git("update-index", "--refresh")
|
|
edited.write_text("# GUIDE\n", encoding="utf-8")
|
|
os.utime(edited, (old, old))
|
|
# git이 index를 쓴 그 초에 파일을 같은 크기로 고친 상태다.
|
|
os.utime(self.repo / ".git/index", (old, old))
|
|
|
|
result = self.verify()
|
|
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
self.assertIn(f"트리 {self.working_tree()[:12]}(", result.stderr)
|
|
self.assertIn("+# GUIDE", self.sent_patch())
|
|
# 진짜 index는 건드리지 않는다: 수정은 stage되지 않은 채 남는다.
|
|
self.assertEqual("docs/guide.md", self.git("diff", "--name-only"))
|
|
|
|
def test_a_clean_tree_says_it_is_the_head_tree(self) -> None:
|
|
result = self.verify()
|
|
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
self.assertIn("HEAD 트리와 같음", result.stderr)
|
|
self.assertEqual("", self.sent_patch())
|
|
|
|
|
|
# Runs here what verify.sh sends, as ssh runs a command line through the remote shell, with a home of its own
|
|
# and the stand-ins below first on the path.
|
|
RUNNING_SSH = """#!/bin/sh
|
|
shift
|
|
HOME="$FAKE_HOME" PATH="$FAKE_BIN:$PATH" exec sh -c "$*"
|
|
"""
|
|
|
|
# The load line does not hang on the host's uptime or its locale.
|
|
FAKE_UPTIME = """#!/bin/sh
|
|
echo " 09:00:00 up 1 day, load average: 0.39, 0.40, 0.41"
|
|
"""
|
|
|
|
# Stands in for Gradle in the stage: prints what it was asked and whether the lock is held exclusively (only
|
|
# then does a shared try fail), reads its stdin to the end if the test asks, and ends with the rc the test chose.
|
|
FAKE_GRADLEW = """#!/bin/sh
|
|
echo "gradle $*"
|
|
[ -z "${FAKE_STAGE_READS_STDIN:-}" ] || cat > /dev/null
|
|
if flock -n -s "$FAKE_LOCK" true; then echo "stage: lock free"; else echo "stage: lock held"; fi
|
|
exit "${FAKE_STAGE_RC:-0}"
|
|
"""
|
|
|
|
# Stands in for junit-summary.py: says whether the lock is still held and leaves a class list of this run.
|
|
FAKE_SUMMARY = """import os, subprocess, sys
|
|
free = subprocess.run(["flock", "-n", "-s", os.environ["FAKE_LOCK"], "true"]).returncode == 0
|
|
print("summary: lock free" if free else "summary: lock held")
|
|
with open(sys.argv[sys.argv.index("--classes") + 1], "w", encoding="utf-8") as classes:
|
|
classes.write("this run\\n")
|
|
"""
|
|
|
|
# Stands in for run-compose-runtime-smoke.sh: reads its stdin to the end, as `docker compose exec -T` does, and
|
|
# ends with the rc the test chose.
|
|
FAKE_SMOKE = """#!/bin/sh
|
|
cat > /dev/null
|
|
exit "${FAKE_SMOKE_RC:-0}"
|
|
"""
|
|
|
|
LEAF = ":adapter:outbound:sample"
|
|
RUN_LIMIT = 60 # seconds a run may take once nothing holds it back
|
|
|
|
HEADER = r"verify: tree {tree} base {base} {stage} \d{{4}}-\d\d-\d\dT\d\d:\d\d:\d\d[+-]\d{{4}}"
|
|
|
|
|
|
class RemoteLogTest(ThrowawayRepoTest):
|
|
"""The remote side runs on this machine: a clone of the test repository is the remote checkout, the
|
|
lock file and the home that holds ~/<log>-logs are temporary."""
|
|
|
|
def setUp(self) -> None:
|
|
super().setUp()
|
|
self.write("scripts/junit-summary.py", FAKE_SUMMARY)
|
|
self.write("scripts/run-compose-runtime-smoke.sh", FAKE_SMOKE)
|
|
self.write("scripts/ci/verify-configuration-cache.sh", "exit 0\n") # round runs it before the smoke
|
|
self.write("gradle/modules.json", f'{{"modules": [{{"gradle_path": "{LEAF}"}}]}}\n')
|
|
self.write("gradlew", FAKE_GRADLEW)
|
|
(self.repo / "gradlew").chmod(0o755)
|
|
self.git("add", "-A")
|
|
self.git("commit", "-q", "-m", "stage stand-ins")
|
|
self.base = self.git("rev-parse", "HEAD")
|
|
self.write("docs/after-base.md", "# after base\n")
|
|
self.git("add", "-A")
|
|
self.git("commit", "-q", "-m", "after the base") # so neither the base nor its tree is the HEAD's
|
|
self.remote = self.outside / "remote"
|
|
self.git("clone", "-q", str(self.repo), str(self.remote), cwd=self.outside)
|
|
self.home = self.outside / "home"
|
|
self.logs = self.home / "t-logs"
|
|
self.lock = self.outside / "gates/heavy.lock"
|
|
self.ssh.write_text(RUNNING_SSH, encoding="utf-8")
|
|
self.ssh.chmod(0o755)
|
|
self.bin = self.outside / "bin"
|
|
self.bin.mkdir()
|
|
(self.bin / "uptime").write_text(FAKE_UPTIME, encoding="utf-8")
|
|
(self.bin / "uptime").chmod(0o755)
|
|
|
|
def env(self, **extra: str) -> dict[str, str]:
|
|
return {**GIT_ENV, "VERIFY_SSH": str(self.ssh), "VERIFY_BASE_REF": self.base, "FAKE_LOCK": str(self.lock),
|
|
"VERIFY_REMOTE_REPO": str(self.remote), "VERIFY_LOCK": str(self.lock),
|
|
"FAKE_HOME": str(self.home), "FAKE_BIN": str(self.bin), **extra}
|
|
|
|
def start(self, *stage: str, stdout: object = subprocess.PIPE, stderr: object = subprocess.PIPE,
|
|
restore_signals: bool = True, **extra: str) -> subprocess.Popen[str]:
|
|
"""Starts a run in a process group of its own. When the test ends, whatever is left of it (the "remote"
|
|
side too) is killed."""
|
|
run = subprocess.Popen(["bash", "scripts/verify.sh", *(stage or ("pr",)), "--on", "fake", "--log", "t"],
|
|
cwd=self.repo, env=self.env(**extra), stdout=stdout, stderr=stderr, text=True,
|
|
restore_signals=restore_signals, start_new_session=True)
|
|
|
|
def end_the_run() -> None:
|
|
try:
|
|
run.wait(RUN_LIMIT)
|
|
finally:
|
|
with contextlib.suppress(ProcessLookupError):
|
|
os.killpg(run.pid, signal.SIGKILL)
|
|
run.wait()
|
|
for pipe in (run.stdout, run.stderr):
|
|
if pipe:
|
|
pipe.close()
|
|
|
|
self.addCleanup(end_the_run)
|
|
return run
|
|
|
|
def run_stage(self, *stage: str, **extra: str) -> subprocess.CompletedProcess[str]:
|
|
run = self.start(*stage, **extra)
|
|
out, err = run.communicate(timeout=RUN_LIMIT)
|
|
return subprocess.CompletedProcess(run.args, run.returncode, out, err)
|
|
|
|
def log(self, stage: str = "pr") -> str:
|
|
return (self.logs / f"{stage}.log").read_text(encoding="utf-8")
|
|
|
|
def keep_a_last_run(self) -> tuple[tuple[str, str], ...]:
|
|
self.logs.mkdir(parents=True)
|
|
(self.logs / "pr.log").write_text(f"verify: tree {'a' * 40} base {'b' * 40} pr\nlast run\n", encoding="utf-8")
|
|
(self.logs / "pr-classes.tsv").write_text(".\ttest\tdev.x.LastTest\t1\t0\t0\t0\t0.100\n", encoding="utf-8")
|
|
return self.log_folder()
|
|
|
|
def log_folder(self) -> tuple[tuple[str, str], ...]:
|
|
return tuple((path.name, path.read_text(encoding="utf-8")) for path in sorted(self.logs.iterdir()))
|
|
|
|
def lock_waited_on(self) -> bool:
|
|
"""Whether a process waits for the flock on the lock file: Linux lists each waiter with "->"."""
|
|
status = self.lock.stat()
|
|
key = f"{os.major(status.st_dev):02x}:{os.minor(status.st_dev):02x}:{status.st_ino}"
|
|
return any("->" in fields and fields[-3] == key
|
|
for fields in map(str.split, Path("/proc/locks").read_text(encoding="utf-8").splitlines()))
|
|
|
|
def wait_until_it_waits(self, run: subprocess.Popen[str]) -> None:
|
|
deadline = time.monotonic() + 30
|
|
while not self.lock_waited_on():
|
|
self.assertLess(time.monotonic(), deadline, "the run never waited for the lock")
|
|
self.assertIsNone(run.poll(), "the run ended without waiting for the lock")
|
|
time.sleep(0.05)
|
|
|
|
def hold_the_lock(self):
|
|
self.lock.parent.mkdir()
|
|
held = self.lock.open("w")
|
|
fcntl.flock(held, fcntl.LOCK_EX)
|
|
return held
|
|
|
|
def test_the_log_starts_with_the_full_hashes_of_the_tree_it_sent_and_its_base_then_the_load(self) -> None:
|
|
# given: a commit after the base and a change not committed, so the tree sent is neither's tree
|
|
self.write("docs/guide.md", "# guide\n\nchanged line\n")
|
|
|
|
# when
|
|
result = self.run_stage()
|
|
|
|
# then
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
header = HEADER.format(tree=self.working_tree(), base=self.base, stage="pr")
|
|
self.assertRegex(self.log(), rf"\A{header}\n"
|
|
r"verify: 09:00:00 up 1 day, load average: 0\.39, 0\.40, 0\.41\n")
|
|
|
|
def test_the_first_line_of_a_leaf_run_names_the_leaf_after_the_stage(self) -> None:
|
|
# when
|
|
result = self.run_stage("leaf", LEAF)
|
|
|
|
# then
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
header = HEADER.format(tree=self.working_tree(), base=self.base, stage=f"leaf {LEAF}")
|
|
self.assertRegex(self.log("leaf"), rf"\A{header}\n")
|
|
|
|
def test_of_two_runs_with_two_trees_the_log_names_the_tree_of_the_last_one(self) -> None:
|
|
# given: a run of the HEAD tree, then a change
|
|
first = self.working_tree()
|
|
self.assertEqual(0, self.run_stage().returncode)
|
|
self.write("docs/guide.md", "# guide\n\nchanged line\n")
|
|
|
|
# when
|
|
result = self.run_stage()
|
|
|
|
# then: the log alone tells which tree the run was
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
named = re.match(r"verify: tree (\S+) ", self.log())
|
|
self.assertEqual((named and named.group(1), first in self.log()), (self.working_tree(), False))
|
|
|
|
def test_while_another_run_holds_the_lock_the_last_log_and_class_list_stay_as_they_were(self) -> None:
|
|
# given: the last run's log and class list, and the lock held by this process
|
|
last = self.keep_a_last_run()
|
|
held = self.hold_the_lock()
|
|
run = self.start(stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
self.addCleanup(held.close) # runs first: the lock goes before the wait
|
|
self.wait_until_it_waits(run)
|
|
|
|
# when: the run waits for the lock a while
|
|
seen = set()
|
|
for _ in range(20):
|
|
seen.add(self.log_folder())
|
|
time.sleep(0.05)
|
|
|
|
# then
|
|
self.assertEqual(seen, {last})
|
|
|
|
def test_a_run_that_waits_for_the_lock_says_so_on_stderr(self) -> None:
|
|
# given
|
|
held = self.hold_the_lock()
|
|
told = self.outside / "stderr"
|
|
with told.open("w") as stderr:
|
|
run = self.start(stdout=subprocess.DEVNULL, stderr=stderr)
|
|
self.addCleanup(held.close)
|
|
|
|
# when
|
|
self.wait_until_it_waits(run)
|
|
|
|
# then
|
|
self.assertIn(f"verify: 다른 실행이 잠금 {self.lock}을 쥐고 있어 기다린다. "
|
|
"지난 로그는 잠금을 얻을 때까지 그대로다.\n", told.read_text(encoding="utf-8"))
|
|
|
|
def test_a_run_that_waited_runs_the_stage_once_the_lock_is_free_and_replaces_the_last_log(self) -> None:
|
|
# given
|
|
self.keep_a_last_run()
|
|
held = self.hold_the_lock()
|
|
run = self.start()
|
|
self.addCleanup(held.close)
|
|
self.wait_until_it_waits(run)
|
|
|
|
# when
|
|
held.close()
|
|
_, err = run.communicate(timeout=RUN_LIMIT)
|
|
|
|
# then
|
|
self.assertEqual(0, run.returncode, err)
|
|
header = HEADER.format(tree=self.working_tree(), base=self.base, stage="pr")
|
|
self.assertRegex(self.log(), rf"\A{header}\n(?:.*\n)*gradle :prCheck .*\nstage: lock held\n")
|
|
self.assertEqual("this run\n", (self.logs / "pr-classes.tsv").read_text(encoding="utf-8"))
|
|
|
|
def test_the_stage_and_the_summary_run_while_the_lock_is_held_exclusively(self) -> None:
|
|
# when
|
|
result = self.run_stage()
|
|
|
|
# then: pr asks Gradle twice
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
self.assertEqual(re.findall(r"^(?:stage|summary): lock \w+$", self.log(), re.MULTILINE),
|
|
["stage: lock held", "stage: lock held", "summary: lock held"])
|
|
|
|
def test_a_run_that_cannot_take_the_lock_ends_with_4_and_changes_nothing(self) -> None:
|
|
# given: every flock fails
|
|
last = self.keep_a_last_run()
|
|
(self.bin / "flock").write_text("#!/bin/sh\nexit 1\n", encoding="utf-8")
|
|
(self.bin / "flock").chmod(0o755)
|
|
|
|
# when
|
|
result = self.run_stage()
|
|
|
|
# then
|
|
self.assertEqual((result.returncode, self.log_folder()), (4, last), result.stderr)
|
|
|
|
def assert_a_lost_client_changes_nothing(self, restore_signals: bool) -> None:
|
|
# given: a run that waits for the lock, its output read through pipes as sshd reads it
|
|
last = self.keep_a_last_run()
|
|
held = self.hold_the_lock()
|
|
run = self.start(restore_signals=restore_signals)
|
|
self.addCleanup(held.close)
|
|
self.wait_until_it_waits(run)
|
|
|
|
# when: the client goes away, then the lock is free
|
|
run.stdout.close()
|
|
run.stderr.close()
|
|
held.close()
|
|
rc = run.wait(RUN_LIMIT)
|
|
|
|
# then: it ends before it changes anything and still removes its worktree
|
|
self.assertEqual((rc, self.log_folder(), len(self.git("worktree", "list", cwd=self.remote).splitlines())),
|
|
(4, last, 1))
|
|
|
|
def test_a_run_whose_client_left_while_it_waited_changes_nothing(self) -> None:
|
|
self.assert_a_lost_client_changes_nothing(restore_signals=True)
|
|
|
|
def test_a_run_whose_client_left_changes_nothing_where_sigpipe_is_ignored(self) -> None:
|
|
# Python ignores SIGPIPE and the run inherits that: the failed write is all that can end it.
|
|
self.assert_a_lost_client_changes_nothing(restore_signals=False)
|
|
|
|
def test_the_rc_of_the_stage_is_the_exit_and_the_last_line_of_the_log(self) -> None:
|
|
# when
|
|
result = self.run_stage(FAKE_STAGE_RC="3")
|
|
|
|
# then
|
|
self.assertEqual((result.returncode, self.log().splitlines()[-1]), (3, "verify: rc=3"), result.stderr)
|
|
|
|
def assert_a_stdin_reading_stage_ends_with(self, rc: int, stage: str, **child: str) -> None:
|
|
"""REV-BE-0050. The remote script is the stdin of `bash -s`: a stage that reads its stdin must not get
|
|
the lines after it (summary, rc line, exit)."""
|
|
# when
|
|
result = self.run_stage(stage, **child)
|
|
|
|
# then
|
|
log = self.log(stage)
|
|
end = re.search(r"^summary: .*\nverify: rc=(\d+)\n\Z", log, re.MULTILINE)
|
|
self.assertEqual((result.returncode, end and end.group(1)), (rc, str(rc)), log + result.stderr)
|
|
|
|
def test_a_smoke_that_reads_stdin_and_fails_ends_with_the_summary_and_its_rc(self) -> None:
|
|
for stage in ("nightly", "round"): # the two stages that run the smoke
|
|
with self.subTest(stage=stage):
|
|
self.assert_a_stdin_reading_stage_ends_with(3, stage, FAKE_SMOKE_RC="3")
|
|
|
|
def test_a_smoke_that_reads_stdin_and_passes_ends_with_the_summary_and_its_rc(self) -> None:
|
|
for stage in ("nightly", "round"):
|
|
with self.subTest(stage=stage):
|
|
self.assert_a_stdin_reading_stage_ends_with(0, stage, FAKE_SMOKE_RC="0")
|
|
|
|
def test_a_gradle_that_reads_stdin_and_fails_ends_with_the_summary_and_its_rc(self) -> None:
|
|
# pr has no smoke: an empty stdin given to the smoke alone does not pass this
|
|
self.assert_a_stdin_reading_stage_ends_with(3, "pr", FAKE_STAGE_READS_STDIN="1", FAKE_STAGE_RC="3")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|