diff --git a/bin/deploy_release/ci_script.py b/bin/deploy_release/ci_script.py index 86f3143b..4463647c 100644 --- a/bin/deploy_release/ci_script.py +++ b/bin/deploy_release/ci_script.py @@ -29,7 +29,7 @@ def ci_runner(log: pathlib.Path, seconds: float, say: Say, container: str, remov def run(worktree: pathlib.Path) -> CiRan | Failure: say(f"ci.sh's output goes to {log}; it is stopped where it still runs after {lasting(seconds)}") try: - with log.open("w", encoding="utf-8") as output: + with log.open("wb") as output: # In a session of its own, ci.sh and each process it starts share one process group, which `stopped` ends whole. process = subprocess.Popen(["sh", "ci.sh"], cwd=worktree, stdin=subprocess.DEVNULL, stdout=output, stderr=subprocess.STDOUT, start_new_session=True, env={**os.environ, CONTAINER: container}) try: @@ -75,4 +75,5 @@ def removed_container(container: str, run: typing.Callable[..., subprocess.Compl def lasting(seconds: float) -> str: - return f"{seconds / 60:g} minutes" if seconds >= 60 else f"{seconds:g} seconds" + count, unit = (seconds / 60, "minute") if seconds >= 60 else (seconds, "second") + return f"{count:g} {unit}{'' if count == 1 else 's'}" diff --git a/bin/deploy_release/test_deploy_release.py b/bin/deploy_release/test_deploy_release.py index c80974b0..086774d2 100644 --- a/bin/deploy_release/test_deploy_release.py +++ b/bin/deploy_release/test_deploy_release.py @@ -1,12 +1,16 @@ +import contextlib import datetime import io import json import os import pathlib +import signal import subprocess import sys import tempfile +import threading import time +import typing import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -497,6 +501,15 @@ class Cut(unittest.TestCase): self.plan_patch() self.assertEqual(cut.ready_release(str(self.clone), "origin/main"), cut.Ready((0, 1, 1), reviewed=False)) + def test_says_why_no_release_is_ready_where_nothing_has_landed_or_no_release_is_named_and_reviewed(self): + self.commit({"CHANGELOG.md": "# Changelog\n\n## 0.4.0\n\n- Second.\n\n## 0.1.0\n\n- First.\n", "todo.md": TODO}, "Cut release 0.4.0") + self.git(self.clone, "tag", "-a", "v0.4.0", "-m", "Cut release 0.4.0") + self.git(self.clone, "push", "-q", "origin", "main", "--tags") + self.assertEqual(cut.ready_release(str(self.clone), "origin/main"), Failure("every change is released already: nothing has landed since the last release cut")) + self.commit({"CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Third.\n\n## 0.4.0\n\n- Second.\n\n## 0.1.0\n\n- First.\n"}, "Ship a third change") + self.git(self.clone, "push", "-q", "origin", "main") + self.assertEqual(cut.ready_release(str(self.clone), "origin/main"), Failure("the release review of the next release hasn't landed")) + def test_refuses_before_any_change_where_mains_changelog_has_no_unreleased_heading(self): ran = self.cut_patch(self.plan_patch({"CHANGELOG.md": "# Changelog\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n"})) self.assertEqual(ran.returncode, 1) @@ -726,6 +739,22 @@ def still_runs(pid: int) -> bool: return False +@contextlib.contextmanager +def typed(text: bytes) -> typing.Iterator[None]: + """This process's stdin holding text, as a terminal someone typed it at would, for what a child inherits.""" + kept = os.dup(0) + reading, writing = os.pipe() + os.write(writing, text) + os.close(writing) + os.dup2(reading, 0) + os.close(reading) + try: + yield + finally: + os.dup2(kept, 0) + os.close(kept) + + class PatchCi(unittest.TestCase): """The patch's ci.sh run, read in-process with the runner handed in, and the runner itself on a real ci.sh.""" @@ -779,6 +808,52 @@ class PatchCi(unittest.TestCase): time.sleep(0.05) self.assertFalse(still_runs(child), "the process ci.sh started still runs") + def test_the_runner_kills_a_stopped_ci_sh_that_ignores_the_interrupt_once_its_grace_has_passed(self): + (self.worktree / "ci.sh").write_text("trap '' INT\necho started\nsleep 60\n") + began = time.monotonic() + ran = ci_script.ci_runner(self.log, 0.5, self.said.append, "ci-of-a-test", self.remove, grace=0.2)(self.worktree) + self.assertLess(time.monotonic() - began, 20) + self.assertEqual(ran, Failure(f"ci.sh still ran after 0.5 seconds and was stopped; {self.log} holds its output")) + self.assertEqual(self.removed, ["ci-of-a-test"]) + + def test_the_runner_stops_ci_sh_and_removes_its_container_where_the_cut_is_interrupted(self): + (self.worktree / "ci.sh").write_text("trap '' INT\necho started\nsleep 60\n") + def interrupt_once_ci_sh_runs(): + while not (self.log.exists() and self.log.read_bytes()): + time.sleep(0.02) + os.kill(os.getpid(), signal.SIGINT) + began = time.monotonic() + threading.Thread(target=interrupt_once_ci_sh_runs, daemon=True).start() + with self.assertRaises(KeyboardInterrupt): + ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove, grace=0.2)(self.worktree) + self.assertLess(time.monotonic() - began, 20) + self.assertEqual(self.removed, ["ci-of-a-test"]) + + def test_stopping_a_ci_sh_that_ended_already_still_removes_its_container(self): + process = subprocess.Popen(["true"], start_new_session=True) + process.wait() + self.assertIsNone(ci_script.stopped(process, 0.2, "ci-of-a-test", self.remove)) + self.assertEqual(self.removed, ["ci-of-a-test"]) + + def test_the_runner_gives_ci_sh_no_input_to_wait_for(self): + (self.worktree / "ci.sh").write_text('read line\necho "read: $line"\n') + with typed(b"typed\n"): + ran = ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree) + self.assertEqual(ran, patch.CiRan(0, "read: \n")) + + def test_the_runner_gives_output_that_is_not_utf_8_with_each_such_byte_replaced(self): + (self.worktree / "ci.sh").write_text("printf 'caf\\351 ok\\n'\n") + ran = ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree) + self.assertEqual(ran, patch.CiRan(0, "caf\ufffd ok\n")) + + def test_the_runner_says_its_bound_in_minutes_from_a_minute_up(self): + (self.worktree / "ci.sh").write_text("exit 0\n") + for seconds, lasting in ((1800, "30 minutes"), (60, "1 minute"), (59, "59 seconds"), (1, "1 second")): + with self.subTest(seconds=seconds): + self.said.clear() + ci_script.ci_runner(self.log, seconds, self.said.append, "ci-of-a-test", self.remove)(self.worktree) + self.assertEqual(self.said, [f"ci.sh's output goes to {self.log}; it is stopped where it still runs after {lasting}"]) + def test_the_runner_names_ci_shs_container_and_removes_it_where_it_stops_ci_sh(self): (self.worktree / "ci.sh").write_text('echo "$CI_CONTAINER"\nsleep 60\n') ran = ci_script.ci_runner(self.log, 0.5, self.said.append, "ci-of-a-test", self.remove, grace=0.2)(self.worktree) @@ -809,6 +884,24 @@ class PatchCi(unittest.TestCase): raise FileNotFoundError("docker") self.assertEqual(ci_script.removed_container("ci-of-a-test", no_docker), Failure("docker rm --force ci-of-a-test failed: docker")) + def test_removing_a_container_gives_dockers_own_error_and_no_input_to_wait_for(self): + fake = self.worktree / "fake-bin" + fake.mkdir() + (fake / "docker").write_text('#!/bin/sh\nread line\necho "no daemon for $*, read: $line" >&2\nexit 1\n') + (fake / "docker").chmod(0o755) + found_first = lambda argv, **options: subprocess.run(argv, env={**os.environ, "PATH": f"{fake}:{os.environ['PATH']}"}, **options) + with typed(b"typed\n"): + left = ci_script.removed_container("ci-of-a-test", found_first) + self.assertEqual(left, Failure("docker rm --force ci-of-a-test failed: no daemon for rm --force ci-of-a-test, read:")) + + def test_removing_a_container_gives_a_failure_where_docker_takes_longer_than_a_minute(self): + def slow_docker(argv, **options): + raise subprocess.TimeoutExpired(argv, options["timeout"]) + left = ci_script.removed_container("ci-of-a-test", slow_docker) + self.assertIsInstance(left, Failure) + self.assertTrue(left.reason.startswith("docker rm --force ci-of-a-test failed: "), left.reason) + self.assertIn("timed out after 60 seconds", left.reason) + def test_ci_sh_names_its_container_only_where_it_is_given_a_name(self): script = (pathlib.Path(__file__).resolve().parents[2] / "ci.sh").read_text() self.assertIn('${CI_CONTAINER:+--name "$CI_CONTAINER"}', script) @@ -851,6 +944,14 @@ class Trace(unittest.TestCase): self.assertEqual(out.getvalue(), "deploy-release: pushed the tag v0.2.0\ndeploy-release: merged pull request 3\n") self.assertEqual(file.read_text(), "2026-11-27T09:30:05 deploy-release --cut\n2026-11-27T09:30:05 pushed the tag v0.2.0\n2026-11-27T09:30:05 merged pull request 3\n") + def test_starts_a_later_runs_trace_beside_the_earlier_one(self): + folder = self.temp / "state" / "deploy-release" + first = trace.started(folder, "first", "deploy-release --cut", self.now) + second = trace.started(folder, "second", "deploy-release --cut-patch a..b", self.now) + self.assertEqual((first, second), (folder / "first.log", folder / "second.log")) + self.assertEqual(second.read_text(), "2026-11-27T09:30:05 deploy-release --cut-patch a..b\n") + self.assertEqual(first.read_text(), "2026-11-27T09:30:05 deploy-release --cut\n") + def test_a_trace_that_cannot_be_started_is_a_failure_naming_the_file(self): (self.temp / "state").write_text("a file where the folder goes\n") made = trace.started(self.temp / "state" / "deploy-release", "run", "deploy-release --cut", self.now) @@ -888,7 +989,18 @@ class Rewritten(unittest.TestCase): failed = cut.rewritten(file, "head CHANGELOG.md with ## 0.1.1, so nothing is tagged", lambda text: "new\n") self.assertIsInstance(failed, Failure) self.assertTrue(failed.reason.startswith("could not head CHANGELOG.md with ## 0.1.1, so nothing is tagged: "), failed.reason) - self.assertIn(str(file), failed.reason) + self.assertEqual(failed.reason.count(str(file)), 1, failed.reason) + self.assertTrue(failed.reason.endswith(f"'{file}'"), failed.reason) + + def test_a_file_that_is_not_utf_8_is_a_failure_naming_the_step_and_the_file(self): + file = self.temp / "CHANGELOG.md" + file.write_bytes(b"caf\xe9\n") + failed = cut.rewritten(file, "head CHANGELOG.md", lambda text: "new\n") + self.assertIsInstance(failed, Failure) + self.assertTrue(failed.reason.startswith("could not head CHANGELOG.md: "), failed.reason) + self.assertTrue(failed.reason.endswith(f" ({file})"), failed.reason) + self.assertEqual(failed.reason.count(str(file)), 1, failed.reason) + self.assertEqual(file.read_bytes(), b"caf\xe9\n") def test_gives_the_rewrites_own_failure_and_leaves_the_file(self): file = self.temp / "CHANGELOG.md" diff --git a/bin/release_plan/test_release_standing.py b/bin/release_plan/test_release_standing.py index fe4e477b..6fca40f4 100644 --- a/bin/release_plan/test_release_standing.py +++ b/bin/release_plan/test_release_standing.py @@ -356,6 +356,31 @@ class ChunkItem(unittest.TestCase): self.assertEqual(held.cut, release_standing.LastCut("v0.1.0", "# Changelog\n\n## 0.2.0 - 2026-10-03\n", 1, [HEADER + ROW.format(id=1, release="0.2.0")], frozenset())) self.assertEqual(release_standing.chunk_item(plan_under((0, 2, 0)), held.cut), release_standing.Next((0, 2, 0), one((0, 2, 0)))) + def test_reads_the_plan_as_the_last_tag_holds_it_and_as_each_later_commit_left_it(self): + repo = tempfile.mkdtemp() + self.addCleanup(subprocess.run, ["rm", "-rf", repo]) + run = lambda *args: subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=repo, env=isolated_env(), text=True) + run("init", "-q", "-b", "main") + before, tagged, after = (HEADER + ROW.format(id=1, release=release) for release in ("0.1.0", "0.2.0", "0.3.0")) + for text, title in ((before, "Plan 0.1.0"), (tagged, "Plan 0.2.0")): + pathlib.Path(repo, "todo.md").write_text(text) + run("add", "todo.md") + run("commit", "-q", "-m", title) + run("tag", "v0.1.0") + pathlib.Path(repo, "todo.md").write_text(after) + run("commit", "-q", "-am", "Plan 0.3.0") + self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut.todos_since, [tagged, after]) + + def test_gives_gits_own_failure_as_the_reviews_where_the_tags_cannot_be_read(self): + repo = tempfile.mkdtemp() + self.addCleanup(subprocess.run, ["rm", "-rf", repo]) + run = lambda *args: subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=repo, env=isolated_env(), text=True) + run("init", "-q", "-b", "main") + run("commit", "-q", "--allow-empty", "-m", "Release review of 0.2.0") + no_tags = lambda *args, cwd: Failure("git tag failed: no tags") if "tag" in args else release_standing.git(*args, cwd=cwd) + cut = release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE, no_tags).cut + self.assertEqual((cut.tag, cut.reviews), (Failure("git tag failed: no tags"), Failure("git tag failed: no tags"))) + def test_reads_a_plan_and_a_changelog_outside_the_checkout_as_they_stand(self): repo, folder = tempfile.mkdtemp(), pathlib.Path(tempfile.mkdtemp()) self.addCleanup(subprocess.run, ["rm", "-rf", repo, str(folder)]) diff --git a/bin/task_bench/test_task_bench.py b/bin/task_bench/test_task_bench.py index 8a406b39..9d0c1d1c 100644 --- a/bin/task_bench/test_task_bench.py +++ b/bin/task_bench/test_task_bench.py @@ -560,6 +560,14 @@ class RunOutcomesTest(unittest.TestCase): task = dataclasses.replace(self.task, trees={"base": str(self.folder / "gone"), "head": str(self.tree)}) self.assertFailsWith(main.fixed(task, "base", 1, self.containers(), self.folder, main.BUG), "could not copy bug 1's tree at the base: ") + def test_a_stream_that_cannot_be_read_after_the_fix_fails_the_bench_naming_the_stream(self): + stream = self.folder / "runs" / "bug-1-base-1.jsonl" + def removing_the_stream(args, *, seconds, stdin=None, stdout=None, stderr=None): + stream.unlink(missing_ok=True) + return Ran(0, "") + containers = dataclasses.replace(self.containers(), docker=removing_the_stream) + self.assertFailsWith(main.fixed(self.task, "base", 1, containers, self.folder, main.BUG), f"could not read {stream}: ") + def test_failing_to_make_the_tree_that_checks_a_fix_fails_the_bench_naming_the_bug_and_side(self): (self.folder / "check").mkdir() self.assertFailsWith(main.fixed(self.task, "base", 1, self.containers(Ran(0, "")), self.folder, main.BUG), "could not make the tree that checks bug 1's fix at the base: ")