diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index a1bc7af..c92dd41 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -42,8 +42,8 @@ jobs: - name: Validate benchmark definitions run: python benchmark/validate_definitions.py - # Fails if a tracked benchmark/test_*.py file is not accounted for in - # the explicit list below (missing, stale, duplicated, or out of scope). + # Fails if a tracked Python or shell test is not accounted for in the + # explicit lists below (missing, stale, duplicated, or out of scope). - name: Check test list coverage run: python tests/validate_ci_test_coverage.py @@ -59,6 +59,7 @@ jobs: benchmark/test_proteobench_compare.py \ benchmark/test_recover_nightly_results.py \ benchmark/test_runner_timestamps.py \ + benchmark/test_validate_ci_test_coverage.py \ benchmark/report/test_generic_renderer.py \ benchmark/report/test_v2_schema.py; do echo "== python $f" diff --git a/benchmark/test_validate_ci_test_coverage.py b/benchmark/test_validate_ci_test_coverage.py new file mode 100644 index 0000000..81eaf8f --- /dev/null +++ b/benchmark/test_validate_ci_test_coverage.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +"""Tests for the Python and shell CI test coverage guard.""" + +import contextlib +import importlib.util +import io +import tempfile +from pathlib import Path +from unittest import mock + +HERE = Path(__file__).resolve().parent +GUARD_PATH = HERE.parent / "tests" / "validate_ci_test_coverage.py" +SPEC = importlib.util.spec_from_file_location("validate_ci_test_coverage", GUARD_PATH) +guard = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(guard) + + +def fixture_workflow(run, shell="bash"): + indented_run = "".join(f" {line}\n" for line in run.splitlines()) + return f""" +jobs: + tests: + steps: + - name: {guard.SHELL_WORKFLOW_STEP} + shell: {shell} + run: | +{indented_run}""" + + +def parse_shell_fixture(run, shell="bash"): + with tempfile.TemporaryDirectory() as tmp: + workflow = Path(tmp) / "workflow.yml" + workflow.write_text(fixture_workflow(run, shell), encoding="utf-8") + with mock.patch.object(guard, "WORKFLOW", workflow): + return guard.configured_shell_tests() + + +def expect_fatal(run, shell="bash"): + stderr = io.StringIO() + try: + with contextlib.redirect_stderr(stderr): + parse_shell_fixture(run, shell) + except SystemExit as exc: + assert exc.code == 2, exc.code + return stderr.getvalue() + raise AssertionError("expected guard configuration failure") + + +def test_shell_fixture_parser(): + tests = parse_shell_fixture( + "# Shell contract tests stay explicit for the coverage guard.\n" + "set -euo pipefail\n" + "bash benchmark/test_one.sh\n" + " # Keep related workflow checks together.\n" + "bash tests/test_two.sh" + ) + assert tests == ["benchmark/test_one.sh", "tests/test_two.sh"], tests + + message = expect_fatal( + "set -euo pipefail\nfor f in tests/test_one.sh; do bash \"$f\"; done" + ) + assert "unexpected command" in message, message + + message = expect_fatal("set -euo pipefail\nsh tests/test_one.sh") + assert "expected one 'bash '" in message, message + + message = expect_fatal("set -euo pipefail\nbash tests/test_one.sh|tee") + assert "unexpected shell operator" in message, message + + message = expect_fatal("set -euo pipefail\nbash tests/test_one.sh", shell="sh") + assert "must declare shell: bash" in message, message + print("PASS: shell workflow parser allows comments and explicit bash entries") + + +def test_shell_mismatch_classes(): + expected = ["benchmark/test_one.sh", "tests/test_two.sh"] + configured = [ + "benchmark/test_one.sh", + "benchmark/test_one.sh", + "tests/test_missing.sh", + "scripts/test_wrong.sh", + ] + mismatches = guard.coverage_mismatches( + expected, configured, {}, guard._shell_path_in_scope + ) + assert mismatches["missing"] == ["tests/test_two.sh"], mismatches + assert mismatches["stale"] == ["tests/test_missing.sh"], mismatches + assert mismatches["duplicates"] == ["benchmark/test_one.sh"], mismatches + assert mismatches["out_of_scope"] == ["scripts/test_wrong.sh"], mismatches + assert mismatches["stale_exclusions"] == [], mismatches + print("PASS: shell missing, stale, duplicate and out-of-scope entries are distinct") + + +def test_shell_mismatch_exit_and_diagnostics(): + expected = ["benchmark/test_one.sh", "tests/test_two.sh"] + configured = [ + "benchmark/test_one.sh", + "benchmark/test_one.sh", + "tests/test_missing.sh", + "scripts/test_wrong.sh", + ] + stdout = io.StringIO() + with mock.patch.object(guard, "discovered_python_tests", return_value=[]), \ + mock.patch.object(guard, "configured_python_tests", return_value=[]), \ + mock.patch.object(guard, "discovered_shell_tests", return_value=expected), \ + mock.patch.object( + guard, "configured_shell_tests", return_value=configured + ), contextlib.redirect_stdout(stdout): + result = guard.main() + output = stdout.getvalue() + assert result == 1, output + for label, path in ( + ("[SHELL MISSING]", "tests/test_two.sh"), + ("[SHELL STALE]", "tests/test_missing.sh"), + ("[SHELL DUPLICATE]", "benchmark/test_one.sh"), + ("[SHELL OUT-OF-SCOPE]", "scripts/test_wrong.sh"), + ): + assert label in output, output + assert path in output, output + print("PASS: shell mismatches exit 1 and name every affected path") + + +def test_shell_exclusion_policy(): + excluded = {"tests/test_heavy.sh": "requires an external service"} + stdout = io.StringIO() + with mock.patch.object(guard, "EXCLUDED_SHELL_TESTS", excluded), \ + mock.patch.object(guard, "discovered_python_tests", return_value=[]), \ + mock.patch.object(guard, "configured_python_tests", return_value=[]), \ + mock.patch.object( + guard, "discovered_shell_tests", return_value=["tests/test_heavy.sh"] + ), \ + mock.patch.object(guard, "configured_shell_tests", return_value=[]), \ + contextlib.redirect_stdout(stdout): + result = guard.main() + output = stdout.getvalue() + assert result == 0, output + assert "[excluded] tests/test_heavy.sh - requires an external service" in output + + stdout = io.StringIO() + with mock.patch.object(guard, "EXCLUDED_SHELL_TESTS", excluded), \ + mock.patch.object(guard, "discovered_python_tests", return_value=[]), \ + mock.patch.object(guard, "configured_python_tests", return_value=[]), \ + mock.patch.object( + guard, "discovered_shell_tests", return_value=["tests/test_heavy.sh"] + ), \ + mock.patch.object( + guard, "configured_shell_tests", return_value=["tests/test_heavy.sh"] + ), contextlib.redirect_stdout(stdout): + result = guard.main() + output = stdout.getvalue() + assert result == 1, output + assert "[SHELL REDUNDANT-EXCLUSION]" in output, output + assert "tests/test_heavy.sh" in output, output + + stderr = io.StringIO() + with mock.patch.object( + guard, "EXCLUDED_SHELL_TESTS", {"tests/test_bad.sh": ""} + ), contextlib.redirect_stderr(stderr): + try: + guard.main() + except SystemExit as exc: + assert exc.code == 2, exc.code + else: + raise AssertionError("an exclusion without a reason must fail") + assert "must have a nonempty reason" in stderr.getvalue() + print("PASS: shell exclusions require reasons and cannot duplicate CI entries") + + +def main(): + test_shell_fixture_parser() + test_shell_mismatch_classes() + test_shell_mismatch_exit_and_diagnostics() + test_shell_exclusion_policy() + print("\nAll CI test coverage guard tests passed.") + + +if __name__ == "__main__": + main() diff --git a/tests/validate_ci_test_coverage.py b/tests/validate_ci_test_coverage.py index c7cd0fd..5ca226d 100644 --- a/tests/validate_ci_test_coverage.py +++ b/tests/validate_ci_test_coverage.py @@ -1,24 +1,15 @@ #!/usr/bin/env python3 -"""CI test-coverage guard for the lightweight PR checks. +"""CI test coverage guard for the lightweight PR checks. -Compares two sets and fails if they disagree: +The guard compares tracked test files with the explicit test lists in +``.github/workflows/pr-checks.yml``. It covers both Python tests under +``benchmark/`` and shell contract tests directly under ``benchmark/`` or +``tests/``. A new test therefore turns CI red until it is either listed in +the workflow or deliberately excluded below with a reason. - * expected - every *tracked* ``test_*.py`` file under ``benchmark/`` - (including nested directories), as reported by - ``git ls-files``. - * configured - the test files listed in the ``Run Python test suites`` - step of ``.github/workflows/pr-checks.yml``. - -This script never runs tests. It only enforces that the workflow's explicit -test list stays in agreement with the repository, so a newly added test file -turns CI red until a maintainer deliberately decides where it belongs: add it -to the workflow list (if it is lightweight enough for PR CI) or record it in -EXCLUDED_TESTS below with a reason (if it is not). Nothing is ever skipped -silently. - -The workflow is parsed with PyYAML. Only ``jobs`` is read: the top-level -``on`` key is deliberately never accessed, because YAML 1.1 loads it as the -boolean ``True`` rather than the string ``"on"``. +This script never runs tests. The workflow is parsed with PyYAML. Only +``jobs`` is read because YAML 1.1 loads the top level ``on`` key as boolean +``True`` rather than the string ``"on"``. Exit codes: 0 = in agreement, 1 = coverage mismatch, 2 = guard could not run. """ @@ -32,31 +23,34 @@ REPO_ROOT = Path(__file__).resolve().parent.parent WORKFLOW = REPO_ROOT / ".github" / "workflows" / "pr-checks.yml" -WORKFLOW_STEP = "Run Python test suites" -SCOPE_DIR = "benchmark" - -# Deliberate exclusions: tracked benchmark test files that are intentionally -# NOT run by the lightweight PR CI, each with its reason. A test belongs here -# only if it cannot run in this environment (heavy dependencies, datasets, -# GPUs, OpenMS binaries, ...). Every other test must be listed in the -# workflow's "Run Python test suites" step. Excluded files are reported by -# this guard on every run, so the exclusion stays visible. +PYTHON_WORKFLOW_STEP = "Run Python test suites" +SHELL_WORKFLOW_STEP = "Run shell contract tests" +PYTHON_SCOPE_DIR = "benchmark" +SHELL_SCOPE_DIRS = ("benchmark", "tests") +SHELL_OPERATOR_RE = re.compile(r"[|&;<>`$()]") + +# Deliberate exclusions: tracked test files intentionally omitted from the +# lightweight PR CI. Each entry must have a nonempty reason. Exclusions are +# printed on every run so they never become invisible policy. EXCLUDED_TESTS = { # "benchmark/test_example.py": "requires OpenMS binaries and reference data", } +EXCLUDED_SHELL_TESTS = { + # "tests/test_example.sh": "requires a service unavailable in PR CI", +} def fatal(message): """Guard could not run (exit 2), distinct from a coverage mismatch (1).""" print(f"ERROR: {message}", file=sys.stderr) - sys.exit(2) + raise SystemExit(2) -def discovered_tests(): - """Tracked test_*.py files under benchmark/, nested directories included.""" +def _git_ls_files(scope_dirs): + """Return tracked paths below scope_dirs, or exit 2 when git fails.""" try: result = subprocess.run( - ["git", "ls-files", "-z", "--", f"{SCOPE_DIR}/"], + ["git", "ls-files", "-z", "--", *(f"{d}/" for d in scope_dirs)], cwd=REPO_ROOT, capture_output=True, text=True, @@ -66,18 +60,30 @@ def discovered_tests(): fatal("git is not available on PATH") except subprocess.CalledProcessError as exc: fatal(f"git ls-files failed: {exc.stderr.strip()}") + return [path for path in result.stdout.split("\0") if path] + + +def discovered_python_tests(): + """Tracked test_*.py files under benchmark/, including nested paths.""" return sorted( path - for path in result.stdout.split("\0") - if path - and path.endswith(".py") + for path in _git_ls_files((PYTHON_SCOPE_DIR,)) + if path.endswith(".py") and Path(path).name.startswith("test_") and (REPO_ROOT / path).is_file() ) -def configured_tests(): - """Test files listed in the workflow's 'Run Python test suites' step.""" +def discovered_shell_tests(): + """Tracked benchmark/test_*.sh and tests/test_*.sh contract tests.""" + return sorted( + path + for path in _git_ls_files(SHELL_SCOPE_DIRS) + if _shell_path_in_scope(path) and (REPO_ROOT / path).is_file() + ) + + +def _workflow_steps(): if not WORKFLOW.is_file(): fatal(f"workflow not found: {WORKFLOW}") try: @@ -87,104 +93,223 @@ def configured_tests(): fatal(f"cannot parse {WORKFLOW.name}: {exc}") except (KeyError, TypeError) as exc: fatal(f"unexpected structure in {WORKFLOW.name} (jobs.tests.steps): {exc!r}") - step = next( - (s for s in steps if isinstance(s, dict) and s.get("name") == WORKFLOW_STEP), - None, - ) - if step is None: - fatal(f"no step named {WORKFLOW_STEP!r} in {WORKFLOW.name}") + if not isinstance(steps, list): + fatal(f"unexpected structure in {WORKFLOW.name}: jobs.tests.steps is not a list") + return steps + + +def _named_step(name): + matches = [ + step + for step in _workflow_steps() + if isinstance(step, dict) and step.get("name") == name + ] + if not matches: + fatal(f"no step named {name!r} in {WORKFLOW.name}") + if len(matches) > 1: + fatal(f"more than one step named {name!r} in {WORKFLOW.name}") + return matches[0] + + +def configured_python_tests(): + """Python paths in the workflow's explicit ``for f in`` test list.""" + step = _named_step(PYTHON_WORKFLOW_STEP) run = step.get("run") if not isinstance(run, str): - fatal(f"step {WORKFLOW_STEP!r} has no run block") - # The workflow keeps an explicit `for f in \ path \ ...; do` list. Only - # the loop header is parsed, never the body, and a change to the loop - # shape fails loudly here instead of silently passing the guard. + fatal(f"step {PYTHON_WORKFLOW_STEP!r} has no run block") match = re.search(r"for\s+f\s+in(.*?);?\s*do\b", run, re.DOTALL) if not match: - fatal(f"no 'for f in ...; do' test list found in step {WORKFLOW_STEP!r}") + fatal( + f"no 'for f in ...; do' test list found in step " + f"{PYTHON_WORKFLOW_STEP!r}" + ) entries = [ token.rstrip(";") for token in match.group(1).replace("\\", " ").split() ] tests = [entry for entry in entries if entry.endswith(".py")] if not tests: - fatal(f"the test list in step {WORKFLOW_STEP!r} contains no .py entries") + fatal( + f"the test list in step {PYTHON_WORKFLOW_STEP!r} contains no .py entries" + ) return tests -def main(): - expected = discovered_tests() - configured = configured_tests() - - duplicates = sorted({t for t in configured if configured.count(t) > 1}) - out_of_scope = sorted({t for t in configured if not t.startswith(f"{SCOPE_DIR}/")}) - stale = sorted( - { - t - for t in configured - if t.startswith(f"{SCOPE_DIR}/") and t not in expected - } - ) - missing = sorted( - t for t in expected if t not in configured and t not in EXCLUDED_TESTS - ) - stale_exclusions = sorted(t for t in EXCLUDED_TESTS if t not in expected) +def configured_shell_tests(): + """Shell paths in the workflow's explicit ``bash `` commands. - print("== CI test coverage guard ==") - print(f"discovered: {len(expected)} tracked test_*.py files under {SCOPE_DIR}/") - print( - f"configured: {len(configured)} entries in the {WORKFLOW_STEP!r} step " - f"of {WORKFLOW.name}" + The accepted shape is intentionally narrow. Apart from comments and + ``set -euo pipefail``, every nonblank line must be one ``bash `` + command. A loop, ``sh`` invocation, pipeline, flag, or other command is a + guard configuration error rather than an empty list that could pass. + """ + step = _named_step(SHELL_WORKFLOW_STEP) + if step.get("shell") != "bash": + fatal(f"step {SHELL_WORKFLOW_STEP!r} must declare shell: bash") + run = step.get("run") + if not isinstance(run, str): + fatal(f"step {SHELL_WORKFLOW_STEP!r} has no run block") + + commands = [ + line.strip() + for line in run.splitlines() + if line.strip() and not line.lstrip().startswith("#") + ] + if commands and commands[0] == "set -euo pipefail": + commands = commands[1:] + if not commands: + fatal(f"step {SHELL_WORKFLOW_STEP!r} contains no bash test entries") + + tests = [] + for command in commands: + match = re.fullmatch(r"bash\s+([^\s]+)", command) + if not match: + fatal( + f"unexpected command in step {SHELL_WORKFLOW_STEP!r}: {command!r}; " + "expected one 'bash ' command per line" + ) + test_path = match.group(1) + if SHELL_OPERATOR_RE.search(test_path): + fatal( + f"unexpected shell operator in step {SHELL_WORKFLOW_STEP!r}: " + f"{command!r}; expected one plain test path after 'bash'" + ) + tests.append(test_path) + return tests + + +def _python_path_in_scope(path): + return path.startswith(f"{PYTHON_SCOPE_DIR}/") and path.endswith(".py") + + +def _shell_path_in_scope(path): + candidate = Path(path) + return ( + candidate.parent.as_posix() in SHELL_SCOPE_DIRS + and candidate.name.startswith("test_") + and candidate.suffix == ".sh" ) - print(f"excluded: {len(EXCLUDED_TESTS)} deliberate exclusions") - for path, reason in sorted(EXCLUDED_TESTS.items()): + + +def _validate_exclusions(exclusions, label): + for path, reason in exclusions.items(): + if not isinstance(reason, str) or not reason.strip(): + fatal(f"{label} entry {path!r} must have a nonempty reason") + + +def coverage_mismatches(expected, configured, exclusions, in_scope): + """Return the mismatch classes shared by both test languages.""" + return { + "missing": sorted( + path + for path in expected + if path not in configured and path not in exclusions + ), + "stale": sorted( + {path for path in configured if in_scope(path) and path not in expected} + ), + "duplicates": sorted( + {path for path in configured if configured.count(path) > 1} + ), + "out_of_scope": sorted({path for path in configured if not in_scope(path)}), + "stale_exclusions": sorted( + path for path in exclusions if path not in expected + ), + "redundant_exclusions": sorted(set(configured) & set(exclusions)), + } + + +def _report_group(language, expected, configured, exclusions, mismatches, step_name): + print(f"== {language} tests ==") + print(f"discovered: {len(expected)} tracked test file(s)") + print(f"configured: {len(configured)} entries in the {step_name!r} step") + print(f"excluded: {len(exclusions)} deliberate exclusions") + for path, reason in sorted(exclusions.items()): print(f" [excluded] {path} - {reason}") print() - def report(label, paths, hint): + hints = { + "missing": f"add it to {step_name!r}, or record a reason in the exclusion map", + "stale": "remove or correct the workflow entry", + "duplicates": "remove the duplicate workflow entry", + "out_of_scope": "only test paths in this guard's scope may be listed", + "stale_exclusions": "remove the exclusion or restore the tracked test file", + "redundant_exclusions": ( + "remove the exclusion because this test is already listed in the workflow" + ), + } + labels = { + "missing": "MISSING", + "stale": "STALE", + "duplicates": "DUPLICATE", + "out_of_scope": "OUT-OF-SCOPE", + "stale_exclusions": "STALE-EXCLUSION", + "redundant_exclusions": "REDUNDANT-EXCLUSION", + } + for key in ( + "missing", + "stale", + "duplicates", + "out_of_scope", + "stale_exclusions", + "redundant_exclusions", + ): + paths = mismatches[key] if paths: - print(f"[{label}]") + print(f"[{language.upper()} {labels[key]}]") for path in paths: print(f" {path}") - print(f" hint: {hint}") + print(f" hint: {hints[key]}") print() - report( - "MISSING", - missing, - "add it to the workflow's 'Run Python test suites' list, or to " - "EXCLUDED_TESTS in tests/validate_ci_test_coverage.py with a reason", - ) - report( - "STALE", - stale, - "listed in the workflow but not a tracked test_*.py under " - "benchmark/ - remove or correct the entry", + +def main(): + _validate_exclusions(EXCLUDED_TESTS, "EXCLUDED_TESTS") + _validate_exclusions(EXCLUDED_SHELL_TESTS, "EXCLUDED_SHELL_TESTS") + + python_expected = discovered_python_tests() + python_configured = configured_python_tests() + shell_expected = discovered_shell_tests() + shell_configured = configured_shell_tests() + + python_mismatches = coverage_mismatches( + python_expected, python_configured, EXCLUDED_TESTS, _python_path_in_scope ) - report( - "DUPLICATE", - duplicates, - "listed more than once in the workflow - remove the duplicate", + shell_mismatches = coverage_mismatches( + shell_expected, + shell_configured, + EXCLUDED_SHELL_TESTS, + _shell_path_in_scope, ) - report( - "OUT-OF-SCOPE", - out_of_scope, - "the workflow list must only contain paths under benchmark/", + + print("== CI test coverage guard ==") + _report_group( + "Python", + python_expected, + python_configured, + EXCLUDED_TESTS, + python_mismatches, + PYTHON_WORKFLOW_STEP, ) - report( - "STALE-EXCLUSION", - stale_exclusions, - "EXCLUDED_TESTS references a file that is not a discovered test - " - "remove the outdated exclusion", + _report_group( + "Shell", + shell_expected, + shell_configured, + EXCLUDED_SHELL_TESTS, + shell_mismatches, + SHELL_WORKFLOW_STEP, ) - problems = len(missing) + len(stale) + len(duplicates) + len(out_of_scope) - problems += len(stale_exclusions) + problems = sum(len(paths) for paths in python_mismatches.values()) + problems += sum(len(paths) for paths in shell_mismatches.values()) if problems: print(f"RESULT: FAIL - {problems} problem(s)") return 1 + + total = len(python_expected) + len(shell_expected) + excluded = len(EXCLUDED_TESTS) + len(EXCLUDED_SHELL_TESTS) print( - f"RESULT: OK - all {len(expected)} discovered test file(s) are " - f"accounted for ({len(EXCLUDED_TESTS)} excluded)" + f"RESULT: OK - all {total} discovered test file(s) are " + f"accounted for ({excluded} excluded)" ) return 0