Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions scripts/ci/validate_test_execution_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,15 +245,18 @@ def comparison_point(base_sha: str, root: Path = ROOT) -> str:
return merge_base(base_sha, root) or base_sha


def register_derivable(root: Path = ROOT) -> list[str]:
"""Append an entry for each unregistered test a workflow already runs; return their paths."""
def register_derivable(root: Path = ROOT, only: set[str] | None = None) -> list[str]:
"""Append an entry for each unregistered test a workflow already runs; return their paths.
With `only`, consider just those repository-relative paths: the pre-commit hook passes the
commit's own tests, so it never writes the base's unregistered ones into a pull request."""
manifest = root / "tests" / "test-execution.toml"
workflows = root / ".github" / "workflows"
registered = {entry.get("path") for entry in load_registry(manifest)}
discovered = sorted(
path.relative_to(root).as_posix() for path in (root / "tests").glob("test_*.py") if path.is_file()
)
added = [path for path in discovered if path not in registered and workflow_running(path, workflows)]
added = [path for path in discovered
if path not in registered and (only is None or path in only) and workflow_running(path, workflows)]
if added:
text = manifest.read_text(encoding="utf-8")
blocks = "".join(f'\n[[test]]\npath = "{path}"\nlane = "{DIRECT_RUN_LANE}"\n' for path in added)
Expand Down Expand Up @@ -474,12 +477,14 @@ def main(argv: list[str]) -> int:
)
parser.add_argument("--write", action="store_true",
help="register unregistered tests a workflow already runs, then validate")
parser.add_argument("--only", action="append", default=None, metavar="PATH",
help="with --write, register only these tests (repeatable)")
args = parser.parse_args(argv)
root = args.repo_root.resolve()

if args.write:
try:
for path in register_derivable(root):
for path in register_derivable(root, set(args.only) if args.only is not None else None):
print(f"registered {path} on lane {DIRECT_RUN_LANE}")
except (OSError, ValueError) as error:
print(error, file=sys.stderr)
Expand Down
16 changes: 15 additions & 1 deletion scripts/git-hooks/pre-commit
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,24 @@ cd "$REPO_ROOT"

