diff --git a/.github/country_main_tests.py b/.github/country_main_tests.py new file mode 100644 index 000000000..b8afe986d --- /dev/null +++ b/.github/country_main_tests.py @@ -0,0 +1,463 @@ +#!/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 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` 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, 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. +""" + +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 + +# 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_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.startswith(DESELECT): + deselected.append(line.removeprefix(DESELECT).strip()) + elif line: + files.append(line) + return files, deselected + + +def select(list_path, repo): + """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): + """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 + + +# 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 records(case, kind): + tag, message = kind + return any(child.tag == tag and child.get("message") == message for child in case) + + +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") + ) + + +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 records(case, kind): + parts = (case.get("classname", ""), case.get("name", "")) + modules.add(".".join(part for part in parts if part)) + return modules + + +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=(), 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; `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. + - 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. + """ + result = { + "broken": [], + "uncollected": [], + "missing": [], + "skipped": [], + "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 in_modules(test, uncollected): + result["unsure"].append(test) + else: + result["broken"].append(test) + for test, outcome in sorted(released.items()): + if outcome != "passed": + continue + 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 + + +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"- With the Core release: {tally(released)}", + f"- With this Core: {tally(candidate)}", + "", + ] + 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: {}**", + "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: {}", + } + 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, json_path=None): + 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 + 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: + print("::error::This Core's run recorded no tests.") + return 1 + result = compare( + released, + candidate, + 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}") + for test in result["unsure"]: + print( + "::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["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) + print(text) + if summary_path: + with open(summary_path, "a") as output: + output.write(text) + 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): + 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 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") + checker.add_argument( + "--summary", + 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) + 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 any(not argument.startswith("--") for argument in arguments): + print("::error::None of the listed files exist.", file=sys.stderr) + return 1 + print("\n".join(arguments)) + return 0 + if args.command == "run": + return run_tests(args.selected, args.report) + if args.command == "report": + return report(args.result) + return run_compare(args.released, args.candidate, args.summary, args.json) + + +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..c30296a88 --- /dev/null +++ b/.github/requirements/policyengine-us-main-tests.txt @@ -0,0 +1,30 @@ +# 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. 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 +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 +# 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 c90189cb6..8e6634811 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,73 @@ 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 + # The result goes on the PR as a check and a comment. + checks: write + pull-requests: write + 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 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 ' + 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: 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. 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 --summary "$GITHUB_STEP_SUMMARY" --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 new file mode 100644 index 000000000..6203d3d85 --- /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. 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 new file mode 100644 index 000000000..c47febfe0 --- /dev/null +++ b/tests/core/test_country_main_tests.py @@ -0,0 +1,447 @@ +"""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 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 +import urllib.error +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": '', + "uncollected": '', + "module-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_compare_sorts_this_cores_failures_and_absences(): + released = { + "t::a": "passed", + "t::b": "failed", + "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", + } + candidate = { + "t::a": "failed", # this Core breaks it + "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", + "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 + } + 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"], + "skipped": ["t::f"], + "unsure": ["m.test_x::test_y"], + "both": ["t::b"], + } + + +@pytest.mark.parametrize( + "released_cases, candidate_cases, status, message", + [ + ( + [("t", "a", "passed")], + [("t", "a", "failed")], + 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")], + [("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, + "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")], + 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", + ), + ( + [("", "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", + ), + ], + ids=[ + "broken", + "this-core-could-not-collect", + "fails-with-both", + "passes", + "newly-skipped", + "this-core-skipped-the-file", + "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( + tmp_path, capsys, released_cases, candidate_cases, status, message +): + 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 + ) + 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", + [ + ({"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 + 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_entries("report.xml", country.COLLECTION_FAILURE) == { + "test_broken" + } + assert country.outcomes("report.xml")["test_ok::test_ok"] == "passed" + + +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" + "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", "--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--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\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(): + 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(): + 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", + "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"] + 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"] + 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 + # 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 --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"] + 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", + }