Skip to content
Open
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
5 changes: 3 additions & 2 deletions .github/workflows/pr-checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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"
Expand Down
263 changes: 263 additions & 0 deletions benchmark/test_validate_ci_test_coverage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,263 @@
#!/usr/bin/env python3
"""Tests for the Python and shell CI test coverage guard."""

import contextlib
import importlib.util
import io
import subprocess
import sys
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 fixture_python_workflow(run):
indented_run = "".join(f" {line}\n" for line in run.splitlines())
return f"""
jobs:
tests:
steps:
- name: {guard.PYTHON_WORKFLOW_STEP}
shell: bash
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 parse_python_fixture(run):
with tempfile.TemporaryDirectory() as tmp:
workflow = Path(tmp) / "workflow.yml"
workflow.write_text(fixture_python_workflow(run), encoding="utf-8")
with mock.patch.object(guard, "WORKFLOW", workflow):
return guard.configured_python_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 <test-path>'" 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

for unsupported in (
"set -euo pipefail\nbash tests/test_one.sh # contract test",
"set -eu\nbash tests/test_one.sh",
"set -euo pipefail\nbash tests/test_one.sh \\\n--verbose",
):
message = expect_fatal(unsupported)
assert "unexpected command" in message, message
print("PASS: shell workflow parser allows comments and explicit bash entries")


def test_python_fixture_parser():
tests = parse_python_fixture(
"set -euo pipefail\n"
"for f in \\\n./benchmark/test_one.py; do\n"
" echo \"== python $f\"\n"
" python \"$f\"\n"
"done"
)
assert tests == ["benchmark/test_one.py"], tests

stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
try:
parse_python_fixture(
"for f in benchmark/test_one.py; do\n true\ndone"
)
except SystemExit as exc:
assert exc.code == 2, exc.code
else:
raise AssertionError("a Python loop that does not run its tests must fail")
assert "must invoke" in stderr.getvalue(), stderr.getvalue()
print("PASS: Python workflow loop must invoke each normalized test path")


def test_missing_pyyaml_is_fatal():
result = subprocess.run(
[sys.executable, "-S", str(GUARD_PATH)],
cwd=GUARD_PATH.parent.parent,
capture_output=True,
text=True,
check=False,
)
assert result.returncode == 2, result
assert "PyYAML is required" in result.stderr, result.stderr
assert "Traceback" not in result.stderr, result.stderr
print("PASS: missing PyYAML exits 2 with a clear fatal error")


def test_exclusion_configuration_type():
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
try:
guard._validate_exclusions([], "EXCLUDED_TESTS")
except SystemExit as exc:
assert exc.code == 2, exc.code
else:
raise AssertionError("a non-mapping exclusion configuration must fail")
assert "must be a mapping" in stderr.getvalue(), stderr.getvalue()
assert "Traceback" not in stderr.getvalue(), stderr.getvalue()
print("PASS: malformed exclusion configuration fails cleanly")


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_python_fixture_parser()
test_missing_pyyaml_is_fatal()
test_exclusion_configuration_type()
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()
Loading
Loading