# Register new Python tests that a workflow already runs, so adding a test and
# its ci-guards.yml step is all a commit needs. Best effort: CI still validates.
# Only this commit's tests: the ones it adds, and the ones its workflow changes
# name. Registering every unregistered test the base carries wrote the same
# entries into every pull request, which then conflicted (#21946).
REGISTRY="tests/test-execution.toml"
if git diff --cached --name-only --diff-filter=ACMRT | grep -Eq '^(tests/test_[^/]+\.py|\.github/workflows/.+)$' \
&& git diff --quiet -- "$REGISTRY"; then
"$PYTHON3_BIN" -I "$REGISTRY_VALIDATOR" --repo-root "$REPO_ROOT" --write >/dev/null 2>&1 || true
OWN_TESTS=()
while IFS= read -r test_path; do
[[ -n "$test_path" ]] && OWN_TESTS+=(--only "$test_path")
done < <(
{
git diff --cached --name-only --diff-filter=A -- 'tests/test_*.py'
git diff --cached -U0 -- .github/workflows | grep -E '^\+' | grep -oE 'tests/test_[A-Za-z0-9_]+\.py' || true
Comment thread
teamleaderleo marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Some test names get skipped

The workflow matcher excludes supported test names containing - or .. If a commit adds a workflow line for an existing unregistered tests/test_foo-bar.py, the hook finds no path and leaves it unregistered. The old hook registered these tests; contributors now need to do that manually.

Use the validator's [A-Za-z0-9_.-]+ filename pattern here too.

Suggested change
git diff --cached -U0 -- .github/workflows | grep -E '^\+' | grep -oE 'tests/test_[A-Za-z0-9_]+\.py' || true
git diff --cached -U0 -- .github/workflows | grep -E '^\+' | grep -oE 'tests/test_[A-Za-z0-9_.-]+\.py' || true

} | sort -u
)
if (( ${#OWN_TESTS[@]} > 0 )); then
"$PYTHON3_BIN" -I "$REGISTRY_VALIDATOR" --repo-root "$REPO_ROOT" --write "${OWN_TESTS[@]}" >/dev/null 2>&1 || true
fi
if ! git diff --quiet -- "$REGISTRY"; then
git add "$REGISTRY"
echo "pre-commit: registered new tests in $REGISTRY"
Expand Down
14 changes: 14 additions & 0 deletions tests/test_ci_test_execution_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,20 @@ def test_a_test_a_workflow_runs_through_a_workload_profile_is_live(self) -> None
errors, _, _ = validator.validate(root, added=set())
self.assertEqual(errors, [])

def test_write_only_registers_the_named_tests(self) -> None:
"""The pre-commit hook passes only the commit's own tests (#21946): registering every
unregistered test the base carries wrote the same entries into every pull request."""
root = self.make_root(tests=["test_kept.py", "test_base.py", "test_mine.py"], registry=self.kept_registry())
workflow = root / ".github" / "workflows" / "ci-guards.yml"
workflow.write_text(
GUARD_WORKFLOW + " - run: python3 tests/test_base.py\n - run: python3 tests/test_mine.py\n",
encoding="utf-8",
)

self.assertEqual(validator.register_derivable(root, only={"tests/test_mine.py"}), ["tests/test_mine.py"])
self.assertEqual(validator.register_derivable(root, only=set()), [])
self.assertEqual(validator.register_derivable(root), ["tests/test_base.py"]) # unrestricted, as before

def test_write_leaves_a_test_no_workflow_runs_for_a_person_to_place(self) -> None:
root = self.make_root(tests=["test_kept.py", "test_orphan.py"], registry=self.kept_registry())
before = (root / "tests" / "test-execution.toml").read_text(encoding="utf-8")
Expand Down
57 changes: 57 additions & 0 deletions tests/test_install_git_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,63 @@ def run_pre_commit(self, env):
hook = Path(self.local_hooks_path()) / "pre-commit"
return subprocess.run([str(hook)], cwd=self.repo, env=env, text=True, capture_output=True)

def test_pre_commit_registers_only_the_commits_own_tests(self):
"""The base carried an unregistered test; the hook wrote it into whichever pull request
committed a test next, so unrelated pull requests conflicted on the registry (#21946)."""
self.assertEqual(self.install().returncode, 0)
workflow = self.repo / ".github/workflows/ci-guards.yml"
workflow.parent.mkdir(parents=True, exist_ok=True)
workflow.write_text(
"name: CI guards\njobs:\n workflow-guard-tests:\n steps:\n"
" - run: python3 tests/test_kept.py\n"
" - run: python3 tests/test_base.py\n - run: python3 tests/test_mine.py\n",
encoding="utf-8",
)
registry = self.repo / "tests/test-execution.toml"
registry.parent.mkdir(parents=True, exist_ok=True)
registry.write_text('version = 1\n\n[[test]]\npath = "tests/test_kept.py"\nlane = "linux-guard"\n',
encoding="utf-8")
for name in ("test_kept.py", "test_base.py"):
(self.repo / "tests" / name).write_text("#!/usr/bin/env python3\n", encoding="utf-8")
self.git("add", "-A")
self.git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "--quiet", "--no-verify", "-m", "base")

(self.repo / "tests/test_mine.py").write_text("#!/usr/bin/env python3\n", encoding="utf-8")
self.git("add", "tests/test_mine.py")
result = subprocess.run([str(Path(self.local_hooks_path()) / "pre-commit")], cwd=self.repo,
env=self.env, text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
text = registry.read_text(encoding="utf-8")
self.assertIn('path = "tests/test_mine.py"', text)
self.assertNotIn("tests/test_base.py", text)

def test_pre_commit_registers_a_test_its_workflow_change_names(self):
"""A commit that only adds a workflow line for an existing test registers that test, and
still not the base's other unregistered one (#21946)."""
self.assertEqual(self.install().returncode, 0)
workflow = self.repo / ".github/workflows/ci-guards.yml"
workflow.parent.mkdir(parents=True, exist_ok=True)
base_workflow = ("name: CI guards\njobs:\n workflow-guard-tests:\n steps:\n"
" - run: python3 tests/test_kept.py\n - run: python3 tests/test_base.py\n")
workflow.write_text(base_workflow, encoding="utf-8")
registry = self.repo / "tests/test-execution.toml"
registry.parent.mkdir(parents=True, exist_ok=True)
registry.write_text('version = 1\n\n[[test]]\npath = "tests/test_kept.py"\nlane = "linux-guard"\n',
encoding="utf-8")
for name in ("test_kept.py", "test_base.py", "test_mine.py"):
(self.repo / "tests" / name).write_text("#!/usr/bin/env python3\n", encoding="utf-8")
self.git("add", "-A")
self.git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "--quiet", "--no-verify", "-m", "base")

workflow.write_text(base_workflow + " - run: python3 tests/test_mine.py\n", encoding="utf-8")
self.git("add", ".github/workflows/ci-guards.yml")
result = subprocess.run([str(Path(self.local_hooks_path()) / "pre-commit")], cwd=self.repo,
env=self.env, text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
text = registry.read_text(encoding="utf-8")
self.assertIn('path = "tests/test_mine.py"', text)
self.assertNotIn("tests/test_base.py", text)

def test_pre_commit_formats_rust_outside_cmux_tui_with_its_edition(self):
self.assertEqual(self.install().returncode, 0)
source = self.stage_rust_package("Native/OptChat/probe", "2024")
Expand Down