From 00167396f448791e69ec3fbed2a6bd486f7951f8 Mon Sep 17 00:00:00 2001 From: ZimingHua Date: Tue, 27 Oct 2026 14:36:02 -0400 Subject: [PATCH 1/5] Test policyengine-us main against the Core under test on each PR Core 3.33.13 broke policyengine-us main's state machine test within minutes of release, while the country smoke job passed: it installs a pinned policyengine-us release and only checks that systems load. The new PolicyEngineUSMain job runs a list of fast policyengine-us tests that drive Core internals, with the Core release and then with this checkout, and fails only on tests that fail with this Core alone. Co-Authored-By: Claude Opus 5.5 --- .github/country_main_tests.py | 162 +++++++++++++++++ .../policyengine-us-main-tests.txt | 26 +++ .github/workflows/pr.yaml | 62 ++++++- .../test-policyengine-us-main.changed.md | 1 + tests/core/test_country_main_tests.py | 169 ++++++++++++++++++ 5 files changed, 416 insertions(+), 4 deletions(-) create mode 100644 .github/country_main_tests.py create mode 100644 .github/requirements/policyengine-us-main-tests.txt create mode 100644 changelog.d/test-policyengine-us-main.changed.md create mode 100644 tests/core/test_country_main_tests.py diff --git a/.github/country_main_tests.py b/.github/country_main_tests.py new file mode 100644 index 000000000..d2fb15c75 --- /dev/null +++ b/.github/country_main_tests.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python +"""Run policyengine-us main's Core-facing tests against the Core under test. + +The country smoke job installs a pinned policyengine-us release and checks +that its system loads, so it cannot see a policyengine-us test that a Core +change breaks. On 2026-10-27, 3.33.13 broke policyengine-us main's +test_social_security_input_state_machine.py within minutes of its release. + +The PolicyEngineUSMain job checks out policyengine-us main and runs the files +in .github/requirements/policyengine-us-main-tests.txt twice, each with a +JUnit report: first with the Core release on PyPI, then with this checkout. + +- `select LIST REPO` prints the listed files that exist in REPO, one per + line, and warns about the rest, which policyengine-us renamed or removed. +- `compare RELEASED CANDIDATE` fails on each test that fails with this Core + but did not fail with the release. A test that fails with both is a + policyengine-us failure, so it is only a warning: policyengine-us main is + sometimes red for its own reasons. +""" + +import argparse +import os +import sys +from pathlib import Path +from xml.etree import ElementTree + + +def listed_files(list_path): + """The paths in a list file, without comments or blank lines.""" + paths = [] + for line in Path(list_path).read_text().splitlines(): + line = line.split("#", 1)[0].strip() + if line: + paths.append(line) + return paths + + +def select(list_path, repo): + """The listed files that exist in the checkout, and those that do not.""" + present, missing = [], [] + for path in listed_files(list_path): + (present if (Path(repo) / path).is_file() else missing).append(path) + return present, missing + + +def outcomes(report): + """Each test's outcome in a JUnit report: passed, failed or skipped. + + A test can appear twice, as when its teardown errors after it passed; + a failure in either entry counts. + """ + results = {} + for case in ElementTree.parse(report).getroot().iter("testcase"): + test = f"{case.get('classname', '')}::{case.get('name', '')}" + tags = {child.tag for child in case} + if tags & {"failure", "error"}: + outcome = "failed" + elif "skipped" in tags: + outcome = "skipped" + else: + outcome = "passed" + if results.get(test) != "failed": + results[test] = outcome + return results + + +def compare(released, candidate): + """Tests this Core breaks, and tests that fail with both Cores.""" + broken = sorted( + test + for test, outcome in candidate.items() + if outcome == "failed" and released.get(test) != "failed" + ) + both = sorted( + test + for test, outcome in candidate.items() + if outcome == "failed" and released.get(test) == "failed" + ) + return broken, both + + +def summary(released, candidate, broken, both): + lines = [ + "### policyengine-us main against this Core", + "", + f"{len(candidate)} tests ran with this Core and {len(released)} with " + "the Core release.", + "", + ] + if broken: + lines.append(f"**This Core breaks {len(broken)}:**") + lines += [f"- `{test}`" for test in broken] + lines.append("") + if both: + lines.append(f"Failing with both Cores (policyengine-us's own): {len(both)}") + lines += [f"- `{test}`" for test in both] + if not broken and not both: + lines.append("Every test passes with this Core.") + return "\n".join(lines) + "\n" + + +def run_compare(released_report, candidate_report, summary_path=None): + if not Path(candidate_report).exists(): + print( + "::error::This Core's run wrote no JUnit report: pytest could not " + "start or was killed." + ) + return 1 + if not Path(released_report).exists(): + print( + "::warning::The Core release's run wrote no JUnit report, so " + "nothing can be blamed on this Core." + ) + return 0 + released = outcomes(released_report) + candidate = outcomes(candidate_report) + broken, both = compare(released, candidate) + for test in both: + print(f"::warning::Fails with the Core release too: {test}") + for test in broken: + print(f"::error::This Core breaks {test}") + text = summary(released, candidate, broken, both) + print(text) + if summary_path: + with open(summary_path, "a") as output: + output.write(text) + return 1 if broken else 0 + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + commands = parser.add_subparsers(dest="command", required=True) + chooser = commands.add_parser("select", help="list the files to run") + chooser.add_argument("list") + chooser.add_argument("repo") + checker = commands.add_parser("compare", help="compare the two runs") + checker.add_argument("released") + checker.add_argument("candidate") + checker.add_argument( + "--summary", + default=os.environ.get("GITHUB_STEP_SUMMARY"), + help="file to append a Markdown summary to", + ) + args = parser.parse_args(argv) + if args.command == "select": + present, missing = select(args.list, args.repo) + for path in missing: + print( + f"::warning::policyengine-us main has no {path}; update " + ".github/requirements/policyengine-us-main-tests.txt.", + file=sys.stderr, + ) + if not present: + print("::error::None of the listed files exist.", file=sys.stderr) + return 1 + print("\n".join(present)) + return 0 + return run_compare(args.released, args.candidate, args.summary) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/requirements/policyengine-us-main-tests.txt b/.github/requirements/policyengine-us-main-tests.txt new file mode 100644 index 000000000..84eb2e5e5 --- /dev/null +++ b/.github/requirements/policyengine-us-main-tests.txt @@ -0,0 +1,26 @@ +# policyengine-us test files the PolicyEngineUSMain job runs from a checkout of +# policyengine-us main, first with the Core release on PyPI and then with the +# Core under test (.github/country_main_tests.py). Paths are relative to the +# policyengine-us repository root. +# +# Each file drives Core internals (simulations, holders, data storage, tools, +# populations, parameters or reforms) and is fast: together they took about +# 95 seconds in policyengine-us release run 40544965026. The state machine test +# runs Core's installed source bodies in namespaces it builds; Core 3.33.13 +# broke it on 2026-10-27, which this job would have shown on the PR. +# +# A file policyengine-us renames or removes is skipped with a warning, so keep +# the list in step when that happens. +policyengine_us/tests/core/test_social_security_input_state_machine.py +policyengine_us/tests/core/test_social_security_real_core.py +policyengine_us/tests/core/test_loss_ald_extraction_parity.py +policyengine_us/tests/core/test_capital_gains_rate_worksheet_properties.py +policyengine_us/tests/core/test_ald_determinism.py +policyengine_us/tests/core/test_pandas3_compatibility.py +policyengine_us/tests/core/test_social_security_lever_properties.py +policyengine_us/tests/test_locality_sales_tax_rates.py +policyengine_us/tests/test_parameter_scale_thresholds.py +policyengine_us/tests/code_health/test_no_group_variables_in_person_adds.py +policyengine_us/tests/microsimulation/data/test_extend_single_year_dataset.py +policyengine_us/tests/policy/baseline/parameters/test_uprating_extensions.py +policyengine_us/tests/policy/baseline/gov/states/or/tax/income/credits/test_or_ctc_sunset.py diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index c90189cb6..7df05951e 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -4,10 +4,10 @@ on: branches: [master] # A new push to a pull request supersedes the run on its previous head. Cancel -# that run instead of letting its 19 jobs (8 Test, 8 smoke, 3 checks) keep -# holding org-wide shared runners. From 2026-10-06 to 10-08, 21 of 55 PR runs -# were superseded while still running, and finishing them used 850 -# runner-minutes (26% of this workflow). +# that run instead of letting its 20 jobs (8 Test, 8 smoke, 1 policyengine-us +# main, 3 checks) keep holding org-wide shared runners. From 2026-10-06 to +# 10-08, 21 of 55 PR runs were superseded while still running, and finishing +# them used 850 runner-minutes (26% of this workflow). concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number }} cancel-in-progress: true @@ -121,3 +121,57 @@ jobs: env: RUN_SMOKE_TESTS: "0" POLICYENGINE_GITHUB_MICRODATA_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PolicyEngineUSMain: + name: Test policyengine-us main against this Core + runs-on: ubuntu-latest + needs: Lint + timeout-minutes: 30 + permissions: + contents: read + env: + PYTHONUNBUFFERED: 1 + steps: + - name: Checkout repo + uses: actions/checkout@v6 + with: + path: core + persist-credentials: false + - name: Checkout policyengine-us main + uses: actions/checkout@v6 + with: + repository: PolicyEngine/policyengine-us + ref: main + path: policyengine-us + persist-credentials: false + - name: Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.14" + - name: Install uv + uses: astral-sh/setup-uv@v8.1.0 + # As policyengine-us's own CI does: its lock with the newest Core release. + - name: Install policyengine-us main with the Core release + working-directory: policyengine-us + run: | + uv lock --upgrade-package policyengine-core + uv sync --locked --extra dev + bash ./update_itemization.sh + - name: Select the policyengine-us tests + run: python core/.github/country_main_tests.py select core/.github/requirements/policyengine-us-main-tests.txt policyengine-us > selected.txt + # Both runs draw the same Hypothesis examples, so a difference between + # them comes from Core. A failing run still writes its report. + - name: Run them with the Core release + working-directory: policyengine-us + run: | + uv pip list | grep -i '^policyengine-core ' + xargs uv run --no-sync python -m pytest -p no:cacheprovider --hypothesis-seed=0 --junitxml=../released.xml < ../selected.txt || true + - name: Install this Core + working-directory: policyengine-us + run: | + uv pip install --python .venv/bin/python --reinstall-package policyengine-core ../core + uv run --no-sync python -c "import json; from importlib.metadata import distribution; url = json.loads(distribution('policyengine-core').read_text('direct_url.json'))['url']; print(url); assert url.startswith('file://'), url" + - name: Run them with this Core + working-directory: policyengine-us + run: xargs uv run --no-sync python -m pytest -p no:cacheprovider --hypothesis-seed=0 --junitxml=../candidate.xml < ../selected.txt || true + - name: Fail on tests this Core breaks + run: python core/.github/country_main_tests.py compare released.xml candidate.xml diff --git a/changelog.d/test-policyengine-us-main.changed.md b/changelog.d/test-policyengine-us-main.changed.md new file mode 100644 index 000000000..52ab3be87 --- /dev/null +++ b/changelog.d/test-policyengine-us-main.changed.md @@ -0,0 +1 @@ +Add a PR job that runs policyengine-us main's Core-facing tests with the Core release and then with the Core under test, and fails on tests the change breaks. diff --git a/tests/core/test_country_main_tests.py b/tests/core/test_country_main_tests.py new file mode 100644 index 000000000..2cf14c6ee --- /dev/null +++ b/tests/core/test_country_main_tests.py @@ -0,0 +1,169 @@ +"""The PolicyEngineUSMain job blames Core only for the tests Core breaks. + +It runs policyengine-us main's listed tests with the Core release and then +with the Core under test (.github/country_main_tests.py). These tests check +the comparison on synthetic JUnit reports, the file selection, the list, and +the order of the job's steps. +""" + +import importlib.util +from pathlib import Path + +import pytest +import yaml + +ROOT = Path(__file__).resolve().parents[2] +SCRIPT = ROOT / ".github" / "country_main_tests.py" +LIST = ROOT / ".github" / "requirements" / "policyengine-us-main-tests.txt" +WORKFLOW = ROOT / ".github" / "workflows" / "pr.yaml" +SPEC = importlib.util.spec_from_file_location("country_main_tests", SCRIPT) +country = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(country) + + +def junit(path, cases): + """Write a JUnit report of (classname, name, outcome) cases.""" + body = "" + for classname, name, outcome in cases: + child = { + "passed": "", + "failed": '', + "error": '', + "skipped": '', + }[outcome] + body += f'{child}' + path.write_text(f"{body}") + return path + + +def test_outcomes_count_a_failure_in_any_entry_of_a_test(tmp_path): + report = junit( + tmp_path / "r.xml", + [ + ("a.test_x", "test_pass", "passed"), + ("a.test_x", "test_fail", "failed"), + ("a.test_x", "test_skip", "skipped"), + ("a.test_x.TestCase", "runTest", "passed"), + ("a.test_x.TestCase", "runTest", "error"), + ], + ) + assert country.outcomes(report) == { + "a.test_x::test_pass": "passed", + "a.test_x::test_fail": "failed", + "a.test_x::test_skip": "skipped", + "a.test_x.TestCase::runTest": "failed", + } + + +def test_only_tests_failing_with_this_core_alone_are_blamed_on_it(): + released = {"t::a": "passed", "t::b": "failed", "t::c": "skipped"} + candidate = { + "t::a": "failed", # this Core breaks it + "t::b": "failed", # policyengine-us's own failure + "t::c": "failed", # skipped before, fails now + "t::d": "failed", # absent before, such as a new collection error + "t::e": "passed", + } + assert country.compare(released, candidate) == ( + ["t::a", "t::c", "t::d"], + ["t::b"], + ) + + +@pytest.mark.parametrize( + "released_cases, candidate_cases, status", + [ + ([("t", "a", "passed")], [("t", "a", "failed")], 1), + ([("t", "a", "failed")], [("t", "a", "failed")], 0), + ([("t", "a", "passed")], [("t", "a", "passed")], 0), + (None, [("t", "a", "failed")], 0), + ([("t", "a", "passed")], None, 1), + ], + ids=["broken", "fails-with-both", "passes", "no-release-report", "no-report"], +) +def test_compare_fails_only_on_breaks_or_a_missing_report( + tmp_path, capsys, released_cases, candidate_cases, status +): + released = tmp_path / "released.xml" + candidate = tmp_path / "candidate.xml" + if released_cases is not None: + junit(released, released_cases) + if candidate_cases is not None: + junit(candidate, candidate_cases) + summary = tmp_path / "summary.md" + assert ( + country.main( + ["compare", str(released), str(candidate), "--summary", str(summary)] + ) + == status + ) + output = capsys.readouterr().out + if status and candidate_cases is not None: + assert "::error::This Core breaks t::a" in output + assert "**This Core breaks 1:**" in summary.read_text() + if released_cases == candidate_cases == [("t", "a", "failed")]: + assert "::warning::Fails with the Core release too: t::a" in output + + +def test_select_skips_files_the_checkout_lacks(tmp_path, capsys): + repo = tmp_path / "policyengine-us" + (repo / "tests").mkdir(parents=True) + (repo / "tests" / "test_kept.py").write_text("") + listing = tmp_path / "list.txt" + listing.write_text( + "# comment\n\ntests/test_kept.py # trailing comment\ntests/test_gone.py\n" + ) + assert country.select(listing, repo) == ( + ["tests/test_kept.py"], + ["tests/test_gone.py"], + ) + assert country.main(["select", str(listing), str(repo)]) == 0 + captured = capsys.readouterr() + assert captured.out == "tests/test_kept.py\n" + assert "::warning::policyengine-us main has no tests/test_gone.py" in captured.err + listing.write_text("tests/test_gone.py\n") + assert country.main(["select", str(listing), str(repo)]) == 1 + + +def test_the_list_names_distinct_policyengine_us_test_files(): + paths = country.listed_files(LIST) + assert paths, "the list is empty" + assert len(paths) == len(set(paths)), "a file is listed twice" + for path in paths: + assert path.startswith("policyengine_us/tests/"), path + assert Path(path).name.startswith("test_") and path.endswith(".py"), path + + +def test_the_job_runs_the_release_then_this_core_and_compares_them(): + job = yaml.safe_load(WORKFLOW.read_text())["jobs"]["PolicyEngineUSMain"] + names = [step["name"] for step in job["steps"]] + assert names == [ + "Checkout repo", + "Checkout policyengine-us main", + "Set up Python", + "Install uv", + "Install policyengine-us main with the Core release", + "Select the policyengine-us tests", + "Run them with the Core release", + "Install this Core", + "Run them with this Core", + "Fail on tests this Core breaks", + ] + steps = {step["name"]: step for step in job["steps"]} + us = steps["Checkout policyengine-us main"]["with"] + assert (us["repository"], us["ref"]) == ("PolicyEngine/policyengine-us", "main") + released = steps["Run them with the Core release"]["run"] + candidate = steps["Run them with this Core"]["run"] + # The same tests and Hypothesis seed, with separate reports. + assert released.splitlines()[-1].replace("released.xml", "candidate.xml") == ( + candidate + ) + assert "--hypothesis-seed=0" in candidate + # The candidate replaces the release even at the same version number, + # and the job checks that it was installed from this checkout. + install = steps["Install this Core"]["run"] + assert "--reinstall-package policyengine-core ../core" in install + assert "assert url.startswith('file://')" in install + assert steps["Fail on tests this Core breaks"]["run"].endswith( + "compare released.xml candidate.xml" + ) From e295445b29f26e25701d2b76d78e39b67d9f9397 Mon Sep 17 00:00:00 2001 From: ZimingHua Date: Mon, 30 Nov 2026 10:56:50 -0600 Subject: [PATCH 2/5] Fail the policyengine-us main job unless every test ran Address review: `|| true` hid pytest's status, and compare looked only at tests in the candidate report, so an empty or cut-short run went green. - Run both passes through `country_main_tests.py run`, with --continue-on-collection-errors, and fail on any pytest status but 0 or 1. - compare fails when this Core's run recorded no tests, a report is missing, or a test that passed with the release did not run. A failure in a file the release could not collect is a warning, not a break. - The summary counts skips and says "failing with both Cores". - Deselect the uprating test that downloads the default microdata. - Check the installed dependencies after installing this Core. Co-Authored-By: Claude Opus 5.5 --- .github/country_main_tests.py | 230 +++++++++++++----- .../policyengine-us-main-tests.txt | 6 +- .github/workflows/pr.yaml | 10 +- tests/core/test_country_main_tests.py | 198 ++++++++++++--- 4 files changed, 341 insertions(+), 103 deletions(-) diff --git a/.github/country_main_tests.py b/.github/country_main_tests.py index d2fb15c75..2f08e7af7 100644 --- a/.github/country_main_tests.py +++ b/.github/country_main_tests.py @@ -10,37 +10,86 @@ in .github/requirements/policyengine-us-main-tests.txt twice, each with a JUnit report: first with the Core release on PyPI, then with this checkout. -- `select LIST REPO` prints the listed files that exist in REPO, one per - line, and warns about the rest, which policyengine-us renamed or removed. +- `select LIST REPO` prints the pytest arguments for the listed files that + exist in REPO, one per line, and warns about the rest, which + policyengine-us renamed or removed. +- `run SELECTED REPORT` runs them with a JUnit report. It fails unless pytest + ran them to the end, passing or failing. - `compare RELEASED CANDIDATE` fails on each test that fails with this Core - but did not fail with the release. A test that fails with both is a - policyengine-us failure, so it is only a warning: policyengine-us main is - sometimes red for its own reasons. + but did not fail with the release, and on each test that passed with the + release but did not run with this Core. A test that fails with both Cores + is only a warning: policyengine-us main or an earlier Core release broke + it, not this checkout. """ import argparse import os +import subprocess import sys from pathlib import Path from xml.etree import ElementTree +# Hypothesis draws the same examples in both runs, so a difference between +# them comes from Core. A file that fails to import must not stop the others. +PYTEST = [ + "uv", + "run", + "--no-sync", + "python", + "-m", + "pytest", + "-p", + "no:cacheprovider", + "--hypothesis-seed=0", + "--continue-on-collection-errors", +] +# pytest's exit statuses other than 0 (all passed) and 1 (some failed). +STOPPED = { + 2: "interrupted", + 3: "internal error", + 4: "usage error", + 5: "no tests collected", +} +DESELECT = "deselect " -def listed_files(list_path): - """The paths in a list file, without comments or blank lines.""" - paths = [] + +def listed_entries(list_path): + """The list's test files, and the tests to deselect from them.""" + files, deselected = [], [] for line in Path(list_path).read_text().splitlines(): line = line.split("#", 1)[0].strip() - if line: - paths.append(line) - return paths + if line.startswith(DESELECT): + deselected.append(line.removeprefix(DESELECT).strip()) + elif line: + files.append(line) + return files, deselected def select(list_path, repo): - """The listed files that exist in the checkout, and those that do not.""" - present, missing = [], [] - for path in listed_files(list_path): - (present if (Path(repo) / path).is_file() else missing).append(path) - return present, missing + """pytest arguments for the files the checkout has, and the files it lacks.""" + files, deselected = listed_entries(list_path) + present = [path for path in files if (Path(repo) / path).is_file()] + missing = [path for path in files if path not in present] + deselect = [ + f"--deselect={test}" for test in deselected if test.split("::")[0] in present + ] + return present + deselect, missing + + +def run_tests(selected_path, report, pytest=PYTEST): + """Run the selected tests with a JUnit report; fail unless they all ran. + + pytest exits 1 when a test fails or a file cannot be collected, and + compare sorts those out. Any other failing status means the run stopped + early or ran nothing, so its report cannot be compared. + """ + arguments = Path(selected_path).read_text().split() + status = subprocess.run([*pytest, f"--junitxml={report}", *arguments]).returncode + if status in (0, 1): + return 0 + meaning = STOPPED.get(status, "unexpected status") + print(f"::error::pytest exited {status} ({meaning}): not every test ran.") + return status def outcomes(report): @@ -64,75 +113,134 @@ def outcomes(report): return results -def compare(released, candidate): - """Tests this Core breaks, and tests that fail with both Cores.""" - broken = sorted( - test - for test, outcome in candidate.items() - if outcome == "failed" and released.get(test) != "failed" - ) - both = sorted( +def collection_errors(report): + """The modules a JUnit report could not collect, as dotted paths. + + pytest records a module's collection error as one entry whose name is + the module and whose class name is empty. + """ + modules = set() + for case in ElementTree.parse(report).getroot().iter("testcase"): + if any( + child.tag == "error" and child.get("message") == "collection failure" + for child in case + ): + parts = (case.get("classname", ""), case.get("name", "")) + modules.add(".".join(part for part in parts if part)) + return modules + + +def compare(released, candidate, uncollected=()): + """Sort this Core's failures and absences against the release's results. + + - broken: fails with this Core but did not fail with the release. + - missing: passed with the release but did not run with this Core. + - unsure: fails with this Core in a module the release could not + collect, so the release has no result to compare. + - both: fails with both Cores. + """ + + def uncollected_module(test): + classname = test.split("::")[0] + return any( + classname == module or classname.startswith(module + ".") + for module in uncollected + ) + + result = {"broken": [], "missing": [], "unsure": [], "both": []} + for test, outcome in sorted(candidate.items()): + if outcome != "failed": + continue + if released.get(test) == "failed": + result["both"].append(test) + elif test not in released and uncollected_module(test): + result["unsure"].append(test) + else: + result["broken"].append(test) + result["missing"] = sorted( test - for test, outcome in candidate.items() - if outcome == "failed" and released.get(test) == "failed" + for test, outcome in released.items() + if outcome == "passed" and test not in candidate ) - return broken, both + return result -def summary(released, candidate, broken, both): +def tally(results): + counts = [ + f"{sum(outcome == kind for outcome in results.values())} {kind}" + for kind in ("passed", "failed", "skipped") + ] + return ", ".join(counts) + + +def summary(released, candidate, result): lines = [ "### policyengine-us main against this Core", "", - f"{len(candidate)} tests ran with this Core and {len(released)} with " - "the Core release.", + f"- With the Core release: {tally(released)}", + f"- With this Core: {tally(candidate)}", "", ] - if broken: - lines.append(f"**This Core breaks {len(broken)}:**") - lines += [f"- `{test}`" for test in broken] - lines.append("") - if both: - lines.append(f"Failing with both Cores (policyengine-us's own): {len(both)}") - lines += [f"- `{test}`" for test in both] - if not broken and not both: - lines.append("Every test passes with this Core.") + titles = { + "broken": "**This Core breaks {}:**", + "missing": "**Passed with the Core release but did not run with this Core: {}**", + "unsure": "Failing with this Core in files the Core release could not collect: {}", + "both": "Failing with both Cores: {}", + } + for key, title in titles.items(): + if result[key]: + lines.append(title.format(len(result[key]))) + lines += [f"- `{test}`" for test in result[key]] + lines.append("") + if not any(result.values()): + lines.append( + "No test fails with this Core, and every test that ran before ran." + ) return "\n".join(lines) + "\n" def run_compare(released_report, candidate_report, summary_path=None): - if not Path(candidate_report).exists(): - print( - "::error::This Core's run wrote no JUnit report: pytest could not " - "start or was killed." - ) + for name, report in ( + ("This Core", candidate_report), + ("The Core release", released_report), + ): + if not Path(report).exists(): + print(f"::error::{name}'s run wrote no JUnit report.") + return 1 + released = outcomes(released_report) + candidate = outcomes(candidate_report) + if not candidate: + print("::error::This Core's run recorded no tests.") return 1 - if not Path(released_report).exists(): + result = compare(released, candidate, collection_errors(released_report)) + for test in result["both"]: + print(f"::warning::Fails with both Cores: {test}") + for test in result["unsure"]: print( - "::warning::The Core release's run wrote no JUnit report, so " - "nothing can be blamed on this Core." + "::warning::Fails with this Core; the Core release could not collect " + f"its file: {test}" ) - return 0 - released = outcomes(released_report) - candidate = outcomes(candidate_report) - broken, both = compare(released, candidate) - for test in both: - print(f"::warning::Fails with the Core release too: {test}") - for test in broken: + for test in result["missing"]: + print(f"::error::Passed with the Core release but did not run: {test}") + for test in result["broken"]: print(f"::error::This Core breaks {test}") - text = summary(released, candidate, broken, both) + text = summary(released, candidate, result) print(text) if summary_path: with open(summary_path, "a") as output: output.write(text) - return 1 if broken else 0 + return 1 if result["broken"] or result["missing"] else 0 def main(argv=None): parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) commands = parser.add_subparsers(dest="command", required=True) - chooser = commands.add_parser("select", help="list the files to run") + chooser = commands.add_parser("select", help="list the pytest arguments") chooser.add_argument("list") chooser.add_argument("repo") + runner = commands.add_parser("run", help="run the selected tests") + runner.add_argument("selected") + runner.add_argument("report") checker = commands.add_parser("compare", help="compare the two runs") checker.add_argument("released") checker.add_argument("candidate") @@ -143,18 +251,20 @@ def main(argv=None): ) args = parser.parse_args(argv) if args.command == "select": - present, missing = select(args.list, args.repo) + arguments, missing = select(args.list, args.repo) for path in missing: print( f"::warning::policyengine-us main has no {path}; update " ".github/requirements/policyengine-us-main-tests.txt.", file=sys.stderr, ) - if not present: + if not any(not argument.startswith("--") for argument in arguments): print("::error::None of the listed files exist.", file=sys.stderr) return 1 - print("\n".join(present)) + print("\n".join(arguments)) return 0 + if args.command == "run": + return run_tests(args.selected, args.report) return run_compare(args.released, args.candidate, args.summary) diff --git a/.github/requirements/policyengine-us-main-tests.txt b/.github/requirements/policyengine-us-main-tests.txt index 84eb2e5e5..c30296a88 100644 --- a/.github/requirements/policyengine-us-main-tests.txt +++ b/.github/requirements/policyengine-us-main-tests.txt @@ -10,7 +10,8 @@ # broke it on 2026-10-27, which this job would have shown on the PR. # # A file policyengine-us renames or removes is skipped with a warning, so keep -# the list in step when that happens. +# the list in step when that happens. A `deselect ::` line leaves +# one test of a listed file out. policyengine_us/tests/core/test_social_security_input_state_machine.py policyengine_us/tests/core/test_social_security_real_core.py policyengine_us/tests/core/test_loss_ald_extraction_parity.py @@ -23,4 +24,7 @@ policyengine_us/tests/test_parameter_scale_thresholds.py policyengine_us/tests/code_health/test_no_group_variables_in_person_adds.py policyengine_us/tests/microsimulation/data/test_extend_single_year_dataset.py policyengine_us/tests/policy/baseline/parameters/test_uprating_extensions.py +# Builds the default Microsimulation, which downloads about 830 MB of microdata, +# only to read parameters. +deselect policyengine_us/tests/policy/baseline/parameters/test_uprating_extensions.py::test_retirement_contribution_limits_include_latest_explicit_irs_values policyengine_us/tests/policy/baseline/gov/states/or/tax/income/credits/test_or_ctc_sunset.py diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 7df05951e..352aaf687 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -158,20 +158,22 @@ jobs: bash ./update_itemization.sh - name: Select the policyengine-us tests run: python core/.github/country_main_tests.py select core/.github/requirements/policyengine-us-main-tests.txt policyengine-us > selected.txt - # Both runs draw the same Hypothesis examples, so a difference between - # them comes from Core. A failing run still writes its report. + # Both runs use the same pytest command (country_main_tests.PYTEST). A + # run whose tests fail goes on to the comparison; one that stops early + # or runs nothing fails here. - name: Run them with the Core release working-directory: policyengine-us run: | uv pip list | grep -i '^policyengine-core ' - xargs uv run --no-sync python -m pytest -p no:cacheprovider --hypothesis-seed=0 --junitxml=../released.xml < ../selected.txt || true + python ../core/.github/country_main_tests.py run ../selected.txt ../released.xml - name: Install this Core working-directory: policyengine-us run: | uv pip install --python .venv/bin/python --reinstall-package policyengine-core ../core uv run --no-sync python -c "import json; from importlib.metadata import distribution; url = json.loads(distribution('policyengine-core').read_text('direct_url.json'))['url']; print(url); assert url.startswith('file://'), url" + uv pip check --python .venv/bin/python - name: Run them with this Core working-directory: policyengine-us - run: xargs uv run --no-sync python -m pytest -p no:cacheprovider --hypothesis-seed=0 --junitxml=../candidate.xml < ../selected.txt || true + run: python ../core/.github/country_main_tests.py run ../selected.txt ../candidate.xml - name: Fail on tests this Core breaks run: python core/.github/country_main_tests.py compare released.xml candidate.xml diff --git a/tests/core/test_country_main_tests.py b/tests/core/test_country_main_tests.py index 2cf14c6ee..e6f8eec35 100644 --- a/tests/core/test_country_main_tests.py +++ b/tests/core/test_country_main_tests.py @@ -2,11 +2,12 @@ It runs policyengine-us main's listed tests with the Core release and then with the Core under test (.github/country_main_tests.py). These tests check -the comparison on synthetic JUnit reports, the file selection, the list, and -the order of the job's steps. +the run's exit handling on real pytest runs, the comparison on synthetic +JUnit reports, the file selection, the list, and the job's steps. """ import importlib.util +import sys from pathlib import Path import pytest @@ -30,6 +31,7 @@ def junit(path, cases): "failed": '', "error": '', "skipped": '', + "uncollected": '', }[outcome] body += f'{child}' path.write_text(f"{body}") @@ -55,34 +57,105 @@ def test_outcomes_count_a_failure_in_any_entry_of_a_test(tmp_path): } -def test_only_tests_failing_with_this_core_alone_are_blamed_on_it(): - released = {"t::a": "passed", "t::b": "failed", "t::c": "skipped"} +def test_compare_sorts_this_cores_failures_and_absences(): + released = { + "t::a": "passed", + "t::b": "failed", + "t::c": "skipped", + "t::gone": "passed", + "t::skipped_gone": "skipped", + "::m.test_x": "failed", # m/test_x.py did not collect + } candidate = { "t::a": "failed", # this Core breaks it - "t::b": "failed", # policyengine-us's own failure + "t::b": "failed", # fails with both Cores "t::c": "failed", # skipped before, fails now "t::d": "failed", # absent before, such as a new collection error "t::e": "passed", + "m.test_x::test_y": "failed", # no release result to compare + } + assert country.compare(released, candidate, {"m.test_x"}) == { + "broken": ["t::a", "t::c", "t::d"], + "missing": ["t::gone"], + "unsure": ["m.test_x::test_y"], + "both": ["t::b"], } - assert country.compare(released, candidate) == ( - ["t::a", "t::c", "t::d"], - ["t::b"], - ) @pytest.mark.parametrize( - "released_cases, candidate_cases, status", + "released_cases, candidate_cases, status, message", [ - ([("t", "a", "passed")], [("t", "a", "failed")], 1), - ([("t", "a", "failed")], [("t", "a", "failed")], 0), - ([("t", "a", "passed")], [("t", "a", "passed")], 0), - (None, [("t", "a", "failed")], 0), - ([("t", "a", "passed")], None, 1), + ( + [("t", "a", "passed")], + [("t", "a", "failed")], + 1, + "::error::This Core breaks t::a", + ), + ( + [("t", "a", "failed")], + [("t", "a", "failed")], + 0, + "::warning::Fails with both Cores: t::a", + ), + ([("t", "a", "passed")], [("t", "a", "passed")], 0, "No test fails"), + ( + [("t", "a", "passed"), ("t", "b", "passed")], + [("t", "a", "passed"), ("t", "b", "skipped")], + 0, + "With this Core: 1 passed, 0 failed, 1 skipped", + ), + ( + [("t", "a", "passed"), ("t", "b", "passed")], + [("t", "a", "passed")], + 1, + "::error::Passed with the Core release but did not run: t::b", + ), + ( + [("t", "a", "passed")], + [], + 1, + "::error::This Core's run recorded no tests.", + ), + ( + None, + [("t", "a", "passed")], + 1, + "::error::The Core release's run wrote no JUnit report.", + ), + ( + [("t", "a", "passed")], + None, + 1, + "::error::This Core's run wrote no JUnit report.", + ), + ( + [("", "t.test_b", "uncollected"), ("t.test_a", "test_x", "passed")], + [("t.test_a", "test_x", "passed"), ("t.test_b", "test_y", "failed")], + 0, + "the Core release could not collect its file: t.test_b::test_y", + ), + ( + [("", "t.test_b", "uncollected"), ("t.test_a", "test_x", "passed")], + [("", "t.test_b", "uncollected"), ("t.test_a", "test_x", "passed")], + 0, + "::warning::Fails with both Cores: ::t.test_b", + ), + ], + ids=[ + "broken", + "fails-with-both", + "passes", + "skipped", + "missing", + "no-tests", + "no-release-report", + "no-report", + "release-could-not-collect", + "neither-could-collect", ], - ids=["broken", "fails-with-both", "passes", "no-release-report", "no-report"], ) -def test_compare_fails_only_on_breaks_or_a_missing_report( - tmp_path, capsys, released_cases, candidate_cases, status +def test_compare_passes_only_when_every_test_ran_and_none_broke( + tmp_path, capsys, released_cases, candidate_cases, status, message ): released = tmp_path / "released.xml" candidate = tmp_path / "candidate.xml" @@ -97,12 +170,54 @@ def test_compare_fails_only_on_breaks_or_a_missing_report( ) == status ) + assert message in capsys.readouterr().out + + +@pytest.mark.parametrize( + "files, status", + [ + ({"test_ok.py": "def test_ok():\n pass\n"}, 0), + ({"test_bad.py": "def test_bad():\n assert False\n"}, 0), + ( + { + "test_ok.py": "def test_ok():\n pass\n", + "test_broken.py": "import a_module_that_does_not_exist\n", + }, + 0, + ), + ({"test_empty.py": ""}, 5), + ({"test_stop.py": "def test_stop():\n raise KeyboardInterrupt\n"}, 2), + ], + ids=["passes", "fails", "collection-error", "no-tests", "interrupted"], +) +def test_run_fails_unless_pytest_ran_every_test( + tmp_path, monkeypatch, capsys, files, status +): + # The job's command, without the Hypothesis seed or its uv environment. + pytest_command = [ + sys.executable, + "-m", + "pytest", + "-p", + "no:cacheprovider", + "--continue-on-collection-errors", + ] + assert set(pytest_command[3:]) < set(country.PYTEST) + assert "--hypothesis-seed=0" in country.PYTEST + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("PYTEST_ADDOPTS", raising=False) + (tmp_path / "pytest.ini").write_text("[pytest]\n") + for name, body in files.items(): + (tmp_path / name).write_text(body) + (tmp_path / "selected.txt").write_text("\n".join(files) + "\n") + assert country.run_tests("selected.txt", "report.xml", pytest_command) == status output = capsys.readouterr().out - if status and candidate_cases is not None: - assert "::error::This Core breaks t::a" in output - assert "**This Core breaks 1:**" in summary.read_text() - if released_cases == candidate_cases == [("t", "a", "failed")]: - assert "::warning::Fails with the Core release too: t::a" in output + assert ("::error::pytest exited" in output) == bool(status) + # pytest writes its report even when it stops early. + assert (tmp_path / "report.xml").exists() + if "test_broken.py" in files: + assert country.collection_errors("report.xml") == {"test_broken"} + assert country.outcomes("report.xml")["test_ok::test_ok"] == "passed" def test_select_skips_files_the_checkout_lacks(tmp_path, capsys): @@ -112,26 +227,32 @@ def test_select_skips_files_the_checkout_lacks(tmp_path, capsys): listing = tmp_path / "list.txt" listing.write_text( "# comment\n\ntests/test_kept.py # trailing comment\ntests/test_gone.py\n" + "deselect tests/test_kept.py::test_slow # downloads data\n" + "deselect tests/test_gone.py::test_other\n" ) assert country.select(listing, repo) == ( - ["tests/test_kept.py"], + ["tests/test_kept.py", "--deselect=tests/test_kept.py::test_slow"], ["tests/test_gone.py"], ) assert country.main(["select", str(listing), str(repo)]) == 0 captured = capsys.readouterr() - assert captured.out == "tests/test_kept.py\n" + assert captured.out == ( + "tests/test_kept.py\n--deselect=tests/test_kept.py::test_slow\n" + ) assert "::warning::policyengine-us main has no tests/test_gone.py" in captured.err - listing.write_text("tests/test_gone.py\n") + listing.write_text("tests/test_gone.py\ndeselect tests/test_gone.py::test_x\n") assert country.main(["select", str(listing), str(repo)]) == 1 def test_the_list_names_distinct_policyengine_us_test_files(): - paths = country.listed_files(LIST) - assert paths, "the list is empty" - assert len(paths) == len(set(paths)), "a file is listed twice" - for path in paths: + files, deselected = country.listed_entries(LIST) + assert files, "the list is empty" + assert len(files) == len(set(files)), "a file is listed twice" + for path in files: assert path.startswith("policyengine_us/tests/"), path assert Path(path).name.startswith("test_") and path.endswith(".py"), path + for test in deselected: + assert test.split("::")[0] in files, test def test_the_job_runs_the_release_then_this_core_and_compares_them(): @@ -152,18 +273,19 @@ def test_the_job_runs_the_release_then_this_core_and_compares_them(): steps = {step["name"]: step for step in job["steps"]} us = steps["Checkout policyengine-us main"]["with"] assert (us["repository"], us["ref"]) == ("PolicyEngine/policyengine-us", "main") + # Both runs go through the script's pytest command and its exit handling. + run = "python ../core/.github/country_main_tests.py run ../selected.txt" released = steps["Run them with the Core release"]["run"] - candidate = steps["Run them with this Core"]["run"] - # The same tests and Hypothesis seed, with separate reports. - assert released.splitlines()[-1].replace("released.xml", "candidate.xml") == ( - candidate - ) - assert "--hypothesis-seed=0" in candidate - # The candidate replaces the release even at the same version number, - # and the job checks that it was installed from this checkout. + assert released.splitlines()[-1] == f"{run} ../released.xml" + assert steps["Run them with this Core"]["run"] == f"{run} ../candidate.xml" + assert all("|| true" not in step.get("run", "") for step in job["steps"]) + # The candidate replaces the release even at the same version number, the + # job checks that it was installed from this checkout, and the dependency + # set must still resolve. install = steps["Install this Core"]["run"] assert "--reinstall-package policyengine-core ../core" in install assert "assert url.startswith('file://')" in install + assert "uv pip check --python .venv/bin/python" in install assert steps["Fail on tests this Core breaks"]["run"].endswith( "compare released.xml candidate.xml" ) From 17a9e6932f2207c88daffcdb7d1418251e546e1e Mon Sep 17 00:00:00 2001 From: ZimingHua Date: Wed, 2 Dec 2026 11:39:02 -0500 Subject: [PATCH 3/5] Show policyengine-us breaks as a neutral check and a PR comment A Core change can need a policyengine-us fix after its release, so a test this Core breaks no longer fails the job. compare writes its result, and the new report step posts a neutral "policyengine-us compatibility" check listing the breaks (successful when there are none) and one bot comment, updated on later runs. A file this Core cannot collect counts as a break. The job still fails when the comparison cannot be trusted: a run wrote no report or no tests, or a test that passed with the release did not run for any reason the reports show. Co-Authored-By: Claude Opus 5.5 --- .github/country_main_tests.py | 210 +++++++++++++++--- .github/workflows/pr.yaml | 17 +- .../test-policyengine-us-main.changed.md | 2 +- tests/core/test_country_main_tests.py | 149 ++++++++++++- 4 files changed, 339 insertions(+), 39 deletions(-) diff --git a/.github/country_main_tests.py b/.github/country_main_tests.py index 2f08e7af7..6fe9b8757 100644 --- a/.github/country_main_tests.py +++ b/.github/country_main_tests.py @@ -15,17 +15,26 @@ policyengine-us renamed or removed. - `run SELECTED REPORT` runs them with a JUnit report. It fails unless pytest ran them to the end, passing or failing. -- `compare RELEASED CANDIDATE` fails on each test that fails with this Core - but did not fail with the release, and on each test that passed with the - release but did not run with this Core. A test that fails with both Cores - is only a warning: policyengine-us main or an earlier Core release broke - it, not this checkout. +- `compare RELEASED CANDIDATE` lists the tests this Core breaks: those that + fail with it but did not fail with the release, and those that passed with + the release in a file this Core cannot collect. A break does not fail the + job, since a Core change can need a policyengine-us fix after its release. + The job fails only when the comparison cannot be trusted: a run wrote no + report or no tests, or a test that passed with the release did not run for + another reason. A test that fails with both Cores is a warning: + policyengine-us main or an earlier Core release broke it. +- `report RESULT` puts compare's result on the PR: a neutral check that + lists the breaks, or a successful one when there are none, and one comment + that lists them, updated on each run. """ import argparse +import json import os import subprocess import sys +import urllib.error +import urllib.request from pathlib import Path from xml.etree import ElementTree @@ -130,38 +139,47 @@ def collection_errors(report): return modules -def compare(released, candidate, uncollected=()): +def in_modules(test, modules): + classname = test.split("::")[0] + return any( + classname == module or classname.startswith(module + ".") for module in modules + ) + + +def compare(released, candidate, uncollected=(), lost=()): """Sort this Core's failures and absences against the release's results. + `uncollected` and `lost` are the modules the release and this Core could + not collect. + - broken: fails with this Core but did not fail with the release. - - missing: passed with the release but did not run with this Core. + - uncollected: passed with the release; this Core cannot collect its file. + - missing: passed with the release but did not run with this Core, for + no reason the reports show. - unsure: fails with this Core in a module the release could not collect, so the release has no result to compare. - both: fails with both Cores. """ - - def uncollected_module(test): - classname = test.split("::")[0] - return any( - classname == module or classname.startswith(module + ".") - for module in uncollected - ) - - result = {"broken": [], "missing": [], "unsure": [], "both": []} + result = { + "broken": [], + "uncollected": [], + "missing": [], + "unsure": [], + "both": [], + } for test, outcome in sorted(candidate.items()): if outcome != "failed": continue if released.get(test) == "failed": result["both"].append(test) - elif test not in released and uncollected_module(test): + elif test not in released and in_modules(test, uncollected): result["unsure"].append(test) else: result["broken"].append(test) - result["missing"] = sorted( - test - for test, outcome in released.items() - if outcome == "passed" and test not in candidate - ) + for test, outcome in sorted(released.items()): + if outcome == "passed" and test not in candidate: + key = "uncollected" if in_modules(test, lost) else "missing" + result[key].append(test) return result @@ -183,6 +201,7 @@ def summary(released, candidate, result): ] titles = { "broken": "**This Core breaks {}:**", + "uncollected": "**Passed with the Core release; this Core cannot collect their file: {}**", "missing": "**Passed with the Core release but did not run with this Core: {}**", "unsure": "Failing with this Core in files the Core release could not collect: {}", "both": "Failing with both Cores: {}", @@ -199,7 +218,7 @@ def summary(released, candidate, result): return "\n".join(lines) + "\n" -def run_compare(released_report, candidate_report, summary_path=None): +def run_compare(released_report, candidate_report, summary_path=None, json_path=None): for name, report in ( ("This Core", candidate_report), ("The Core release", released_report), @@ -212,7 +231,12 @@ def run_compare(released_report, candidate_report, summary_path=None): if not candidate: print("::error::This Core's run recorded no tests.") return 1 - result = compare(released, candidate, collection_errors(released_report)) + result = compare( + released, + candidate, + collection_errors(released_report), + collection_errors(candidate_report), + ) for test in result["both"]: print(f"::warning::Fails with both Cores: {test}") for test in result["unsure"]: @@ -220,16 +244,141 @@ def run_compare(released_report, candidate_report, summary_path=None): "::warning::Fails with this Core; the Core release could not collect " f"its file: {test}" ) + for test in result["broken"] + result["uncollected"]: + print(f"::warning::This Core breaks {test}") for test in result["missing"]: print(f"::error::Passed with the Core release but did not run: {test}") - for test in result["broken"]: - print(f"::error::This Core breaks {test}") text = summary(released, candidate, result) print(text) if summary_path: with open(summary_path, "a") as output: output.write(text) - return 1 if result["broken"] or result["missing"] else 0 + if json_path: + Path(json_path).write_text(json.dumps({**result, "summary": text}, indent=2)) + return 1 if result["missing"] else 0 + + +MARKER = "" +HEADING = "### policyengine-us main against this Core" +CHECK = "policyengine-us compatibility" +BOT = "github-actions[bot]" +LISTED = 50 + + +def github(method, path, payload=None, env=os.environ): + """Call the GitHub REST API with the job's token.""" + request = urllib.request.Request( + env.get("GITHUB_API_URL", "https://api.github.com") + path, + data=None if payload is None else json.dumps(payload).encode(), + method=method, + headers={ + "Authorization": f"Bearer {env['GITHUB_TOKEN']}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + }, + ) + with urllib.request.urlopen(request, timeout=30) as response: + body = response.read() + return json.loads(body) if body else None + + +def find_comment(api, repo, number): + """The comment an earlier run of this job left on the PR, if any.""" + page = 1 + while True: + comments = api( + "GET", f"/repos/{repo}/issues/{number}/comments?per_page=100&page={page}" + ) + for comment in comments: + if comment["user"]["login"] == BOT and MARKER in comment["body"]: + return comment + if len(comments) < 100: + return None + page = page + 1 + + +def break_comment(breaks, where): + noun, verb = ("test", "passes") if len(breaks) == 1 else ("tests", "pass") + lines = [ + MARKER, + HEADING, + "", + f"This Core breaks {len(breaks)} policyengine-us {noun} that {verb} with " + "the Core release:", + "", + *(f"- `{test}`" for test in breaks[:LISTED]), + ] + if len(breaks) > LISTED: + lines.append(f"- ...and {len(breaks) - LISTED} more in the job summary.") + lines += [ + "", + "If the change is intended, merge it and fix these tests in " + "policyengine-us right after the release: policyengine-us CI installs " + "each new Core release.", + "", + f"Checked at {where}.", + ] + return "\n".join(lines) + "\n" + + +def report(result_path, env=os.environ, api=None): + """Put compare's result on the PR as a check and, for breaks, a comment. + + A break is a neutral check, not a failure: the change may be intended. + Without write access, as on a PR from a fork, it warns and leaves the + result in the job summary. + """ + if api is None: + + def api(method, path, payload=None): + return github(method, path, payload, env) + + result = json.loads(Path(result_path).read_text()) + breaks = result["broken"] + result["uncollected"] + repo, sha, number = env["GITHUB_REPOSITORY"], env["HEAD_SHA"], env["PR_NUMBER"] + where = f"`{sha[:7]}` ([run]({env['RUN_URL']}))" + noun = "test" if len(breaks) == 1 else "tests" + title = ( + f"This Core breaks {len(breaks)} policyengine-us {noun}" + if breaks + else "No policyengine-us test breaks" + ) + try: + api( + "POST", + f"/repos/{repo}/check-runs", + { + "name": CHECK, + "head_sha": sha, + "status": "completed", + "conclusion": "neutral" if breaks else "success", + "output": {"title": title, "summary": result["summary"][:65000]}, + }, + ) + comment = find_comment(api, repo, number) + if breaks: + body = break_comment(breaks, where) + elif comment: + body = ( + f"{MARKER}\n{HEADING}\n\nNo policyengine-us test breaks with this " + f"Core any more, as of {where}.\n" + ) + else: + return 0 + if comment: + api( + "PATCH", + f"/repos/{repo}/issues/comments/{comment['id']}", + {"body": body}, + ) + else: + api("POST", f"/repos/{repo}/issues/{number}/comments", {"body": body}) + except urllib.error.URLError as error: + print( + f"::warning::Could not report on the PR ({error}); the job summary " + "has the result." + ) + return 0 def main(argv=None): @@ -249,6 +398,9 @@ def main(argv=None): default=os.environ.get("GITHUB_STEP_SUMMARY"), help="file to append a Markdown summary to", ) + checker.add_argument("--json", help="file to write the result to for report") + reporter = commands.add_parser("report", help="put the result on the PR") + reporter.add_argument("result") args = parser.parse_args(argv) if args.command == "select": arguments, missing = select(args.list, args.repo) @@ -265,7 +417,9 @@ def main(argv=None): return 0 if args.command == "run": return run_tests(args.selected, args.report) - return run_compare(args.released, args.candidate, args.summary) + if args.command == "report": + return report(args.result) + return run_compare(args.released, args.candidate, args.summary, args.json) if __name__ == "__main__": diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 352aaf687..168e61f70 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -128,6 +128,9 @@ jobs: timeout-minutes: 30 permissions: contents: read + # The result goes on the PR as a check and a comment. + checks: write + pull-requests: write env: PYTHONUNBUFFERED: 1 steps: @@ -175,5 +178,15 @@ jobs: - name: Run them with this Core working-directory: policyengine-us run: python ../core/.github/country_main_tests.py run ../selected.txt ../candidate.xml - - name: Fail on tests this Core breaks - run: python core/.github/country_main_tests.py compare released.xml candidate.xml + # A test this Core breaks is a warning here and a neutral check on the + # PR, since the change may be intended; a comparison that cannot be + # trusted fails the job. + - name: Compare the two runs + run: python core/.github/country_main_tests.py compare released.xml candidate.xml --json result.json + - name: Report the result on the PR + env: + GITHUB_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: python core/.github/country_main_tests.py report result.json diff --git a/changelog.d/test-policyengine-us-main.changed.md b/changelog.d/test-policyengine-us-main.changed.md index 52ab3be87..6203d3d85 100644 --- a/changelog.d/test-policyengine-us-main.changed.md +++ b/changelog.d/test-policyengine-us-main.changed.md @@ -1 +1 @@ -Add a PR job that runs policyengine-us main's Core-facing tests with the Core release and then with the Core under test, and fails on tests the change breaks. +Add a PR job that runs policyengine-us main's Core-facing tests with the Core release and then with the Core under test. Tests the change breaks appear as a neutral check and a PR comment; the job fails only when a run is incomplete. diff --git a/tests/core/test_country_main_tests.py b/tests/core/test_country_main_tests.py index e6f8eec35..b758a33d2 100644 --- a/tests/core/test_country_main_tests.py +++ b/tests/core/test_country_main_tests.py @@ -8,6 +8,7 @@ import importlib.util import sys +import urllib.error from pathlib import Path import pytest @@ -65,6 +66,7 @@ def test_compare_sorts_this_cores_failures_and_absences(): "t::gone": "passed", "t::skipped_gone": "skipped", "::m.test_x": "failed", # m/test_x.py did not collect + "n.test_z::test_w": "passed", } candidate = { "t::a": "failed", # this Core breaks it @@ -73,9 +75,11 @@ def test_compare_sorts_this_cores_failures_and_absences(): "t::d": "failed", # absent before, such as a new collection error "t::e": "passed", "m.test_x::test_y": "failed", # no release result to compare + "::n.test_z": "failed", # this Core cannot collect n/test_z.py } - assert country.compare(released, candidate, {"m.test_x"}) == { - "broken": ["t::a", "t::c", "t::d"], + assert country.compare(released, candidate, {"m.test_x"}, {"n.test_z"}) == { + "broken": ["::n.test_z", "t::a", "t::c", "t::d"], + "uncollected": ["n.test_z::test_w"], "missing": ["t::gone"], "unsure": ["m.test_x::test_y"], "both": ["t::b"], @@ -88,8 +92,14 @@ def test_compare_sorts_this_cores_failures_and_absences(): ( [("t", "a", "passed")], [("t", "a", "failed")], - 1, - "::error::This Core breaks t::a", + 0, + "::warning::This Core breaks t::a", + ), + ( + [("t.test_b", "test_y", "passed"), ("t.test_a", "test_x", "passed")], + [("", "t.test_b", "uncollected"), ("t.test_a", "test_x", "passed")], + 0, + "::warning::This Core breaks t.test_b::test_y", ), ( [("t", "a", "failed")], @@ -143,6 +153,7 @@ def test_compare_sorts_this_cores_failures_and_absences(): ], ids=[ "broken", + "this-core-could-not-collect", "fails-with-both", "passes", "skipped", @@ -154,7 +165,7 @@ def test_compare_sorts_this_cores_failures_and_absences(): "neither-could-collect", ], ) -def test_compare_passes_only_when_every_test_ran_and_none_broke( +def test_compare_fails_only_when_the_comparison_cannot_be_trusted( tmp_path, capsys, released_cases, candidate_cases, status, message ): released = tmp_path / "released.xml" @@ -173,6 +184,115 @@ def test_compare_passes_only_when_every_test_ran_and_none_broke( assert message in capsys.readouterr().out +class FakeGitHub: + """Records API calls; GET returns the PR's comments.""" + + def __init__(self, comments=(), refuse=False): + self.comments = list(comments) + self.refuse = refuse + self.calls = [] + + def __call__(self, method, path, payload=None): + self.calls.append((method, path, payload)) + if self.refuse: + raise urllib.error.HTTPError(path, 403, "Forbidden", None, None) + return self.comments if method == "GET" else {} + + def writes(self): + return [ + (method, path, payload) + for method, path, payload in self.calls + if method != "GET" + ] + + +ENV = { + "GITHUB_REPOSITORY": "PolicyEngine/policyengine-core", + "HEAD_SHA": "abcdef1234567890", + "PR_NUMBER": "635", + "RUN_URL": "https://github.com/PolicyEngine/policyengine-core/actions/runs/1", +} +BOT_COMMENT = { + "id": 7, + "user": {"login": "github-actions[bot]"}, + "body": f"{country.MARKER}\nold result", +} + + +def compared(tmp_path, candidate_outcome): + junit(tmp_path / "released.xml", [("t", "a", "passed")]) + junit(tmp_path / "candidate.xml", [("t", "a", candidate_outcome)]) + result = tmp_path / "result.json" + arguments = [ + "compare", + str(tmp_path / "released.xml"), + str(tmp_path / "candidate.xml"), + ] + arguments += ["--summary", str(tmp_path / "summary.md"), "--json", str(result)] + assert country.main(arguments) == 0 + return result + + +@pytest.mark.parametrize( + "candidate_outcome, comments, conclusion, comment_call", + [ + ("failed", [], "neutral", "POST"), + ("failed", [BOT_COMMENT], "neutral", "PATCH"), + ("passed", [], "success", None), + ("passed", [BOT_COMMENT], "success", "PATCH"), + ( + "failed", + [{**BOT_COMMENT, "user": {"login": "someone"}}], + "neutral", + "POST", + ), + ], + ids=[ + "break-new-comment", + "break-updates-comment", + "no-break-no-comment", + "fixed-updates-comment", + "ignores-other-authors", + ], +) +def test_report_shows_breaks_as_a_neutral_check_and_one_comment( + tmp_path, candidate_outcome, comments, conclusion, comment_call +): + github = FakeGitHub(comments) + result = compared(tmp_path, candidate_outcome) + assert country.report(result, ENV, github) == 0 + (check, *comment) = github.writes() + assert check[:2] == ("POST", "/repos/PolicyEngine/policyengine-core/check-runs") + assert check[2]["name"] == "policyengine-us compatibility" + assert check[2]["head_sha"] == ENV["HEAD_SHA"] + assert check[2]["conclusion"] == conclusion + if comment_call is None: + assert comment == [] + return + ((method, path, payload),) = comment + assert method == comment_call + assert path == ( + "/repos/PolicyEngine/policyengine-core/issues/comments/7" + if method == "PATCH" + else "/repos/PolicyEngine/policyengine-core/issues/635/comments" + ) + assert payload["body"].startswith(country.MARKER) + if conclusion == "neutral": + assert "This Core breaks 1 policyengine-us test that" in payload["body"] + assert "- `t::a`" in payload["body"] + else: + assert ( + "No policyengine-us test breaks with this Core any more" in payload["body"] + ) + assert "`abcdef1`" in payload["body"] + + +def test_report_warns_without_write_access(tmp_path, capsys): + github = FakeGitHub(refuse=True) + assert country.report(compared(tmp_path, "failed"), ENV, github) == 0 + assert "::warning::Could not report on the PR" in capsys.readouterr().out + + @pytest.mark.parametrize( "files, status", [ @@ -268,7 +388,8 @@ def test_the_job_runs_the_release_then_this_core_and_compares_them(): "Run them with the Core release", "Install this Core", "Run them with this Core", - "Fail on tests this Core breaks", + "Compare the two runs", + "Report the result on the PR", ] steps = {step["name"]: step for step in job["steps"]} us = steps["Checkout policyengine-us main"]["with"] @@ -286,6 +407,18 @@ def test_the_job_runs_the_release_then_this_core_and_compares_them(): assert "--reinstall-package policyengine-core ../core" in install assert "assert url.startswith('file://')" in install assert "uv pip check --python .venv/bin/python" in install - assert steps["Fail on tests this Core breaks"]["run"].endswith( - "compare released.xml candidate.xml" + assert steps["Compare the two runs"]["run"].endswith( + "compare released.xml candidate.xml --json result.json" + ) + # The result goes on the PR's head commit as a check, and as a comment. + report = steps["Report the result on the PR"] + assert ( + report["run"] == "python core/.github/country_main_tests.py report result.json" ) + assert report["env"]["HEAD_SHA"] == "${{ github.event.pull_request.head.sha }}" + assert report["env"]["PR_NUMBER"] == "${{ github.event.pull_request.number }}" + assert job["permissions"] == { + "contents": "read", + "checks": "write", + "pull-requests": "write", + } From a08b1308da40903fd2a33ff43000954d16e2e80f Mon Sep 17 00:00:00 2001 From: ZimingHua Date: Wed, 2 Dec 2026 13:43:20 -0500 Subject: [PATCH 4/5] Require a release baseline, list newly skipped tests, write the job summary - compare fails when the Core release's run collected no tests (only collection errors), instead of calling every entry a failure with both Cores and reporting no breaks. - A test that passed with the release and is skipped with this Core is a warning and listed in the check summary. - The compare step appends its result to the job summary, which the PR comment and the no-write-access warning point to. Co-Authored-By: Claude Opus 5.5 --- .github/country_main_tests.py | 45 ++++++++++++++++++++++----- .github/workflows/pr.yaml | 5 +-- tests/core/test_country_main_tests.py | 19 +++++++++-- 3 files changed, 56 insertions(+), 13 deletions(-) diff --git a/.github/country_main_tests.py b/.github/country_main_tests.py index 6fe9b8757..5fc3ed919 100644 --- a/.github/country_main_tests.py +++ b/.github/country_main_tests.py @@ -20,9 +20,11 @@ the release in a file this Core cannot collect. A break does not fail the job, since a Core change can need a policyengine-us fix after its release. The job fails only when the comparison cannot be trusted: a run wrote no - report or no tests, or a test that passed with the release did not run for - another reason. A test that fails with both Cores is a warning: - policyengine-us main or an earlier Core release broke it. + report, the release's run collected no tests, this Core's run recorded + none, or a test that passed with the release did not run for another + reason. A test that fails with both Cores is a warning: policyengine-us + main or an earlier Core release broke it. So is a test that passed with + the release and is skipped with this Core, since its coverage is lost. - `report RESULT` puts compare's result on the PR: a neutral check that lists the breaks, or a successful one when there are none, and one comment that lists them, updated on each run. @@ -122,6 +124,19 @@ def outcomes(report): return results +def is_collection_error(case): + return any( + child.tag == "error" and child.get("message") == "collection failure" + for child in case + ) + + +def collected_any(report): + """Whether a JUnit report has a test entry, not only collection errors.""" + cases = ElementTree.parse(report).getroot().iter("testcase") + return any(not is_collection_error(case) for case in cases) + + def collection_errors(report): """The modules a JUnit report could not collect, as dotted paths. @@ -130,10 +145,7 @@ def collection_errors(report): """ modules = set() for case in ElementTree.parse(report).getroot().iter("testcase"): - if any( - child.tag == "error" and child.get("message") == "collection failure" - for child in case - ): + if is_collection_error(case): parts = (case.get("classname", ""), case.get("name", "")) modules.add(".".join(part for part in parts if part)) return modules @@ -156,6 +168,7 @@ def compare(released, candidate, uncollected=(), lost=()): - uncollected: passed with the release; this Core cannot collect its file. - missing: passed with the release but did not run with this Core, for no reason the reports show. + - skipped: passed with the release and is skipped with this Core. - unsure: fails with this Core in a module the release could not collect, so the release has no result to compare. - both: fails with both Cores. @@ -164,6 +177,7 @@ def compare(released, candidate, uncollected=(), lost=()): "broken": [], "uncollected": [], "missing": [], + "skipped": [], "unsure": [], "both": [], } @@ -177,9 +191,13 @@ def compare(released, candidate, uncollected=(), lost=()): else: result["broken"].append(test) for test, outcome in sorted(released.items()): - if outcome == "passed" and test not in candidate: + if outcome != "passed": + continue + if test not in candidate: key = "uncollected" if in_modules(test, lost) else "missing" result[key].append(test) + elif candidate[test] == "skipped": + result["skipped"].append(test) return result @@ -203,6 +221,7 @@ def summary(released, candidate, result): "broken": "**This Core breaks {}:**", "uncollected": "**Passed with the Core release; this Core cannot collect their file: {}**", "missing": "**Passed with the Core release but did not run with this Core: {}**", + "skipped": "Passed with the Core release; skipped with this Core: {}", "unsure": "Failing with this Core in files the Core release could not collect: {}", "both": "Failing with both Cores: {}", } @@ -226,6 +245,12 @@ def run_compare(released_report, candidate_report, summary_path=None, json_path= if not Path(report).exists(): print(f"::error::{name}'s run wrote no JUnit report.") return 1 + if not collected_any(released_report): + print( + "::error::The Core release's run collected no tests, so there is " + "nothing to compare this Core with." + ) + return 1 released = outcomes(released_report) candidate = outcomes(candidate_report) if not candidate: @@ -246,6 +271,10 @@ def run_compare(released_report, candidate_report, summary_path=None, json_path= ) for test in result["broken"] + result["uncollected"]: print(f"::warning::This Core breaks {test}") + for test in result["skipped"]: + print( + f"::warning::Passed with the Core release; skipped with this Core: {test}" + ) for test in result["missing"]: print(f"::error::Passed with the Core release but did not run: {test}") text = summary(released, candidate, result) diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 168e61f70..8e6634811 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -180,9 +180,10 @@ jobs: run: python ../core/.github/country_main_tests.py run ../selected.txt ../candidate.xml # A test this Core breaks is a warning here and a neutral check on the # PR, since the change may be intended; a comparison that cannot be - # trusted fails the job. + # trusted fails the job. The job summary keeps the full result, which + # PRs from forks cannot post. - name: Compare the two runs - run: python core/.github/country_main_tests.py compare released.xml candidate.xml --json result.json + run: python core/.github/country_main_tests.py compare released.xml candidate.xml --summary "$GITHUB_STEP_SUMMARY" --json result.json - name: Report the result on the PR env: GITHUB_TOKEN: ${{ github.token }} diff --git a/tests/core/test_country_main_tests.py b/tests/core/test_country_main_tests.py index b758a33d2..1cfddd3fe 100644 --- a/tests/core/test_country_main_tests.py +++ b/tests/core/test_country_main_tests.py @@ -65,6 +65,7 @@ def test_compare_sorts_this_cores_failures_and_absences(): "t::c": "skipped", "t::gone": "passed", "t::skipped_gone": "skipped", + "t::f": "passed", "::m.test_x": "failed", # m/test_x.py did not collect "n.test_z::test_w": "passed", } @@ -74,6 +75,7 @@ def test_compare_sorts_this_cores_failures_and_absences(): "t::c": "failed", # skipped before, fails now "t::d": "failed", # absent before, such as a new collection error "t::e": "passed", + "t::f": "skipped", # passed before, skipped now "m.test_x::test_y": "failed", # no release result to compare "::n.test_z": "failed", # this Core cannot collect n/test_z.py } @@ -81,6 +83,7 @@ def test_compare_sorts_this_cores_failures_and_absences(): "broken": ["::n.test_z", "t::a", "t::c", "t::d"], "uncollected": ["n.test_z::test_w"], "missing": ["t::gone"], + "skipped": ["t::f"], "unsure": ["m.test_x::test_y"], "both": ["t::b"], } @@ -112,7 +115,7 @@ def test_compare_sorts_this_cores_failures_and_absences(): [("t", "a", "passed"), ("t", "b", "passed")], [("t", "a", "passed"), ("t", "b", "skipped")], 0, - "With this Core: 1 passed, 0 failed, 1 skipped", + "Passed with the Core release; skipped with this Core: 1\n- `t::b`", ), ( [("t", "a", "passed"), ("t", "b", "passed")], @@ -150,19 +153,26 @@ def test_compare_sorts_this_cores_failures_and_absences(): 0, "::warning::Fails with both Cores: ::t.test_b", ), + ( + [("", "t.test_b", "uncollected")], + [("", "t.test_b", "uncollected")], + 1, + "::error::The Core release's run collected no tests", + ), ], ids=[ "broken", "this-core-could-not-collect", "fails-with-both", "passes", - "skipped", + "newly-skipped", "missing", "no-tests", "no-release-report", "no-report", "release-could-not-collect", "neither-could-collect", + "release-collected-nothing", ], ) def test_compare_fails_only_when_the_comparison_cannot_be_trusted( @@ -407,8 +417,11 @@ def test_the_job_runs_the_release_then_this_core_and_compares_them(): assert "--reinstall-package policyengine-core ../core" in install assert "assert url.startswith('file://')" in install assert "uv pip check --python .venv/bin/python" in install + # The job summary has the full result, as the PR comment and the warning + # without write access say. assert steps["Compare the two runs"]["run"].endswith( - "compare released.xml candidate.xml --json result.json" + 'compare released.xml candidate.xml --summary "$GITHUB_STEP_SUMMARY" ' + "--json result.json" ) # The result goes on the PR's head commit as a check, and as a comment. report = steps["Report the result on the PR"] From d45823a42c87dda5822ae1ea91200d6227a0608b Mon Sep 17 00:00:00 2001 From: ZimingHua Date: Wed, 2 Dec 2026 14:18:50 -0500 Subject: [PATCH 5/5] Treat module-level skips as collection entries, not tests - The release-baseline check ignores modules that skipped themselves while being collected, as it ignores modules that failed to import, so a release run with only those entries fails the job instead of reporting no breaks. - Tests in a module this Core skips while collecting are newly skipped (a warning, listed in the check) rather than missing (a job failure). Co-Authored-By: Claude Opus 5.5 --- .github/country_main_tests.py | 54 +++++++++++++++------------ tests/core/test_country_main_tests.py | 16 ++++++-- 2 files changed, 44 insertions(+), 26 deletions(-) diff --git a/.github/country_main_tests.py b/.github/country_main_tests.py index 5fc3ed919..b8afe986d 100644 --- a/.github/country_main_tests.py +++ b/.github/country_main_tests.py @@ -124,28 +124,31 @@ def outcomes(report): return results -def is_collection_error(case): - return any( - child.tag == "error" and child.get("message") == "collection failure" - for child in case - ) +# pytest's JUnit report records a module it could not collect, or one that +# skipped itself while being collected, as one entry whose name is the module +# and whose class name is empty. Neither entry is a test. +COLLECTION_FAILURE = ("error", "collection failure") +COLLECTION_SKIP = ("skipped", "collection skipped") -def collected_any(report): - """Whether a JUnit report has a test entry, not only collection errors.""" - cases = ElementTree.parse(report).getroot().iter("testcase") - return any(not is_collection_error(case) for case in cases) +def records(case, kind): + tag, message = kind + return any(child.tag == tag and child.get("message") == message for child in case) -def collection_errors(report): - """The modules a JUnit report could not collect, as dotted paths. +def collected_any(report): + """Whether a JUnit report records a test, not only collection entries.""" + return any( + not records(case, COLLECTION_FAILURE) and not records(case, COLLECTION_SKIP) + for case in ElementTree.parse(report).getroot().iter("testcase") + ) - pytest records a module's collection error as one entry whose name is - the module and whose class name is empty. - """ + +def collection_entries(report, kind): + """The modules a JUnit report records as a collection failure or skip.""" modules = set() for case in ElementTree.parse(report).getroot().iter("testcase"): - if is_collection_error(case): + if records(case, kind): parts = (case.get("classname", ""), case.get("name", "")) modules.add(".".join(part for part in parts if part)) return modules @@ -158,11 +161,11 @@ def in_modules(test, modules): ) -def compare(released, candidate, uncollected=(), lost=()): +def compare(released, candidate, uncollected=(), lost=(), skipped_modules=()): """Sort this Core's failures and absences against the release's results. `uncollected` and `lost` are the modules the release and this Core could - not collect. + not collect; `skipped_modules`, those this Core skipped while collecting. - broken: fails with this Core but did not fail with the release. - uncollected: passed with the release; this Core cannot collect its file. @@ -193,11 +196,15 @@ def compare(released, candidate, uncollected=(), lost=()): for test, outcome in sorted(released.items()): if outcome != "passed": continue - if test not in candidate: - key = "uncollected" if in_modules(test, lost) else "missing" - result[key].append(test) - elif candidate[test] == "skipped": + if test in candidate: + if candidate[test] == "skipped": + result["skipped"].append(test) + elif in_modules(test, lost): + result["uncollected"].append(test) + elif in_modules(test, skipped_modules): result["skipped"].append(test) + else: + result["missing"].append(test) return result @@ -259,8 +266,9 @@ def run_compare(released_report, candidate_report, summary_path=None, json_path= result = compare( released, candidate, - collection_errors(released_report), - collection_errors(candidate_report), + collection_entries(released_report, COLLECTION_FAILURE), + collection_entries(candidate_report, COLLECTION_FAILURE), + collection_entries(candidate_report, COLLECTION_SKIP), ) for test in result["both"]: print(f"::warning::Fails with both Cores: {test}") diff --git a/tests/core/test_country_main_tests.py b/tests/core/test_country_main_tests.py index 1cfddd3fe..c47febfe0 100644 --- a/tests/core/test_country_main_tests.py +++ b/tests/core/test_country_main_tests.py @@ -33,6 +33,7 @@ def junit(path, cases): "error": '', "skipped": '', "uncollected": '', + "module-skipped": '', }[outcome] body += f'{child}' path.write_text(f"{body}") @@ -117,6 +118,12 @@ def test_compare_sorts_this_cores_failures_and_absences(): 0, "Passed with the Core release; skipped with this Core: 1\n- `t::b`", ), + ( + [("t.test_b", "test_y", "passed"), ("t.test_a", "test_x", "passed")], + [("", "t.test_b", "module-skipped"), ("t.test_a", "test_x", "passed")], + 0, + "skipped with this Core: 1\n- `t.test_b::test_y`", + ), ( [("t", "a", "passed"), ("t", "b", "passed")], [("t", "a", "passed")], @@ -154,8 +161,8 @@ def test_compare_sorts_this_cores_failures_and_absences(): "::warning::Fails with both Cores: ::t.test_b", ), ( - [("", "t.test_b", "uncollected")], - [("", "t.test_b", "uncollected")], + [("", "t.test_b", "uncollected"), ("", "t.test_c", "module-skipped")], + [("", "t.test_b", "uncollected"), ("", "t.test_c", "module-skipped")], 1, "::error::The Core release's run collected no tests", ), @@ -166,6 +173,7 @@ def test_compare_sorts_this_cores_failures_and_absences(): "fails-with-both", "passes", "newly-skipped", + "this-core-skipped-the-file", "missing", "no-tests", "no-release-report", @@ -346,7 +354,9 @@ def test_run_fails_unless_pytest_ran_every_test( # pytest writes its report even when it stops early. assert (tmp_path / "report.xml").exists() if "test_broken.py" in files: - assert country.collection_errors("report.xml") == {"test_broken"} + assert country.collection_entries("report.xml", country.COLLECTION_FAILURE) == { + "test_broken" + } assert country.outcomes("report.xml")["test_ok::test_ok"] == "passed"