Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(impacted-tests): select the tests a change needs in CI, and run everything whenever that is not certain (#2665)
Raghav Chamadiya7d5782d0fce4
diff --git a/action.yml b/action.ymlindex 2627494ca..4bcf8b6b7 100644--- a/action.yml+++ b/action.yml@@ -1,7 +1,8 @@name: Repowise CI gatesdescription: >-Gate a pull request on patch coverage, documentation drift, new security- findings and change risk. Needs git and nothing else: no index, no API key.+ findings and change risk, and select the tests it needs. The gates need git+ and nothing else (no index, no API key); test selection reads a cached index.author: repowise-devbranding:icon: check-circle@@ -97,6 +98,17 @@ inputs:"true" uploads doc-drift and security findings to GitHub code scanning.The workflow needs the security-events write permission.default: "false"+ impacted-tests:+ description: >-+ "true" selects the tests the change needs (repowise impacted-tests+ --format args) and sets the impacted-tests and run-all-tests outputs. It+ requires a cached Repowise index: restore .repowise into the working+ directory first, and the step brings it up to date with repowise update+ --index-only. Without one every answer is run-all-tests, with the reason.+ default: "false"+ impacted-tests-runner:+ description: Runner the tests output is written for (auto, pytest, go, jest or files).+ default: autooutputs:coverage:@@ -114,6 +126,15 @@ outputs:sarif-dir:description: Directory holding the SARIF files, when upload-sarif is on.value: ${{ steps.gates.outputs.sarif-dir }}+ impacted-tests:+ description: With impacted-tests, the runner arguments for the selected tests, or ":all" to run every test.+ value: ${{ steps.impacted.outputs.impacted-tests }}+ run-all-tests:+ description: >-+ With impacted-tests, "false" only when the subset is safe to run alone;+ "true" when every test must run, also when selection could not run.+ Branch on != 'false' so a skipped step runs everything.+ value: ${{ steps.impacted.outputs.run-all-tests }}runs:using: composite@@ -128,8 +149,21 @@ runs:REPOWISE_VERSION: ${{ inputs.version }}run: python -m pip install --quiet "repowise${REPOWISE_VERSION:+==$REPOWISE_VERSION}"+ - name: Select impacted tests+ id: impacted+ if: inputs.impacted-tests == 'true'+ shell: bash+ working-directory: ${{ inputs.working-directory }}+ env:+ BASE: ${{ inputs.base }}+ RUNNER: ${{ inputs.impacted-tests-runner }}+ PYTHONUTF8: "1"+ run: bash "$GITHUB_ACTION_PATH/ci/github/impacted-tests.sh"+- name: Run gatesid: gates+ # Test selection alone runs no gate.+ if: inputs.checks != '' || inputs.impacted-tests != 'true'shell: bashworking-directory: ${{ inputs.working-directory }}env:diff --git a/ci/github/fetch-base.sh b/ci/github/fetch-base.shnew file mode 100644index 000000000..a5400b257--- /dev/null+++ b/ci/github/fetch-base.sh@@ -0,0 +1,10 @@+# Sourced by run-gates.sh and impacted-tests.sh. A diff against the pull+# request's target needs its history and the target branch, and a shallow clone+# has neither; fetch them rather than fail to evaluate.++if [[ "$(git rev-parse --is-shallow-repository)" == "true" ]]; then+ git fetch --quiet --no-tags --unshallow origin || true+fi+if [[ -n "${GITHUB_BASE_REF:-}" ]] && ! git rev-parse --verify --quiet "refs/remotes/origin/$GITHUB_BASE_REF" >/dev/null; then+ git fetch --quiet --no-tags origin "+refs/heads/$GITHUB_BASE_REF:refs/remotes/origin/$GITHUB_BASE_REF" || true+fidiff --git a/ci/github/impacted-tests.sh b/ci/github/impacted-tests.shnew file mode 100644index 000000000..4dbd15503--- /dev/null+++ b/ci/github/impacted-tests.sh@@ -0,0 +1,58 @@+#!/usr/bin/env bash+# Selects the tests a change needs, for the composite action in action.yml.+#+# Sets two step outputs: impacted-tests (runner arguments, or ":all") and+# run-all-tests ("true" or "false"). It fails closed: when the cached index+# cannot be updated, selection cannot run, or its output is not one line, the+# outputs say run everything and a warning says why; the step never fails.+# Inputs arrive as environment variables set by action.yml.++set -u++here=${0//\\//}+source "${here%/*}/fetch-base.sh"++# write TESTS RUN_ALL: both outputs, the arguments in delimiter form so no+# value can be read as another output.+write() {+ local delim="REPOWISE_${RANDOM}${RANDOM}"+ {+ echo "impacted-tests<<$delim"+ echo "$1"+ echo "$delim"+ echo "run-all-tests=$2"+ } >>"$GITHUB_OUTPUT"+}++run_everything() {+ echo "::warning::$1; running every test."+ write ":all" true+ exit 0+}++# A restored cache is behind the change; bring it up to date first.+if [[ -f .repowise/state.json ]]; then+ echo "::group::repowise update --index-only"+ repowise update --index-only+ code=$?+ echo "::endgroup::"+ ((code == 0)) || run_everything "The cached index could not be updated (exit $code)"+fi++args=(impacted-tests)+[[ -n "$BASE" ]] && args+=("$BASE")+args+=(--format args --runner "${RUNNER:-auto}")++echo "::group::repowise impacted-tests"+tests=$(repowise "${args[@]}")+code=$?+echo "::endgroup::"++((code == 0)) || run_everything "Test selection could not run (exit $code)"+[[ "$tests" != *$'\n'* ]] || run_everything "Test selection printed more than one line"+if [[ "$tests" == ":all" ]]; then+ write ":all" true+else+ write "$tests" false+fi+exit 0diff --git a/ci/github/run-gates.sh b/ci/github/run-gates.shindex d7beb8db0..7bccfe5d4 100644--- a/ci/github/run-gates.sh+++ b/ci/github/run-gates.sh@@ -25,15 +25,10 @@ for name in $names; dodone# Coverage, security and risk diff the change, so they need its history and-# the target branch; risk also ranks it against recent commits. A shallow-# clone has neither; fetch them rather than exit 2.+# the target branch; risk also ranks it against recent commits.if wants coverage || wants security || wants risk; then- if [[ "$(git rev-parse --is-shallow-repository)" == "true" ]]; then- git fetch --quiet --no-tags --unshallow origin || true- fi- if [[ -n "${GITHUB_BASE_REF:-}" ]] && ! git rev-parse --verify --quiet "refs/remotes/origin/$GITHUB_BASE_REF" >/dev/null; then- git fetch --quiet --no-tags origin "+refs/heads/$GITHUB_BASE_REF:refs/remotes/origin/$GITHUB_BASE_REF" || true- fi+ here=${0//\\//}+ source "${here%/*}/fetch-base.sh"fifailed=0diff --git a/ci/gitlab/repowise.gitlab-ci.yml b/ci/gitlab/repowise.gitlab-ci.ymlindex 1f575ac95..db3e44d99 100644--- a/ci/gitlab/repowise.gitlab-ci.yml+++ b/ci/gitlab/repowise.gitlab-ci.yml@@ -36,6 +36,10 @@# REPOWISE_RISK_FAIL_ABOVE_PERCENTILE# Fail when the change ranks above this percentile of# recent commits. The risk job runs only when it is set.+# REPOWISE_IMPACTED_TESTS "true" adds repowise-impacted-tests, which selects the+# tests the change needs from a cached index.+# REPOWISE_IMPACTED_TESTS_RUNNER Runner its arguments are for: auto (default), pytest,+# go, jest or files..repowise:image: python:3.12@@ -160,3 +164,38 @@ repowise-risk:paths: [repowise-risk.md]rules:- if: $CI_PIPELINE_SOURCE == "merge_request_event" && $REPOWISE_RISK_FAIL_ABOVE_PERCENTILE++# Test selection, opt-in with REPOWISE_IMPACTED_TESTS: "true". It fails+# closed: RUN_ALL_TESTS in the dotenv report is "false" only when the arguments+# in the impacted-tests.txt artifact are safe to run alone; a test job should+# run everything unless it reads "false". It needs a cached Repowise index+# (give the job a cache holding .repowise), which it updates first; when that+# update or the selection fails, the report says run everything and the job+# still passes, so a broken setup costs a full run, never a red pipeline.+repowise-impacted-tests:+ extends: .repowise+ script:+ - |+ status=0+ run_all=true+ echo ":all" > impacted-tests.txt+ if [ -f .repowise/state.json ] && ! repowise update --index-only; then+ echo "The cached index could not be updated; running every test."+ else+ repowise impacted-tests "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME...HEAD" \+ --format args --runner "${REPOWISE_IMPACTED_TESTS_RUNNER:-auto}" > selected.txt || status=$?+ if [ "$status" -ne 0 ]; then+ echo "Test selection could not run (exit $status); running every test."+ elif [ "$(wc -l < selected.txt)" -eq 1 ] && [ "$(cat selected.txt)" != ":all" ]; then+ mv selected.txt impacted-tests.txt+ run_all=false+ fi+ fi+ printf 'RUN_ALL_TESTS=%s\n' "$run_all" > repowise-impacted-tests.env+ artifacts:+ when: always+ paths: [impacted-tests.txt]+ reports:+ dotenv: repowise-impacted-tests.env+ rules:+ - if: $CI_PIPELINE_SOURCE == "merge_request_event" && $REPOWISE_IMPACTED_TESTS == "true"diff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.mdindex beb4ebbe6..082585f49 100644--- a/docs/layers/TEST_INTELLIGENCE.md+++ b/docs/layers/TEST_INTELLIGENCE.md@@ -185,13 +185,15 @@ repowise impacted-tests main...HEAD # a branch or PR, from the merge-repowise impacted-tests main..HEAD # a plain rangerepowise impacted-tests abc123 # a single commitrepowise impacted-tests main..HEAD --format list | xargs pytest+repowise impacted-tests main...HEAD --format args --runner pytest # for CI```| Flag | Values ||------|--------|| `--path` | Repo path (defaults to cwd, or the workspace primary) |-| `--staged` | Diff `git diff --cached`. Implied when no range is given |-| `--format` | `table` (default), `json` (full report), `list` (test ids, one per line) |+| `--staged` | Diff `git diff --cached`. Implied with no range outside CI; in CI the default is the pull request's change |+| `--format` | `table` (default), `json` (full report), `list` (test ids, one per line), `args` (runner arguments, or `:all`) |+| `--runner` | For `--format args`: `auto` (default), `pytest`, `go`, `jest`, `files` |It always says which path fired, and it never lets a guess pass for evidence:@@ -199,15 +201,21 @@ It always says which path fired, and it never lets a guess pass for evidence:|-----------|-------------|| Changed file has per-test coverage on the changed lines | The exact covering tests, `via: coverage` || The changed file is itself a test | Itself, `via: changed-test` |-| Changed file has no coverage rows, but a test reaches it in the graph | Those test files, `via: import-graph`, in the "NOT coverage-backed" table |+| Changed file has no coverage rows, but a test reaches it in the graph | Those test files, `via: call-graph` or `via: import-graph` (direct or transitive), in the "NOT coverage-backed" table || No coverage and no graph edge, but a name-shaped match | That file, `via: filename-pattern`, in the same table || None of the above | "unknown, run the full suite to be safe" || No map ingested at all | A prompt to run `coverage add` on a report with contexts |-Deletion-only files are dropped from the diff (there are no new lines to cover).-With `--format list` the caveats go to stderr so the stdout pipe into `pytest`-stays clean. The command exits `0` in every one of these cases, including "no-tests found": it is a reporting tool, not a gate.+Changed lines are matched at the commit the map was measured at (the change's+base or head); otherwise, and for deleted or removal-only files, matching is by+file and the graph is asked too. With `--format list` the caveats go to stderr+so the pipe into `pytest` stays clean. The command exits `0` in every one of+these cases, including "no tests found": it is a reporting tool, not a gate.++For CI, `--format args` prints the runner arguments, or `:all` whenever any part+of the answer is not known, with the reasons on stderr. The rules, the+`tests.*` config keys and the CI recipes are in+[CI](../start/CI.md#selecting-the-tests-a-change-needs).A `base...head` range diffs from the merge-base of the two, so it is what a pullrequest changed: commits that landed on `base` after the branch forked stay out.@@ -722,7 +730,7 @@ Note that `--coverage-report` is test coverage, while `--coverage` controls| `repowise coverage status` | Coverage summary plus test-to-code map counts. Flag: `--path` || `repowise coverage check [REVSPEC]` | Patch-coverage gate for CI, no index needed. Flags: `--report`, `--report-format`, `--fail-under`, `--min-coverable-lines`, `--fail-under-risky`, `--fail-under-branches`, `--base-report`, `--max-drop`, `--path`, `--format` || `repowise coverage suggest-gates` | Propose path-scoped gates for `coverage.gates` as YAML to paste below `coverage:`; writes nothing. Flags: `--path`, `--format` |-| `repowise impacted-tests [REVSPEC]` | The tests a change exercises. Flags: `--path`, `--staged`, `--format` |+| `repowise impacted-tests [REVSPEC]` | The tests a change exercises, or the runner arguments for CI. Flags: `--path`, `--staged`, `--format`, `--runner` |Full reference: [CLI_REFERENCE.md](../reference/CLI_REFERENCE.md#repowise-coverage).diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 79dfc3b5d..9609ad066 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1054,8 +1054,9 @@ line up.| Flag | Description ||------|-------------|| `--path` | Repo path (defaults to cwd / workspace primary) |-| `--staged` | Diff the staged changes (`git diff --cached`); the default when no range is given |-| `--format` | `table` (default), `json` (full report), or `list` (test ids one per line, for piping) |+| `--staged` | Diff the staged changes (`git diff --cached`); the default with no range outside CI (in CI: the pull request's change) |+| `--format` | `table` (default), `json` (full report plus the selection), `list` (test ids one per line), or `args` (one line of runner arguments, or `:all`; reasons on stderr) |+| `--runner` | For `--format args`: `auto` (default; `files` when mixed), `pytest` (node ids or files), `go` (package dirs), `jest` (files; pass with `--runTestsByPath`), `files` |```bashrepowise impacted-tests # staged changes@@ -1063,8 +1064,18 @@ repowise impacted-tests main...HEAD # a branch / PR (diffed from therepowise impacted-tests main..HEAD # a plain rangerepowise impacted-tests abc123 # a single commitrepowise impacted-tests main..HEAD --format list | xargs pytest+repowise impacted-tests main...HEAD --format args --runner pytest```+`--format args` exits `0` whether it selects a subset or everything, and `2`+when it cannot read the change (unknown revision, missing history) or `tests.*`+in the config. `--format json` adds `indexed_commit`, `map_current` and a+per-file `selected.basis`: `full-run`, `no-tests-needed`, `test-tree`,+`test-package`, `conftest`, `helper-importers`, `deleted-test`, `coverage`,+`changed-test`, `call-graph`, `import-graph`, `filename-pattern`, `unknown`,+or `none` (no index). When it runs everything:+[CI](../start/CI.md#selecting-the-tests-a-change-needs).+---### `repowise health [PATH]`diff --git a/docs/start/CI.md b/docs/start/CI.mdindex ff4c773ac..13b3e8df4 100644--- a/docs/start/CI.md+++ b/docs/start/CI.md@@ -25,6 +25,9 @@ Doc drift's `--check` needs no index. `--kind symbol` adds symbol referencesexits `2` without one. It also reads `git blame`: in a shallow clone every lineblames to the boundary commit, so give that job `fetch-depth: 0`.+Not a gate, but in the same pipeline:+[selecting the tests a change needs](#selecting-the-tests-a-change-needs).+## What every gate does the same way**Exit codes.** `0` passed, or had nothing to judge. `1` the change failed the@@ -132,9 +135,13 @@ release the action installs.| `security-baseline` | none | Committed baseline file. || `risk-fail-above-percentile` | none | With `risk` in `checks`, fail when the change ranks above this percentile of recent commits. Empty reports the rank without gating. || `upload-sarif` | `false` | Upload doc drift and security findings to code scanning. |+| `impacted-tests` | `false` | Select the tests the change needs (needs a cached `.repowise` index); see [below](#selecting-the-tests-a-change-needs). |+| `impacted-tests-runner` | `auto` | `auto`, `pytest`, `go`, `jest` or `files`. |Outputs: `coverage`, `doc-drift`, `security` and `risk` hold each gate's exitcode (empty when not run), and `sarif-dir` the SARIF directory.+`impacted-tests` holds the runner arguments (or `:all`), and `run-all-tests` is+`false` only when that subset is safe to run alone.The risk gate ranks the change against the repository's own recent commits,so at a percentile P roughly (100 - P)% of changes fail it by construction.@@ -236,6 +243,98 @@ repowise security check "origin/$CHANGE_TARGET...HEAD"Bitbucket Pipelines and others work the same way with their own branchvariable; `--format markdown` or `json` gives you something to post.+## Selecting the tests a change needs++`repowise impacted-tests --format args` prints one line of arguments for a test+runner, or `:all` whenever any part of the answer is not known, with the+reasons on stderr. It needs an index (cached from the default branch, below);+a per-test coverage map (`repowise coverage add`) makes it more precise.++- It exits `0` for a subset or for everything, and `2` only when it cannot read the change or the `tests.*` config.+- Branch on the run-all flag, never on `:all`: jest and vitest read it as a pattern and run nothing.+- It runs everything for: an empty change; a lockfile, manifest, build, test or CI config change; `.repowise/config.yaml`; a production package's `__init__.py`.+- It also runs everything for: non-code files in a test tree; a changed file with no known test or only a filename guess; a route through a test helper no test imports; any Python test helper while a conftest or pytest config loads plugins by name.+- It also runs everything for: a missing, out-of-date or unreadable index; a per-test map at its row cap; a deleted file no known test used.+- Only `docs/` and root README-like files (README, CHANGELOG, LICENSE, CONTRIBUTING) are skipped, and only when no code names them (a test that reads `README.md` names it); an empty line means only those changed.+- Tests the graph cannot see into (not indexed, or importing nothing it resolves, such as a test that only runs a subprocess) run with every subset. With `--runner pytest`, test-named modules outside `testpaths` and outside test directories are left out, as a bare `pytest` leaves them out.+- A changed `conftest.py`, test package `__init__.py` or imported test helper selects the tests under or importing it, not everything.+- Without a range, in CI it reads the pull request's change; locally, the staged changes.+- `tests.full_run_on` (gitignore patterns) adds run-everything paths; `tests.always_run` is appended to every selection as written.+- Ceiling: on the JVM and .NET, a same-package test linked only by an unresolved call is missed. A test that reaches the change only through a subprocess, a plugin or registry loaded by a string name, or a directory it globs, while importing something else, is missed too: list such tests in `tests.always_run`, and run the full suite on the default branch.++**What to expect.** The subset is only as small as the code is loosely coupled.+On tightly coupled code the graph alone picks most tests (over 80% of test+files on this repository), because most tests import something that imports+the changed file. Real savings need a per-test map measured at the change's+base. `--format json` shows what drove each file's selection in+`selected.basis`.++On GitHub Actions, keep the index cached from the default branch and branch+on the outputs in the pull request job:++```yaml+# .github/workflows/repowise-index.yml+on: {push: {branches: [main]}}+jobs:+ index:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ with: {fetch-depth: 0}+ - uses: actions/cache/restore@v4+ with: {path: .repowise, key: "repowise-${{ github.sha }}", restore-keys: "repowise-"}+ - run: pip install repowise+ - run: if [ -f .repowise/state.json ]; then repowise update --index-only; else repowise init --yes --index-only; fi+ - uses: actions/cache/save@v4+ with: {path: .repowise, key: "repowise-${{ github.sha }}"}+```++```yaml+# in the pull request workflow+- uses: actions/checkout@v4+ with: {fetch-depth: 0}+- uses: actions/cache/restore@v4+ with: {path: .repowise, key: "repowise-${{ github.event.pull_request.base.sha }}", restore-keys: "repowise-"}+- id: select+ uses: repowise-dev/repowise@main+ with: {checks: "", impacted-tests: true, impacted-tests-runner: pytest}+- if: steps.select.outputs.run-all-tests != 'false'+ run: pytest+- if: steps.select.outputs.run-all-tests == 'false' && steps.select.outputs.impacted-tests != ''+ env: {TESTS: "${{ steps.select.outputs.impacted-tests }}"}+ run: eval "pytest $TESTS"+```++A skipped or failed step leaves `run-all-tests` empty, so `!= 'false'` runs+everything.++On GitLab, set `REPOWISE_IMPACTED_TESTS: "true"` (and optionally+`REPOWISE_IMPACTED_TESTS_RUNNER`). The `repowise-impacted-tests` job writes the+arguments to `impacted-tests.txt` and `RUN_ALL_TESTS` to a dotenv report:++```yaml+repowise-index:+ image: python:3.12+ variables: {GIT_DEPTH: "0"}+ script:+ - pip install repowise+ - if [ -f .repowise/state.json ]; then repowise update --index-only; else repowise init --yes --index-only; fi+ cache: {key: repowise-index, paths: [.repowise/], policy: pull-push}+ rules:+ - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH++repowise-impacted-tests:+ cache: {key: repowise-index, paths: [.repowise/], policy: pull}++test:+ needs: [{job: repowise-impacted-tests, optional: true}]+ script:+ - |+ if [ "${RUN_ALL_TESTS:-}" != "false" ]; then pytest+ elif [ -n "$(cat impacted-tests.txt 2>/dev/null)" ]; then eval "pytest $(cat impacted-tests.txt)"+ fi+```+## Coverage reports per languageThe coverage gate needs the lines each file could have run, not only the linesdiff --git a/packages/cli/src/repowise/cli/ci.py b/packages/cli/src/repowise/cli/ci.pyindex ef625c004..5e32c651c 100644--- a/packages/cli/src/repowise/cli/ci.py+++ b/packages/cli/src/repowise/cli/ci.py@@ -9,8 +9,9 @@ the workflow-command strings come from :mod:`repowise.core.ci.github`.from __future__ import annotations+import contextlibimport os-from collections.abc import Mapping+from collections.abc import Iterator, Mappingfrom pathlib import Pathfrom typing import Any, NoReturn@@ -100,17 +101,32 @@ def change_lines(With *staged*, the staged diff (what ``git commit`` would record) instead."""- import subprocess-from repowise.core.analysis.changed_lines import changed_linesrevspec = None if staged else ci_revspec(root, revspec)- try:+ with _reading_change(revspec or "the staged changes", shallow_hint=not staged):return changed_lines(root, revspec, staged=staged)+++def change_set(root: str, revspec: str | None, *, staged: bool = False) -> Any:+ """Every path *revspec* touches, else the staged changes (a ``ChangeSet``)."""+ from repowise.core.analysis.changed_lines import change_set as read_change_set++ with _reading_change(revspec or "the staged changes", shallow_hint=not staged):+ return read_change_set(root, revspec, staged=staged)+++def _reading_change(what: str, *, shallow_hint: bool = True) -> Iterator[None]:+ """Turn a failed diff of *what* into :class:`CannotEvaluateError`."""+ import subprocess++ try:+ yieldexcept ValueError as exc:- hint = "" if staged else f" {SHALLOW_CLONE_HINT}"+ hint = f" {SHALLOW_CLONE_HINT}" if shallow_hint else ""raise CannotEvaluateError(- "diff_failed", f"Could not diff {revspec or 'the staged changes'}: {exc}.{hint}"+ "diff_failed", f"Could not diff {what}: {exc}.{hint}") from excexcept (subprocess.SubprocessError, OSError) as exc:raise CannotEvaluateError("git_failed", f"Could not run git: {exc}") from excdiff --git a/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py b/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.pyindex 65945cfbe..7d6362fd5 100644--- a/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py+++ b/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py@@ -2,8 +2,8 @@Given a diff (a ``base..head`` range, a commit, or the staged changes), mapeach changed source line to the tests whose recorded coverage touches it, using-the per-test test-to-code map built by ``repowise coverage add``. The output is-"run these N tests, not all N-thousand" - a CI story that needs no agent.+the per-test test-to-code map built by ``repowise coverage add``, and to the+tests the dependency graph shows reaching each changed file.Honest about what it knows:- a changed file with per-test coverage -> the exact covering tests;@@ -13,34 +13,60 @@ Honest about what it knows:- a new file with neither -> "unknown, run the full suite" (never impliedas "no tests needed").+With ``--format args`` it becomes a CI primitive: one line of arguments for a+test runner, or ``:all`` when anything about the change is uncertain (the rules+live in :mod:`repowise.core.analysis.test_selection`), with the reasons on+stderr. Selection is not a gate: it exits 0 either way, and 2 only when it+cannot read the change or the config.+Examples:- repowise impacted-tests # staged changes+ repowise impacted-tests # staged changes (in CI: the PR's change)repowise impacted-tests main..HEAD # a branch / PR rangerepowise impacted-tests abc123 # a single commitrepowise impacted-tests main..HEAD --format list | xargs pytest+ repowise impacted-tests main...HEAD --format args --runner pytest"""from __future__ import annotations-import json+import sys+from pathlib import Pathimport clickfrom rich.table import Table+from repowise.cli.ci import (+ CannotEvaluateError,+ cannot_evaluate,+ change_set,+ ci_notices,+ ci_revspec,+ repo_root,+)from repowise.cli.helpers import (console,err_console,- get_db_url_for_repo,+ repo_index_session,resolve_command_target,run_async,silence_logs_for_machine_output,)+from repowise.cli.output import emit_json+from repowise.core.analysis.test_selection import RUNNERS++# The whole reverse-import closure: a test importing a module that imports the+# changed file runs it too. No depth limit: the walk ends when no node gains a+# new seed, so a cut-off can never drop a test.+_IMPORT_CLOSURE_DEPTH = sys.maxsize+# Candidates the table prints per changed file; json and list carry them all.+_TABLE_CANDIDATES = 10-def _resolve_repo_path(path: str | None):++def _resolve_repo_path(path: str | None, fmt: str):"""Resolve the repo path (workspace-aware), mirroring ``coverage``."""target = resolve_command_target(path=path)- target.notice(console, command="impacted-tests")+ target.notice(ci_notices(fmt), command="impacted-tests")if target.is_workspace:primary = target.primary_path()if primary is None:@@ -58,79 +84,173 @@ def _resolve_repo_path(path: str | None):@click.option("--staged",is_flag=True,- help="Diff the staged changes (git diff --cached). The default when no range is given.",+ help="Diff the staged changes (git diff --cached). The default when no range is given, "+ "outside CI; in CI the default is the pull request's change.",)@click.option("--format","fmt",default="table",- type=click.Choice(["table", "json", "list"]),- help="table (human), json (full report), or list (test ids, one per line, for piping).",+ type=click.Choice(["table", "json", "list", "args"]),+ help="table (human), json (full report and selection), list (test ids, one per line), "+ "or args (one line of runner arguments, or :all for a full run; reasons on stderr).",+)+ "--runner",+ default="auto",+ type=click.Choice(list(RUNNERS)),+ help="Who --format args is for: pytest (node ids and files), go (package dirs), "+ "jest (files), files, or auto (from the selected test files; mixed means files).",)-def impacted_tests_command(revspec: str | None, repo: str | None, staged: bool, fmt: str) -> None:+def impacted_tests_command(+ revspec: str | None, repo: str | None, staged: bool, fmt: str, runner: str+) -> None:"""Print the tests whose coverage intersects a change's changed lines."""if revspec and staged:raise click.ClickException("Give a revision range or --staged, not both.")- # json/list go to downstream tools; keep stdout clean of log noise.+ # json/list/args go to downstream tools; keep stdout clean of log noise.if fmt != "table":silence_logs_for_machine_output()- repo_path = _resolve_repo_path(repo)+ repo_path = _resolve_repo_path(repo, fmt)+ try:+ change, config = _read_change(repo_path, revspec, staged, fmt)+ except CannotEvaluateError as exc:+ cannot_evaluate(fmt, exc.code, str(exc))- from repowise.core.analysis.changed_lines import changed_lines+ result = run_async(_collect(repo_path, change))+ result["diff"] = change.label+ if config is not None:+ result["selection"] = _select(repo_path, change, result, config)+ _render(result, fmt, runner)- try:- changed, label = changed_lines(str(repo_path), revspec, staged=staged)- except ValueError as exc:- raise click.ClickException(str(exc)) from exc- result = run_async(_collect(repo_path, changed))- result["diff"] = label- _render(result, fmt)+def _read_change(repo_path, revspec: str | None, staged: bool, fmt: str):+ """``(change set, selection config or None)``, or :class:`CannotEvaluateError`."""+ from repowise.core.ci.base import in_ci+ config = _selection_config(repo_path) if fmt in ("json", "args") else None+ if revspec is None and not staged and in_ci():+ # In CI the change to test is the pull request's, not the staged index.+ revspec = ci_revspec(str(repo_root(str(repo_path))), None)+ return change_set(str(repo_path), revspec, staged=staged), config-async def _collect(repo_path, changed: dict[str, set[int]]) -> dict:- """Resolve changed files to impacted tests + labelled fallbacks."""- from repowise.core.persistence import (- create_engine,- create_session_factory,- get_session,- )++def _selection_config(repo_path):+ from repowise.core.analysis.test_selection import TestSelectionConfig+ from repowise.core.repo_config import RepoConfigError, load_repo_config++ try:+ return TestSelectionConfig.from_repo_config(load_repo_config(repo_path))+ except (RepoConfigError, ValueError) as exc:+ raise CannotEvaluateError("config_invalid", str(exc)) from exc+++async def _collect(repo_path, change) -> dict:+ """Resolve the change's files to impacted tests + labelled fallbacks."""from repowise.core.persistence.crud import (get_health_metrics,- get_repository_by_path,+ get_repository,get_test_coverage_summary,)+ from repowise.core.persistence.crud.analysis.coverage_map import MAX_TEST_COVERAGE_ROWS- out = _empty_result(len(changed))- if not changed:+ out = _empty_result(len(change.files) + len(change.deleted))+ if not out["changed_files"]:return out- engine = create_engine(get_db_url_for_repo(repo_path))- sf = create_session_factory(engine)- async with get_session(sf) as session:- repo_row = await get_repository_by_path(session, str(repo_path))- if repo_row is None:+ async with repo_index_session(Path(repo_path)) as opened:+ if opened is None:out["no_index"] = Truereturn out- repo_id = repo_row.id+ session, repo_id = opened+ repo_row = await get_repository(session, repo_id)+ _indexed_commit(repo_path, repo_row.head_commit if repo_row else None, out)summary = await get_test_coverage_summary(session, repo_id)out["map_empty"] = summary.get("pair_count", 0) == 0+ out["map_truncated"] = summary.get("pair_count", 0) >= MAX_TEST_COVERAGE_ROWS+ measured = summary.get("ingested_commit_sha")+ out["map_current"] = out["map_empty"] or measured in {change.base, change.head} - {None}# Repo file keys back the filename-pattern fallback (same source the# aggregate coverage ingest resolves against).repo_keys = {m.file_path for m in await get_health_metrics(session, repo_id)}- await _resolve_impacted(session, repo_id, changed, repo_keys, out)+ await _resolve_impacted(session, repo_id, _query_lines(change, measured), repo_keys, out)+ await _place_tests(session, repo_id, out)return out+async def _place_tests(session, repo_id: str, out: dict) -> None:+ """Record the tests the graph can see into, which selection needs to find the rest."""+ from repowise.core.analysis.test_reachability import placed_test_files++ if out["graph_error"] is not None:+ return+ try:+ out["placed_tests"] = await placed_test_files(session, repo_id)+ except Exception as exc:+ out["graph_error"] = f"{type(exc).__name__}: {exc}"+++def _indexed_commit(repo_path, row_commit: str | None, out: dict) -> None:+ """The commit the index describes: ``state.json`` first, then the repository row.++ The same order the server's freshness check reads. When both are recorded+ and disagree, the index's own history is in doubt, so the commit is unknown.+ """+ from repowise.core.workspace.update import read_state_commit++ state = read_state_commit(Path(repo_path))+ if state and row_commit and state != row_commit:+ out["index_problem"] = (+ f"The index records two commits ({state[:7]} in state.json, {row_commit[:7]} "+ "in its database), so what it describes is unknown; run `repowise update`."+ )+ return+ out["indexed_commit"] = state or row_commit+++def _query_lines(change, measured: str | None) -> dict[str, set[int] | None]:+ """The lines to look up per file, on the side of the diff the map was measured at.++ Coverage measured at the change's base is keyed in the old file's line+ numbers, at its head in the new file's. Measured anywhere else, or for a+ deleted or hunkless file, only the file can be matched (``None``).+ """+ side = None+ if measured and measured == change.head:+ side = "new"+ elif measured and measured == change.base:+ side = "old"+ lines: dict[str, set[int] | None] = dict.fromkeys(change.deleted)+ for path, diff in change.files.items():+ lines[path] = _touched_lines(diff.hunks, side) if side and diff.hunks else None+ return lines+++def _touched_lines(hunks, side: str) -> set[int]:+ """Lines the hunks touch on *side*; for a pure insertion or deletion, its two neighbours."""+ lines: set[int] = set()+ for old_start, old_count, new_start, new_count in hunks:+ start, count = (old_start, old_count) if side == "old" else (new_start, new_count)+ lines.update(range(start, start + count) if count else {start, start + 1} - {0})+ return lines++def _empty_result(changed_files: int) -> dict:return {"no_index": False,"map_empty": False,+ "map_current": True,+ "map_truncated": False,+ "indexed_commit": None,+ "index_problem": None,+ "graph_error": None,+ "placed_tests": None,+ "helper_importers": {},"changed_files": changed_files,"covered": {}, # test_id -> {test_file, source_files: [...]}"inferred": [], # {source_file, test_file, via}@@ -141,7 +261,7 @@ def _empty_result(changed_files: int) -> dict:async def _resolve_impacted(session,repo_id: str,- changed: dict[str, set[int]],+ changed: dict[str, set[int] | None],repo_keys: set[str],out: dict,) -> dict:@@ -149,7 +269,10 @@ async def _resolve_impacted(Mutates and returns *out*. Split from ``_collect`` (which owns the DBbootstrap) so the diff -> lines -> tests path is testable against a seeded- ``test_coverage`` table.+ ``test_coverage`` table. A file mapped to ``None`` is matched by file, not+ by line (a deleted file, or a map measured at another commit). Every file+ also asks the graph: coverage records what one run executed, so it adds to+ the graph's answer and never replaces it.Three tiers, and the output says which one answered for every file, becausethey are not interchangeable:@@ -158,34 +281,28 @@ async def _resolve_impacted(Recorded per-test coverage intersecting the changed *lines*. The onlytier that knows about lines, and the only one that proves execution.``inferred``- No coverage row, so fall back to naming candidates. A changed file that- is itself a test is its own candidate (``via="changed-test"``) - it used- to be reported as a file with no test, which is true and useless. Then- the dependency graph, which reports which tier answered: a test whose- calls reach the file (``via="call-graph"``) or, only where no call edge- does, a test that imports it (``via="import-graph"``). Both are recorded- edges, and they find suites whose tests are named for behaviour rather- than for the file. The filename pattern answers when the graph is silent- (``via="filename-pattern"``). All are file-level and all over-claim;- none may be read as coverage.+ What the graph names, beside any coverage. A changed test is its own+ candidate (``via="changed-test"``). Then the dependency graph, which+ reports which tier answered: tests whose calls reach the file+ (``via="call-graph"``), and every test that imports it, directly or+ through other modules or other tests (``via="import-graph"``). Both are+ recorded edges, and they find suites whose tests are named for+ behaviour rather than for the file. The filename pattern answers only+ when the graph is silent (``via="filename-pattern"``). All are+ file-level and all over-claim; none may be read as coverage.``unknown``Nothing said anything. Run the full suite."""from repowise.core.analysis.health.coverage import paired_test_file- from repowise.core.analysis.test_reachability import (- load_test_files,- tests_reaching_by_tier,- )from repowise.core.persistence.crud import tests_coveringcovered: dict[str, dict] = out["covered"]- uncovered: list[str] = []+ has_rows: set[str] = set()+ graph_targets = sorted(changed)for source_file, lines in sorted(changed.items()):rows = await tests_covering(session, repo_id, source_file, lines=lines)- if not rows:- uncovered.append(source_file)- continuefor r in rows:+ has_rows.add(source_file)entry = covered.setdefault(r["test_id"],{"test_file": r["test_file"], "source_files": []},@@ -193,35 +310,25 @@ async def _resolve_impacted(if source_file not in entry["source_files"]:entry["source_files"].append(source_file)- if not uncovered:+ if not graph_targets:return out- # One walk for every uncovered file rather than one per file: the seed set- # is what makes this cheap, and splitting it would run the same query once- # per changed path.try:- reaching = await tests_reaching_by_tier(session, repo_id, uncovered)- test_files = await load_test_files(session, repo_id)- except Exception:- reaching, test_files = {}, set()-- for source_file in uncovered:- if source_file in test_files:- out["inferred"].append(- {- "source_file": source_file,- "test_file": source_file,- "via": "changed-test",- }- )- continue- reached = reaching.get(source_file)- if reached:+ candidates, importers = await _graph_candidates(session, repo_id, graph_targets)+ except Exception as exc:+ # Nothing the graph said can be trusted; selection runs everything.+ out["graph_error"] = f"{type(exc).__name__}: {exc}"+ candidates, importers = {}, {}+ out["helper_importers"] = importers+ for source_file in graph_targets:+ found = candidates.get(source_file)+ if found:out["inferred"].extend(- {"source_file": source_file, "test_file": t, "via": reached.via}- for t in reached.tests+ {"source_file": source_file, "test_file": t, "via": via} for t, via in found)continue+ if source_file in has_rows:+ continue # coverage answered; a name-shaped guess adds nothingguess = paired_test_file(source_file, repo_keys)if guess:out["inferred"].append(@@ -236,6 +343,166 @@ async def _resolve_impacted(return out+async def _graph_candidates(+ session, repo_id: str, targets: list[str]+) -> tuple[dict[str, list], dict[str, list[str]]]:+ """``{target: [(test file, via), ...]}`` from the graph, and each test file's importers.++ Candidates come strongest tier first. The importers map says, for every+ test file the walk met, which test files import it.++ One walk per tier for every target rather than one per file: the seed set+ is what makes it cheap. Uncapped, since a trimmed list would drop tests a+ change needs. The import walk treats a test file as a leaf, so the tests+ importing a candidate (a shared base class, a helper module under+ ``tests/``) are added until nothing new appears. Only code counts as a test+ node: a JSON or golden file the index flags as test material is data, not a+ route. A read failure raises.+ """+ from repowise.core.analysis.test_reachability import load_test_files+ from repowise.core.analysis.test_selection import is_code_file++ test_files = {f for f in await load_test_files(session, repo_id) if is_code_file(f)}+ found = await _tier_picks(session, repo_id, targets, test_files)+ seeds = {t for picks in found.values() for t in picks}+ parents = await _test_importers(session, repo_id, seeds, test_files)+ out = {target: _with_importers(picks, parents) for target, picks in found.items()}+ return out, {test: sorted(found_by) for test, found_by in parents.items()}+++def _all_tests(reached) -> tuple[str, ...]:+ """Every test a walk found, not the capped list it reports."""+ return reached.all_tests or tuple(reached.tests)+++async def _tier_picks(+ session, repo_id: str, targets: list[str], test_files: set[str]+) -> dict[str, dict[str, str]]:+ """``{target: {test file: via}}``: a changed test itself, then the call and import walks."""+ from repowise.core.analysis.test_reachability import tests_reaching_by_tier+ from repowise.core.test_paths import is_test_path++ reaching = await tests_reaching_by_tier(session, repo_id, targets, test_files=test_files)+ importers = await tests_reaching_by_tier(+ session,+ repo_id,+ targets,+ call_depth=0,+ import_depth=_IMPORT_CLOSURE_DEPTH,+ test_files=test_files,+ )+ found: dict[str, dict[str, str]] = {}+ for target in targets:+ picks = found.setdefault(target, {})+ if target in test_files or is_test_path(target):+ picks[target] = "changed-test"+ for reached, via in ((reaching.get(target), None), (importers.get(target), "import-graph")):+ for t in _all_tests(reached) if reached else ():+ picks.setdefault(t, via or reached.via)+ return found+++async def _test_importers(+ session, repo_id: str, seeds: set[str], test_files: set[str]+) -> dict[str, set[str]]:+ """``{test file: test files importing it}``, walked until nothing new appears."""+ from repowise.core.analysis.test_reachability import tests_reaching_by_tier++ parents: dict[str, set[str]] = {}+ frontier, seen = set(seeds), set(seeds)+ while frontier:+ walked = await tests_reaching_by_tier(+ session,+ repo_id,+ sorted(frontier),+ call_depth=0,+ import_depth=_IMPORT_CLOSURE_DEPTH,+ test_files=test_files,+ )+ frontier = set()+ for test, reached in walked.items():+ parents.setdefault(test, set()).update(_all_tests(reached))+ frontier.update(set(_all_tests(reached)) - seen)+ seen |= frontier+ return parents+++def _with_importers(picks: dict[str, str], parents: dict[str, set[str]]) -> list:+ """*picks* plus every test importing one of them, transitively, as ``import-graph``."""+ stack = list(picks)+ while stack:+ fresh = [p for p in sorted(parents.get(stack.pop(), ())) if p not in picks]+ picks.update(dict.fromkeys(fresh, "import-graph"))+ stack.extend(fresh)+ return list(picks.items())+++def _select(repo_path, change, result: dict, config):+ """The run-all-or-subset decision for ``--format args`` / ``json``."""+ from repowise.core import git_refs+ from repowise.core.analysis.changed_lines import index_gap+ from repowise.core.analysis.test_selection import (+ SelectionInput,+ doc_readers,+ is_documentation,+ is_runnable_test,+ is_scan_source,+ plugin_loader,+ pytest_testpaths,+ select_tests,+ )++ named = {g["test_file"] for g in result["inferred"]}+ named |= {i["test_file"] for i in result["covered"].values() if i["test_file"]}+ root = Path(repo_path)+ tracked = git_refs.tracked_paths(str(root))+ go_test_dirs = {str(Path(p).parent.as_posix()) for p in tracked if p.endswith("_test.go")}+ known_tests = sorted(p for p in tracked if is_runnable_test(p))+ placed = result["placed_tests"]+ docs = [p for p in (*change.files, *change.deleted) if is_documentation(p)]+ sources = [p for p in tracked if is_scan_source(p)]+ return select_tests(+ SelectionInput(+ changed=change.files,+ deleted=change.deleted,+ tiers=result,+ config=config,+ index_available=not result["no_index"],+ label=change.label,+ map_current=result["map_current"],+ map_truncated=result["map_truncated"],+ index_gap=index_gap(str(root), result["indexed_commit"], change),+ index_problem=result["index_problem"],+ graph_error=result["graph_error"],+ missing={f for f in named if not (root / f).is_file()},+ go_test_dirs=go_test_dirs,+ known_tests=known_tests,+ doc_readers=doc_readers(docs, _texts(root, sources)) if docs else {},+ plugin_loader=plugin_loader(_texts(root, sources, pytest_only=True)),+ unplaced_tests=[] if placed is None else [t for t in known_tests if t not in placed],+ pytest_testpaths=pytest_testpaths(lambda name: _text(root / name)),+ )+ )+++def _text(path: Path) -> str | None:+ try:+ return path.read_text(encoding="utf-8", errors="ignore")+ except OSError:+ return None+++def _texts(root: Path, paths: list[str], *, pytest_only: bool = False):+ """``(path, text)`` for each readable file; with *pytest_only*, conftests and configs."""+ from repowise.core.analysis.test_selection import is_code_file++ for path in paths:+ if pytest_only and is_code_file(path) and not path.endswith("conftest.py"):+ continue+ if (text := _text(root / path)) is not None:+ yield path, text++def _machine_test_ids(result: dict) -> list[str]:"""Test ids for --format list: covered node ids + inferred test files."""ids = list(result["covered"].keys())@@ -245,30 +512,9 @@ def _machine_test_ids(result: dict) -> list[str]:return [i for i in ids if not (i in seen or seen.add(i))]-def _render(result: dict, fmt: str) -> None:- if fmt == "json":- click.echo(- json.dumps(- {- "diff": result["diff"],- "changed_files": result["changed_files"],- "no_index": result["no_index"],- "map_empty": result["map_empty"],- "impacted_tests": [- {- "test_id": tid,- "test_file": info["test_file"],- "source_files": info["source_files"],- "via": "coverage",- }- for tid, info in result["covered"].items()- ],- "inferred_tests": result["inferred"],- "unknown_files": result["unknown"],- },- indent=2,- )- )+def _render(result: dict, fmt: str, runner: str = "auto") -> None:+ if fmt in ("json", "args"):+ _render_selection(result, fmt, runner)returnif fmt == "list":@@ -290,6 +536,54 @@ def _render(result: dict, fmt: str) -> None:_render_table(result)+def _render_selection(result: dict, fmt: str, runner: str) -> None:+ """``--format args`` (one line, reasons on stderr) or ``--format json``."""+ from repowise.core.analysis.test_selection import format_args, resolve_runner, runner_args++ selection = result["selection"]+ resolved = resolve_runner(selection, runner)+ args = runner_args(selection, resolved)+ if fmt == "args":+ click.echo(format_args(args))+ # Plain stderr, one reason per line: a CI log must not wrap or style them.+ if selection.run_all:+ click.echo("Run every test:", err=True)+ else:+ click.echo(f"{len(args)} argument(s) for {resolved}.", err=True)+ for reason in selection.reasons:+ click.echo(f" {reason}", err=True)+ return++ selected = selection.to_dict()+ run_all, reasons = selected.pop("run_all"), selected.pop("reasons")+ emit_json(+ {+ "diff": result["diff"],+ "changed_files": result["changed_files"],+ "no_index": result["no_index"],+ "map_empty": result["map_empty"],+ "impacted_tests": [+ {+ "test_id": tid,+ "test_file": info["test_file"],+ "source_files": info["source_files"],+ "via": "coverage",+ }+ for tid, info in result["covered"].items()+ ],+ "inferred_tests": result["inferred"],+ "unknown_files": result["unknown"],+ "indexed_commit": result["indexed_commit"],+ "map_current": result["map_current"],+ "run_all": run_all,+ "reasons": reasons,+ "selected": selected,+ "runner": resolved,+ "args": args,+ }+ )++def _render_table(result: dict) -> None:if result["no_index"]:console.print("[yellow]No index yet - run `repowise init` first.[/yellow]")@@ -301,6 +595,13 @@ def _render_table(result: dict) -> None:console.print("[dim]No changed source lines in this diff.[/dim]")return+ _print_map_state(result)+ _print_covered(result)+ _print_inferred(result["inferred"])+ _print_unknown(result["unknown"])+++def _print_map_state(result: dict) -> None:if result["map_empty"]:console.print("[yellow]No test-to-code map ingested.[/yellow] Run "@@ -308,44 +609,64 @@ def _render_table(result: dict) -> None:"[cyan]coverage run --contexts=test[/cyan] to get exact impacted tests. ""Falling back to the dependency graph and filename patterns below.")-- covered = result["covered"]- if covered:- table = Table(title="Tests covering the changed lines")- table.add_column("Test", style="green")- table.add_column("Changed file(s) it covers")- for tid, info in sorted(covered.items()):- table.add_row(tid, "\n".join(info["source_files"]))- console.print(table)+ elif not result["map_current"]:console.print(- f"[green]{len(covered)} test(s)[/green] directly cover the change "- "(via recorded per-test coverage)."- )- elif not result["map_empty"]:- console.print("[dim]No recorded test covers the changed lines directly.[/dim]")-- if result["inferred"]:- gtable = Table(title="Inferred tests (NOT coverage-backed)")- gtable.add_column("Changed file")- gtable.add_column("Candidate test", style="yellow")- gtable.add_column("From", style="dim")- for g in result["inferred"]:- gtable.add_row(g["source_file"], g["test_file"], g["via"])- console.print(gtable)- files = len({g["source_file"] for g in result["inferred"]})- console.print(- f"[yellow]{len(result['inferred'])} candidate(s)[/yellow] for {files} file(s) with "- "no coverage. [dim]changed-test[/dim] = the changed file is itself a test; "- "[dim]call-graph[/dim] = a test whose calls reach this file; "- "[dim]import-graph[/dim] = a test that only imports it; "- "[dim]filename-pattern[/dim] = a name-shaped guess. None proves execution - "- "verify they exercise the change."+ "[yellow]The test-to-code map was measured at another commit[/yellow], so "+ "covering tests are matched by file, not by changed line.")- if result["unknown"]:- console.print(- f"[red]{len(result['unknown'])} changed file(s)[/red] have no coverage, no test "- "reaching them in the graph and no paired test - run the full suite to be safe:"- )- for path in result["unknown"]:- console.print(f" [red]{path}[/red]")++def _print_covered(result: dict) -> None:+ covered = result["covered"]+ if not covered:+ if not result["map_empty"]:+ console.print("[dim]No recorded test covers the changed lines directly.[/dim]")+ return+ table = Table(title="Tests covering the changed lines")+ table.add_column("Test", style="green")+ table.add_column("Changed file(s) it covers")+ for tid, info in sorted(covered.items()):+ table.add_row(tid, "\n".join(info["source_files"]))+ console.print(table)+ console.print(+ f"[green]{len(covered)} test(s)[/green] directly cover the change "+ "(via recorded per-test coverage)."+ )+++def _print_inferred(inferred: list[dict]) -> None:+ if not inferred:+ return+ table = Table(title="Inferred tests (NOT coverage-backed)")+ table.add_column("Changed file")+ table.add_column("Candidate test", style="yellow")+ table.add_column("From", style="dim")+ per_file: dict[str, list[dict]] = {}+ for g in inferred:+ per_file.setdefault(g["source_file"], []).append(g)+ for rows in per_file.values():+ for g in rows[:_TABLE_CANDIDATES]:+ table.add_row(g["source_file"], g["test_file"], g["via"])+ for source, rows in per_file.items():+ if len(rows) > _TABLE_CANDIDATES:+ table.add_row(source, f"... and {len(rows) - _TABLE_CANDIDATES} more", "")+ console.print(table)+ console.print(+ f"[yellow]{len(inferred)} candidate(s)[/yellow] for {len(per_file)} file(s) "+ "with no coverage. [dim]changed-test[/dim] = the changed file is itself a test; "+ "[dim]call-graph[/dim] = a test whose calls reach this file; "+ "[dim]import-graph[/dim] = a test that imports it, directly or not; "+ "[dim]filename-pattern[/dim] = a name-shaped guess. None proves execution - "+ "verify they exercise the change."+ )+++def _print_unknown(unknown: list[str]) -> None:+ if not unknown:+ return+ console.print(+ f"[red]{len(unknown)} changed file(s)[/red] have no coverage, no test "+ "reaching them in the graph and no paired test - run the full suite to be safe:"+ )+ for path in unknown:+ console.print(f" [red]{path}[/red]")diff --git a/packages/cli/src/repowise/cli/platform/telemetry/environment.py b/packages/cli/src/repowise/cli/platform/telemetry/environment.pyindex 05f6cd508..02124742e 100644--- a/packages/cli/src/repowise/cli/platform/telemetry/environment.py+++ b/packages/cli/src/repowise/cli/platform/telemetry/environment.py@@ -11,17 +11,7 @@ from __future__ import annotationsimport osimport platform-# Common CI signals across providers. ``CI`` covers GitHub Actions, GitLab,-# CircleCI, Travis; the rest catch platforms that don't set a generic ``CI``.-_CI_ENV_VARS = (- "CI",- "GITHUB_ACTIONS",- "GITLAB_CI",- "BUILDKITE",- "JENKINS_URL",- "TEAMCITY_VERSION",- "TF_BUILD",-)+from repowise.core.ci.base import CI_ENV_VARS as _CI_ENV_VARSdef os_family() -> str:diff --git a/packages/core/src/repowise/core/analysis/changed_lines.py b/packages/core/src/repowise/core/analysis/changed_lines.pyindex 76ae99352..bc599182c 100644--- a/packages/core/src/repowise/core/analysis/changed_lines.py+++ b/packages/core/src/repowise/core/analysis/changed_lines.py@@ -246,9 +246,17 @@ def changed_lines(if working_tree:return _working_tree_lines(repo_path, base)+ command, revisions, label = _change_command(repo_path, revspec, staged=staged)+ diff = _diff(repo_path, [*command, "--unified=0", *DIFF_ARGS, *revisions])+ return _parse_unified_diff(diff), label+++def _change_command(+ repo_path: str, revspec: str | None, *, staged: bool+) -> tuple[list[str], list[str], str]:+ """``(git command, revisions, label)`` that diff a change, its refs verified."""if staged or not revspec:- diff = _git(["diff", "--cached", "--unified=0", *DIFF_ARGS], repo_path)- return _parse_unified_diff(diff), "staged changes"+ return ["diff", "--cached"], [], "staged changes"if (parts := split_revspec(revspec)) is not None:# ``base...head`` is what a pull request changed: git diffs from the@@ -257,8 +265,7 @@ def changed_lines(_verify_ref(repo_path, base)_verify_ref(repo_path, head)label = f"{base}{sep}{head}"- diff = _diff(repo_path, ["diff", "--unified=0", *DIFF_ARGS, label])- return _parse_unified_diff(diff), label+ return ["diff"], [label], label_verify_ref(repo_path, revspec)if is_shallow_root(repo_path, revspec):@@ -268,8 +275,69 @@ def changed_lines(# --format= drops the commit message so only the diff body is parsed.# -m --first-parent matches what change risk counts on a merge; without it# git's combined diff emits nothing at all and a merged PR reads as empty.- args = ["show", "--unified=0", *DIFF_ARGS, "--format=", "-m", "--first-parent", revspec]- return _parse_unified_diff(_diff(repo_path, args)), revspec+ return ["show", "--format=", "-m", "--first-parent"], [revspec], revspec+++@dataclass+class ChangeSet:+ """Every path a change touched, for a reader that must not miss one.++ *files* holds each path present after the change, including those+ :func:`changed_lines` drops (a removal-only edit, a binary or mode-only+ change, which have no new-side lines); *deleted* the paths it removed. A+ rename reads as a deletion plus an addition. *base* and *head* are the+ commits either side; *head* is ``None`` for staged changes, and either is+ ``None`` when git cannot name it.+ """++ files: dict[str, FileDiff]+ deleted: set[str]+ label: str+ base: str | None+ head: str | None+++def change_set(repo_path: str, revspec: str | None = None, *, staged: bool = False) -> ChangeSet:+ """The change :func:`changed_lines` reads, with every touched path and its ends.++ Raises ``ValueError`` on an unknown revision, as :func:`changed_lines` does.+ """+ command, revisions, label = _change_command(repo_path, revspec, staged=staged)+ tail = ["--no-renames", *revisions]+ diffs = parse_unified_diff(_diff(repo_path, [*command, "--unified=0", *DIFF_ARGS, *tail]))+ listing = _diff(repo_path, [*command, "--name-status", "-z", *tail])+ fields = [f.strip("\n") for f in listing.split("\0")]+ files: dict[str, FileDiff] = {}+ deleted: set[str] = set()+ for status, path in zip(fields[0::2], fields[1::2], strict=False):+ if not path:+ continue+ if status.startswith("D"):+ deleted.add(path)+ else:+ files[path] = diffs.get(path) or FileDiff(path=path)+ base, head = _change_ends(repo_path, revspec, staged=staged)+ return ChangeSet(files, deleted, label, base, head)+++def _change_ends(+ repo_path: str, revspec: str | None, *, staged: bool+) -> tuple[str | None, str | None]:+ """The commits a change goes from and to; ``None`` where git names none."""++ def sha(rev: str) -> str | None:+ args = ["rev-parse", "--verify", "--quiet", f"{rev}^{{commit}}"]+ return _git(args, repo_path, check=False).strip() or None++ if staged or not revspec:+ return sha("HEAD"), None+ if (parts := split_revspec(revspec)) is not None:+ base, sep, head = parts+ if sep == "...":+ fork = _git(["merge-base", base, head], repo_path, check=False).strip()+ return fork or None, sha(head)+ return sha(base), sha(head)+ return sha(f"{revspec}^"), sha(revspec)def _working_tree_lines(repo_path: str, base: str | None) -> tuple[dict[str, set[int]], str]:@@ -378,3 +446,23 @@ def is_shallow_root(repo_path: str, rev: str) -> bool:return Falsesha = _git(["rev-parse", "--verify", "--quiet", f"{rev}^{{commit}}"], repo_path, check=False)return bool(sha.strip()) and sha.strip() in path.read_text(encoding="utf-8").split()+++def index_gap(repo_path: str, indexed_commit: str | None, change: ChangeSet) -> list[str] | None:+ """Files outside *change* that differ between *indexed_commit* and its base.++ What an index built at another commit cannot see. Empty when the index was+ built at either end of the change; ``None`` when that cannot be told (no+ recorded commit, no base, or a commit this clone lacks).+ """+ if indexed_commit and indexed_commit in (change.base, change.head):+ return []+ if not indexed_commit or not change.base:+ return None+ args = ["diff", "--name-only", "-z", "--no-renames", indexed_commit, change.base]+ try:+ listing = _git(args, repo_path)+ except (subprocess.SubprocessError, OSError):+ return None+ touched = set(change.files) | change.deleted+ return [p for p in listing.split("\0") if p.strip() and p not in touched]diff --git a/packages/core/src/repowise/core/analysis/test_reachability.py b/packages/core/src/repowise/core/analysis/test_reachability.pyindex 2a7493e3c..4ac118f01 100644--- a/packages/core/src/repowise/core/analysis/test_reachability.py+++ b/packages/core/src/repowise/core/analysis/test_reachability.py@@ -402,6 +402,33 @@ async def load_test_files(session: AsyncSession, repo_id: str) -> set[str]:return {row[0] for row in res.all()}+async def placed_test_files(session: AsyncSession, repo_id: str) -> set[str]:+ """Test files with a resolved dependency edge into a non-test file of the repository.++ Only these can be found by walking back from a changed file; a test with+ none (every import unresolved, or it only runs a subprocess) is invisible.+ An edge into test material (a conftest, a helper) or a third-party module+ (``external:``) does not count: it says nothing about which of the+ repository's files the test exercises.+ """+ params: dict[str, Any] = {"repo_id": repo_id, "is_test": True, "not_test": False}+ ets = _in_clause("e", sorted(FILE_DEPENDENCY_EDGE_TYPES), params)+ rows = await session.execute(+ text(+ "SELECT DISTINCT e.source_node_id FROM graph_edges e "+ "JOIN graph_nodes s ON s.repository_id = e.repository_id "+ "AND s.node_id = e.source_node_id "+ "JOIN graph_nodes t ON t.repository_id = e.repository_id "+ "AND t.node_id = e.target_node_id "+ f"WHERE e.repository_id = :repo_id AND e.edge_type IN ({ets}) "+ "AND s.is_test = :is_test AND t.is_test = :not_test AND t.node_type = 'file' "+ "AND t.node_id NOT LIKE 'external:%'"+ ),+ params,+ )+ return {row[0] for row in rows}++async def tests_reaching(session: AsyncSession,repo_id: str,diff --git a/packages/core/src/repowise/core/analysis/test_selection.py b/packages/core/src/repowise/core/analysis/test_selection.pynew file mode 100644index 000000000..787574fe3--- /dev/null+++ b/packages/core/src/repowise/core/analysis/test_selection.py@@ -0,0 +1,919 @@+"""Pick the tests a change needs to run, or say why it needs them all.++``repowise impacted-tests`` names the tests that cover or reach each changed+file. A CI job can only trust that as a subset when every part of the answer+is positively known, so :func:`select_tests` fails closed: anything it cannot+vouch for answers "run everything", and the answer always says why. A full run+is chosen when any of these hold:++1. there is no change to select from;+2. a changed or deleted file can change any test: a dependency lock or+ manifest, build or test configuration, a production package's+ ``__init__.py``, a shared test helper, CI config, Repowise's own config, or+ a path listed in ``tests.full_run_on``;+3. a changed or deleted file sits in a test tree but is not code (data, a+ snapshot, a golden file), or is a helper module no test imports;+4. a changed file is neither code the index knows nor documentation, or is+ documentation some code names (a test may read it);+5. a changed code file has no known test, only a filename guess names one, or+ a route to it passes through a test helper no test imports, or any Python+ test helper while a conftest or pytest config loads plugins by name (its+ users are unknown);+6. the index is missing, was built before other files changed, disagrees with+ itself about its commit, or its graph could not be read;+7. the per-test map hit its stored row cap;+8. a deleted code file has no known test, or a test the index names is+ missing from the checkout.++Otherwise the subset is the covering tests, the tests the graph shows reaching+the changed files (a changed test, the call graph, the import graph) and+``tests.always_run``, plus every test the graph cannot see into (not indexed,+or with no resolved edge). A test package's ``__init__.py`` or a ``conftest.py``+(changed, deleted, or on a route to a changed file) stands for every test under+its directory. A helper module tests import stands for the tests that import+it, directly or through other helpers (basis ``helper-importers``), which are the files that run it: Python runs the package file+for each module in it, and pytest loads a conftest for each test at or below+it. Only documentation (``docs/`` and the root README,+CHANGELOG, LICENSE and the like, never code) that no code names is skipped+without a test.++:func:`runner_args` renders a selection as arguments for one test runner; a+full run renders as the :data:`RUN_ALL` sentinel. pytest and go reject it as a+path; jest and vitest treat arguments as patterns and would match nothing, so+a pipeline must branch on the run-all flag rather than rely on the sentinel.+"""++from __future__ import annotations++import configparser+import re+import shlex+import tomllib+from collections.abc import Callable, Collection, Iterable, Mapping+from dataclasses import dataclass, field+from fnmatch import fnmatchcase+from pathlib import PurePosixPath+from typing import Any++import pathspec++from ..test_paths import is_test_path, is_test_related_path, is_test_support_path++#: Printed alone instead of arguments when every test must run.+RUN_ALL = ":all"++RUNNERS = ("auto", "pytest", "go", "jest", "files")++# (why it forces a full run, gitwildmatch patterns). The config extends these,+# never replaces them. Ceiling: no opt-out until someone needs one.+_FULL_RUN_GROUPS: tuple[tuple[str, tuple[str, ...]], ...] = (+ (+ "dependencies can change any test",+ (+ "package-lock.json",+ "yarn.lock",+ "pnpm-lock.yaml",+ "poetry.lock",+ "uv.lock",+ "Pipfile.lock",+ "Pipfile",+ "requirements*.txt",+ "constraints*.txt",+ "go.mod",+ "go.sum",+ "Cargo.lock",+ "Cargo.toml",+ "Gemfile.lock",+ "Gemfile",+ "composer.lock",+ "composer.json",+ ),+ ),+ (+ "build or test configuration can change any test",+ (+ "pyproject.toml",+ "setup.py",+ "setup.cfg",+ "package.json",+ "tsconfig*.json",+ "jest.config.*",+ "vitest.config.*",+ "vite.config.*",+ "pytest.ini",+ "tox.ini",+ "noxfile.py",+ "Makefile",+ "CMakeLists.txt",+ "build.gradle*",+ "settings.gradle*",+ "pom.xml",+ "Dockerfile*",+ "docker-compose*.y*ml",+ ),+ ),+ ("shared test data can change any test", ("**/testdata/**", "**/fixtures/**")),+ (+ "CI configuration changed",+ (+ ".github/workflows/**",+ ".gitlab-ci.yml",+ "**/.gitlab-ci.yml",+ ".gitlab/**",+ ".circleci/**",+ "Jenkinsfile*",+ "azure-pipelines*.y*ml",+ ".azure-pipelines/**",+ ".buildkite/**",+ "bitbucket-pipelines.yml",+ ".travis.yml",+ ".drone.y*ml",+ ".woodpecker/**",+ ".woodpecker.y*ml",+ "appveyor.y*ml",+ ".teamcity/**",+ ),+ ),+ ("Repowise's configuration changed", (".repowise/config.yaml",)),+)++_DEFAULT_SPECS = tuple(+ (why, pathspec.PathSpec.from_lines("gitwildmatch", patterns))+ for why, patterns in _FULL_RUN_GROUPS+)++# Documentation only: ``docs/`` and root-level project meta. A doc or image+# anywhere else may be package data a test reads, so it is not skipped.+_DOCS_SPEC = pathspec.PathSpec.from_lines("gitwildmatch", ["/docs/**"])+_ROOT_META = (+ "readme",+ "changelog",+ "changes",+ "history",+ "license",+ "licence",+ "copying",+ "notice",+ "authors",+ "contributors",+ "contributing",+ "code_of_conduct",+ "security",+)+# A root file only reads as project meta with no extension or a prose one:+# ``history.json`` or ``changes.yaml`` is data a test may load.+_DOC_SUFFIXES = frozenset({"", ".md", ".markdown", ".rst", ".txt", ".adoc"})++# Extensions a test runner collects tests from; anything else in a test tree+# (data, snapshots, golden files) is read by tests, not run.+_TEST_CODE_SUFFIXES = frozenset(+ {".py", ".go", ".java", ".kt", ".kts", ".scala", ".groovy", ".rb", ".cs", ".fs"}+ | {".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts"}+ | {".rs", ".php", ".swift", ".ex", ".exs", ".dart", ".c", ".cc", ".cpp"}+)++_PYTHON = (".py",)+_JS = (".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts")+# coverage.py names each phase of a test as its own context.+_PHASES = ("|run", "|setup", "|teardown")+++@dataclass(frozen=True)+class TestSelectionConfig:+ """``tests.full_run_on`` and ``tests.always_run`` from ``.repowise/config.yaml``."""++ __test__ = False # not a pytest class, whatever its name says++ full_run_on: tuple[str, ...] = ()+ always_run: tuple[str, ...] = ()++ @classmethod+ def from_repo_config(cls, raw: Mapping[str, Any]) -> TestSelectionConfig:+ """Parse the ``tests`` block; raises ``ValueError`` naming what is wrong.++ A misspelt key is refused rather than ignored: a full-run trigger that+ silently stops applying would skip tests the change needs.+ """+ block = raw.get("tests")+ if block is None:+ return cls()+ if not isinstance(block, Mapping):+ raise ValueError(f"tests must be a mapping, got {type(block).__name__}.")+ unknown = sorted(set(block) - {"full_run_on", "always_run"})+ if unknown:+ raise ValueError(+ f"tests.{unknown[0]} is not a setting; use tests.full_run_on or "+ "tests.always_run."+ )+ return cls(+ full_run_on=_string_list(block, "full_run_on"),+ always_run=_string_list(block, "always_run"),+ )+++def _string_list(block: Mapping[str, Any], key: str) -> tuple[str, ...]:+ value = block.get(key)+ if value is None:+ return ()+ if not isinstance(value, list) or not all(isinstance(v, str) and v.strip() for v in value):+ raise ValueError(f"tests.{key} must be a list of non-empty strings, got {value!r}.")+ return tuple(v.strip() for v in value)+++@dataclass(frozen=True)+class Selection:+ """What to run for a change, and why.++ ``tests`` are what a runner that takes test ids (pytest) is given: covering+ test ids where coverage named them, else whole test files. ``test_files``+ are the files behind them, for runners that take files. ``packages`` are+ the directories of changed Go files that hold tests of their own. ``basis``+ names, per changed or deleted file, what decided it: ``full-run``,+ ``no-tests-needed``, ``deleted-test``, ``test-tree``, ``test-package``,+ ``conftest``, ``helper-importers``, ``coverage``,+ ``changed-test``, ``call-graph``, ``import-graph``, ``filename-pattern``,+ ``unknown``, or ``none`` when nothing was asked (no index).+ """++ run_all: bool+ reasons: tuple[str, ...]+ tests: tuple[str, ...] = ()+ test_files: tuple[str, ...] = ()+ packages: tuple[str, ...] = ()+ always_run: tuple[str, ...] = ()+ skipped_files: tuple[str, ...] = ()+ basis: Mapping[str, str] = field(default_factory=dict)+ pytest_testpaths: tuple[str, ...] = ()++ def to_dict(self) -> dict[str, Any]:+ return {+ "run_all": self.run_all,+ "reasons": list(self.reasons),+ "tests": list(self.tests),+ "test_files": list(self.test_files),+ "packages": list(self.packages),+ "always_run": list(self.always_run),+ "skipped_files": list(self.skipped_files),+ "basis": dict(self.basis),+ }+++def is_documentation(path: str) -> bool:+ """``docs/**`` or a root-level README, CHANGELOG, LICENSE and the like.++ Never code: a ``docs/conf.py``, an example a test imports, or a root+ ``history.py`` is a module like any other, so the graph decides it.+ """+ if is_code_file(path):+ return False+ if _DOCS_SPEC.match_file(path):+ return True+ p = PurePosixPath(path)+ return (+ len(p.parts) == 1+ and p.suffix.lower() in _DOC_SUFFIXES+ and p.name.lower().startswith(_ROOT_META)+ )+++# pytest config a doctest glob or a plugin can be declared in.+_PYTEST_CONFIGS = frozenset({"pyproject.toml", "setup.cfg", "pytest.ini", "tox.ini"})+# ``pytest_plugins = [...]`` or ``-p name`` (not ``-p no:name``, which disables one).+_PLUGIN_DECLARATION = re.compile(r"\bpytest_plugins\b|(?:^|[\s\"'=])-p\s*(?!no:)[A-Za-z_]")+++def is_scan_source(path: str) -> bool:+ """Code or pytest config: the files :func:`doc_readers` and :func:`plugin_loader` read."""+ name = PurePosixPath(path).name+ return is_code_file(path) or name in _PYTEST_CONFIGS+++def doc_readers(docs: Collection[str], sources: Iterable[tuple[str, str]]) -> dict[str, str]:+ """``{doc: a file naming it}`` for each of *docs* some code or config names.++ A test that reads a doc names it (``ROOT / "README.md"``), and a+ ``--doctest-glob`` turns every doc into a test, so either means the doc's+ tests are unknown. Ceiling: a test that globs a directory names no file.+ """+ names = {doc: PurePosixPath(doc).name for doc in docs}+ out: dict[str, str] = {}+ for path, text in sources:+ # Config only for the glob, code only for names: pyproject's+ # ``readme = "README.md"`` is packaging, not a test.+ if not is_code_file(path):+ if "doctest-glob" in text:+ return {doc: path for doc in docs}+ continue+ for doc, name in names.items():+ if doc not in out and name in text:+ out[doc] = path+ return out+++def plugin_loader(sources: Iterable[tuple[str, str]]) -> str | None:+ """The first conftest or pytest config that loads a plugin module by name.++ Such a plugin's fixtures reach tests that never import it, so while one is+ declared, a test helper's importers are not all of its users.+ """+ for path, text in sources:+ name = PurePosixPath(path).name+ pytest_file = name == "conftest.py" or name in _PYTEST_CONFIGS+ if pytest_file and _PLUGIN_DECLARATION.search(text):+ return path+ return None+++_PACKAGE_INIT_REASON = "every import of the package runs it, and those are not all tracked"+++def scope_kind(path: str) -> str | None:+ """``test-package`` or ``conftest`` for a file every test under its directory runs.++ A test tree's ``__init__.py`` runs for each module in the package, and+ pytest loads a ``conftest.py`` for each test at or below its directory, so+ those tests are exactly its users.+ """+ name = PurePosixPath(path).name+ if name == "conftest.py":+ return "conftest"+ if name == "__init__.py" and is_test_related_path(path):+ return "test-package"+ return None+++def is_code_file(path: str) -> bool:+ """A file with an extension a test runner loads, test or not."""+ return PurePosixPath(path).suffix.lower() in _TEST_CODE_SUFFIXES+++def is_test_helper(path: str) -> bool:+ """Code in a test tree that is neither a test nor a directory-scoped file."""+ return (+ is_code_file(path)+ and is_test_related_path(path)+ and not is_runnable_test(path)+ and scope_kind(path) is None+ )+++def is_runnable_test(path: str) -> bool:+ """A test-shaped file name with an extension a runner collects tests from."""+ p = PurePosixPath(path)+ return p.suffix.lower() in _TEST_CODE_SUFFIXES and is_test_path(p.name)+++def full_run_reason(path: str, extra: Iterable[str] = ()) -> str | None:+ """Why a change to *path* can change any test, or ``None``."""+ specs = list(_DEFAULT_SPECS)+ if extra := tuple(extra):+ spec = pathspec.PathSpec.from_lines("gitwildmatch", extra)+ specs.append(("it matches tests.full_run_on", spec))+ for why, spec in specs:+ if spec.match_file(path):+ return why+ if PurePosixPath(path).name == "__init__.py" and not is_test_related_path(path):+ return _PACKAGE_INIT_REASON+ if is_test_support_path(path) and scope_kind(path) is None:+ return "a shared test helper can change any test"+ return None+++@dataclass(frozen=True)+class SelectionInput:+ """Everything :func:`select_tests` decides from.++ *changed* are the paths present after the change, *deleted* those it+ removed, *label* names the change; *tiers* is ``impacted-tests``' result+ (``covered``, ``inferred``, ``unknown``, ``helper_importers``).+ *map_current* is false when the per-test map was measured at neither end of+ the change, so its tests were matched by file; *map_truncated* when it holds+ as many rows as the store keeps. *index_gap* lists the files that changed+ between the indexed commit and the change, ``None`` when that cannot be+ told; *index_problem* says why the index's own commit cannot be trusted.+ *graph_error* names a graph read that failed. *missing* are test files the+ tiers name that the checkout does not have; *go_test_dirs* the directories+ holding ``_test.go`` files; *known_tests* every runnable test in the+ checkout, which a test package's ``__init__.py`` or a ``conftest.py``+ expands to. *doc_readers* maps a changed doc to a file naming it+ (:func:`doc_readers`); *plugin_loader* is a file loading pytest plugins by+ name (:func:`plugin_loader`); *unplaced_tests* are tests the graph cannot+ see into (not indexed, or with no resolved edge), which every subset runs.+ """++ changed: Collection[str]+ deleted: Collection[str]+ tiers: Mapping[str, Any]+ config: TestSelectionConfig = field(default_factory=TestSelectionConfig)+ index_available: bool = True+ label: str = "the base"+ map_current: bool = True+ map_truncated: bool = False+ index_gap: Collection[str] | None = ()+ index_problem: str | None = None+ graph_error: str | None = None+ missing: Collection[str] = ()+ go_test_dirs: Collection[str] = ()+ known_tests: Collection[str] = ()+ doc_readers: Mapping[str, str] = field(default_factory=dict)+ plugin_loader: str | None = None+ unplaced_tests: Collection[str] = ()+ pytest_testpaths: tuple[str, ...] = ()+++@dataclass+class _Triage:+ """The changed paths sorted by what decides them, before any test is asked."""++ run_all: list[str] = field(default_factory=list)+ basis: dict[str, str] = field(default_factory=dict)+ skipped: list[str] = field(default_factory=list)+ code: list[str] = field(default_factory=list)+++def select_tests(inp: SelectionInput) -> Selection:+ """Decide what a change must run (see the module docstring for the rules)."""+ deleted = set(inp.deleted)+ paths = sorted(set(inp.changed) | deleted)+ triage = _triage(paths, inp.config, inp.doc_readers)+ run_all = [*_empty_change_reasons(paths, inp.label), *triage.run_all]+ run_all += _index_reasons(inp, has_code=bool(triage.code))++ evidence = _Evidence.of(inp, deleted)+ per_file, file_reasons = _tests_per_file(triage.code, evidence)+ if inp.index_available:+ run_all += file_reasons+ basis = {**triage.basis, **{path: per_file[path][1] for path in triage.code}}++ # The graph cannot say what an unplaced test reaches, so it always runs.+ unplaced = [(t, t) for t in inp.unplaced_tests] if triage.code else []+ tests, test_files = _runnable(+ [*(t for path in triage.code for t in per_file[path][0]), *unplaced]+ )+ return Selection(+ run_all=bool(run_all),+ reasons=tuple(run_all + _notes(inp, triage.skipped, bool(unplaced))),+ tests=tests,+ test_files=test_files,+ packages=_go_packages(triage.code, deleted, inp.go_test_dirs),+ always_run=inp.config.always_run,+ skipped_files=tuple(triage.skipped),+ basis=basis,+ pytest_testpaths=inp.pytest_testpaths,+ )+++def _triage(+ paths: list[str], config: TestSelectionConfig, doc_readers: Mapping[str, str]+) -> _Triage:+ """Full-run triggers, documentation and test-tree data first; code for the tiers."""+ out = _Triage()+ for path in paths:+ if why := full_run_reason(path, config.full_run_on):+ out.run_all.append(f"{path} changed: {why}.")+ out.basis[path] = "full-run"+ elif is_documentation(path) and (reader := doc_readers.get(path)):+ out.run_all.append(+ f"{path} is named by {reader}, so a test may read it; the tests "+ "that do are not tracked."+ )+ out.basis[path] = "full-run"+ elif is_documentation(path):+ out.skipped.append(path)+ out.basis[path] = "no-tests-needed"+ elif is_test_related_path(path) and not is_code_file(path):+ out.run_all.append(+ f"{path} is in a test tree but is not code (data, a snapshot or a "+ "golden file); the tests that read it are not tracked."+ )+ out.basis[path] = "test-tree"+ else:+ out.code.append(path)+ return out+++def _empty_change_reasons(paths: list[str], label: str) -> list[str]:+ return [] if paths else [f"No change against {label}; nothing to select from."]+++def _index_reasons(inp: SelectionInput, *, has_code: bool) -> list[str]:+ """Why the index cannot vouch for the tiers; nothing to say without code."""+ if not has_code:+ return []+ if not inp.index_available:+ return [+ "No index: nothing records which tests reach the changed code "+ "(run `repowise init`, or restore a cached .repowise directory)."+ ]+ out = [inp.index_problem] if inp.index_problem else _gap_reasons(inp.index_gap)+ if inp.graph_error:+ out.append(+ f"The graph could not be read ({inp.graph_error}), so the tests reaching "+ "the changed files are unknown."+ )+ if inp.map_truncated:+ out.append(+ "The per-test map is at its stored row cap, so some tests' coverage "+ "was dropped when it was ingested."+ )+ return out+++def _notes(inp: SelectionInput, skipped: list[str], unplaced: bool) -> list[str]:+ """Reasons that explain the selection without forcing a full run."""+ out = []+ if unplaced:+ out.append(+ f"{len(inp.unplaced_tests)} test file(s) the graph cannot see into run with "+ f"every selection (e.g. {sorted(inp.unplaced_tests)[0]})."+ )+ if not inp.map_current and inp.tiers.get("covered"):+ out.append(+ "The per-test map was measured at another commit, so covering tests "+ "are matched by file, not by changed line."+ )+ if skipped:+ out.append(f"{len(skipped)} changed file(s) are documentation: no tests needed.")+ return out+++def _go_packages(+ code: list[str], deleted: set[str], go_test_dirs: Collection[str]+) -> tuple[str, ...]:+ """Directories of changed Go files that hold same-package tests."""+ dirs = {+ str(PurePosixPath(p).parent)+ for p in code+ if p.endswith(".go") and not p.endswith("_test.go") and p not in deleted+ }+ return tuple(sorted(dirs & set(go_test_dirs)))+++def _gap_reasons(index_gap: Collection[str] | None) -> list[str]:+ if index_gap is None:+ return [+ "Cannot tell what changed since the index was built (its commit is not "+ "recorded, or not in this clone); run `repowise update` before selecting."+ ]+ unseen = sorted(p for p in index_gap if not is_documentation(p))+ if not unseen:+ return []+ return [+ f"The index predates {len(unseen)} changed file(s) outside this change "+ f"(e.g. {unseen[0]}), so its graph cannot see them; run `repowise update` "+ "before selecting."+ ]+++_TestRef = tuple[str, str | None] # (test id or file, the file it lives in)++# Bases that need no test of their own to be safe.+_SELF_SUFFICIENT = ("deleted-test", "test-package", "conftest")+++@dataclass(frozen=True)+class _Evidence:+ """The tiers indexed by changed file, and what the checkout lacks."""++ covered: Mapping[str, list[_TestRef]]+ inferred: Mapping[str, list[tuple[str, str]]]+ unknown: frozenset[str]+ importers: Mapping[str, Collection[str]]+ missing: frozenset[str]+ deleted: frozenset[str]+ known_tests: tuple[str, ...]+ plugin_loader: str | None++ @classmethod+ def of(cls, inp: SelectionInput, deleted: set[str]) -> _Evidence:+ covered: dict[str, list[_TestRef]] = {}+ for test_id, info in (inp.tiers.get("covered") or {}).items():+ for source in info.get("source_files", ()):+ covered.setdefault(source, []).append((test_id, info.get("test_file") or None))+ inferred: dict[str, list[tuple[str, str]]] = {}+ for row in inp.tiers.get("inferred") or ():+ inferred.setdefault(row["source_file"], []).append((row["test_file"], row["via"]))+ return cls(+ covered=covered,+ inferred=inferred,+ unknown=frozenset(inp.tiers.get("unknown") or ()),+ importers=inp.tiers.get("helper_importers") or {},+ missing=frozenset(inp.missing),+ deleted=frozenset(deleted),+ known_tests=tuple(inp.known_tests),+ plugin_loader=inp.plugin_loader,+ )++ def found(self, path: str) -> list[_TestRef]:+ """What the graph named for *path*, a name-shaped guess excluded."""+ return [(t, t) for t, via in self.inferred.get(path, ()) if via != "filename-pattern"]++ def guesses(self, path: str) -> list[str]:+ return [t for t, via in self.inferred.get(path, ()) if via == "filename-pattern"]++ def present(self, tests: list[_TestRef]) -> list[_TestRef]:+ """*tests* the checkout still has; a test this change deletes is gone."""+ return [(t, f) for t, f in tests if f not in self.missing and f not in self.deleted]+++def _tests_per_file(+ code: list[str], ev: _Evidence+) -> tuple[dict[str, tuple[list[_TestRef], str]], list[str]]:+ """``{path: ([(test id or file, test file)], basis)}`` and the run-all reasons."""+ reasons = _stale_index_reasons(ev)+ out: dict[str, tuple[list[_TestRef], str]] = {}+ for path in code:+ tests, basis, file_reasons = _file_tests(path, ev)+ out[path] = (tests, basis)+ reasons += file_reasons+ return out, reasons+++def _stale_index_reasons(ev: _Evidence) -> list[str]:+ stale = sorted(ev.missing - ev.deleted)+ if not stale:+ return []+ return [+ f"{stale[0]} is a test the index names but the checkout does not have "+ f"({len(stale)} such), so the index is out of date; run `repowise update`."+ ]+++def _file_tests(path: str, ev: _Evidence) -> tuple[list[_TestRef], str, list[str]]:+ """One changed file's tests, the evidence behind them, and any run-all reasons."""+ found = ev.found(path)+ tests = ev.present([*ev.covered.get(path, ()), *found])+ basis = _basis(path, ev.covered, ev.inferred, ev.unknown)+ scopes, basis = _scope_files(path, found, basis)+ tests = _expand_scopes(tests, scopes, ev)+ helpers = sorted(+ {f for _, f in found if not is_runnable_test(f)} - ev.deleted - scopes - {path}+ )+ drop = {*helpers, path} if is_test_helper(path) else set(helpers)+ tests = [(t, f) for t, f in tests if f is None or f not in drop]+ if is_test_helper(path):+ return tests, "helper-importers", _own_helper_reasons(path, ev)++ reasons = _helper_route_reasons(path, helpers, ev) + _unfiled_reasons(path, tests)+ # A deleted test needs no run of its own; the tests importing it do.+ if path in ev.deleted and is_runnable_test(path):+ basis = "deleted-test"+ if not (tests or helpers or basis in _SELF_SUFFICIENT):+ reasons.append(_no_test_reason(path, basis, ev))+ return tests, basis, reasons+++def _scope_files(path: str, found: list[_TestRef], basis: str) -> tuple[set[str], str]:+ """Test-package ``__init__.py`` / ``conftest.py`` files on *path*'s routes, or itself.++ Each runs for every test under its directory, so it stands for those tests+ rather than for itself.+ """+ scopes = {f for _, f in found if f and scope_kind(f)}+ if kind := scope_kind(path):+ scopes.add(path)+ basis = kind+ return scopes, basis+++def _expand_scopes(tests: list[_TestRef], scopes: set[str], ev: _Evidence) -> list[_TestRef]:+ kept = [(t, f) for t, f in tests if f not in scopes]+ return kept + [(t, t) for t in _tests_under(scopes, ev.known_tests) if t not in ev.deleted]+++def _own_helper_reasons(path: str, ev: _Evidence) -> list[str]:+ """A changed helper stands for its importers; one no test imports is unknown."""+ if plugin := _plugin_reason(path, ev):+ return [plugin]+ if ev.importers.get(path):+ return []+ return [+ f"{path} is a test helper no test imports; tests that use it without an "+ "import are not tracked."+ ]+++def _plugin_reason(helper: str, ev: _Evidence) -> str | None:+ """A Python helper may be a plugin, whose fixtures reach tests that never import it."""+ if not (ev.plugin_loader and helper.endswith(_PYTHON)):+ return None+ return (+ f"{helper} is a test helper and {ev.plugin_loader} loads pytest plugins by "+ "name, so tests that use its fixtures without an import are not tracked."+ )+++def _helper_route_reasons(path: str, helpers: list[str], ev: _Evidence) -> list[str]:+ """A helper on a route stands for its importers, which the walk adds beside it.++ One no test imports is used some other way (a fixture, a plugin), so its+ users are unknown.+ """+ plugins = [r for h in helpers if (r := _plugin_reason(h, ev))]+ if plugins:+ return [f"{path} is reached through a test helper: {plugins[0]}"]+ unimported = [h for h in helpers if not ev.importers.get(h)]+ if not unimported:+ return []+ return [+ f"{path} is reached through the test helper {unimported[0]}, and no test "+ "imports that helper; tests that use it without an import are not tracked."+ ]+++def _unfiled_reasons(path: str, tests: list[_TestRef]) -> list[str]:+ return [+ f"Coverage names {test_id} for {path}, but not its file."+ for test_id, test_file in tests+ if test_file is None+ ]+++def _no_test_reason(path: str, basis: str, ev: _Evidence) -> str:+ """Why a changed file with no test left forces a full run."""+ if path in ev.deleted:+ return f"{path} was deleted and no test is known to have used it."+ if guesses := ev.guesses(path):+ return f"{path}: only a filename guess names a test ({guesses[0]})."+ if basis in ("unknown", "none"):+ return f"{path}: no coverage, no test reaching it in the graph, no paired test."+ return f"{path}: its only known tests are not in the checkout."+++def _tests_under(inits: Collection[str], known_tests: Collection[str]) -> list[str]:+ """Every known test below the directory of each scope file."""+ dirs = {str(PurePosixPath(i).parent) for i in inits}+ return [+ t for t in known_tests if any(d == "." or t.startswith(f"{d}/") for d in dirs)+ ]+++def _basis(+ path: str,+ covered: Mapping[str, Any],+ inferred: Mapping[str, list[tuple[str, str]]],+ unknown: set[str],+) -> str:+ """The strongest evidence behind *path*'s tests."""+ if path in covered:+ return "coverage"+ vias = {via for _, via in inferred.get(path, ())}+ for via in ("changed-test", "call-graph", "import-graph", "filename-pattern"):+ if via in vias:+ return via+ return "unknown" if path in unknown else "none"+++def _runnable(selected: list[_TestRef]) -> tuple[tuple[str, ...], tuple[str, ...]]:+ """``(tests, test_files)``: node ids and whole files, deduplicated, stable.++ A node id whose whole file is selected anyway is dropped.+ """+ files: dict[str, None] = {}+ whole: set[str] = set()+ ids: dict[str, None] = {}+ for test, test_file in selected:+ if test_file is None:+ continue+ files[test_file] = None+ node = _node_id(test, test_file)+ if node == test_file:+ whole.add(test_file)+ ids[node] = None+ tests = [t for t in ids if t in whole or t.split("::", 1)[0] not in whole]+ return tuple(tests), tuple(files)+++def _node_id(test_id: str, test_file: str) -> str:+ """A runnable id: ``file::name`` rebased on the resolved file, else the file."""+ for phase in _PHASES:+ if test_id.endswith(phase):+ test_id = test_id[: -len(phase)]+ break+ if "::" not in test_id:+ return test_file+ return f"{test_file}::{test_id.split('::', 1)[1]}"+++def _all_python(files: tuple[str, ...], packages: tuple[str, ...]) -> bool:+ return bool(files) and all(f.endswith(_PYTHON) for f in files)+++def _all_go(files: tuple[str, ...], packages: tuple[str, ...]) -> bool:+ # A changed Go file's own package counts even with no selected test file.+ return bool(files or packages) and all(f.endswith("_test.go") for f in files)+++def _all_js(files: tuple[str, ...], packages: tuple[str, ...]) -> bool:+ return bool(files) and all(f.endswith(_JS) for f in files)+++# ``auto`` picks the first runner every selected test file belongs to.+_AUTO_RUNNERS = (("pytest", _all_python), ("go", _all_go), ("jest", _all_js))+++def resolve_runner(selection: Selection, runner: str) -> str:+ """*runner*, or for ``auto`` the one every selected test file belongs to."""+ if runner != "auto":+ return runner+ files, packages = selection.test_files, selection.packages+ return next((name for name, fits in _AUTO_RUNNERS if fits(files, packages)), "files")+++def _pytest_args(selection: Selection) -> list[str]:+ roots = selection.pytest_testpaths+ return [+ t+ for t in selection.tests+ if (f := t.split("::", 1)[0]).endswith(_PYTHON) and _pytest_collects(f, roots)+ ]+++def _pytest_collects(path: str, testpaths: tuple[str, ...]) -> bool:+ """Whether a bare ``pytest`` would run *path*, so passing it adds nothing new.++ A test-shaped module outside ``testpaths`` and outside any test tree is+ production code (``core/test_paths.py``) that pytest would fail to collect;+ a full run never runs it, so neither does a subset.+ """+ p = PurePosixPath(path)+ # A neutral file name asks about the directory alone: in a test tree, keep it.+ if not testpaths or is_test_related_path(str(p.parent / "__init__.py")):+ return True+ candidates = [path, *(str(parent) for parent in p.parents)]+ return any(fnmatchcase(c, root) for root in testpaths for c in candidates)+++# Where pytest reads ``testpaths`` from, in its own order: the first file that+# holds the section wins, and a ``pytest.ini`` wins even without one.+_PYTEST_SECTIONS = (+ ("pytest.ini", "pytest"),+ ("pyproject.toml", None),+ ("tox.ini", "pytest"),+ ("setup.cfg", "tool:pytest"),+)+++def pytest_testpaths(read: Callable[[str], str | None]) -> tuple[str, ...]:+ """``testpaths`` from the root pytest config (*read* returns a file's text or None).++ ``()`` when unset or unreadable, which filters nothing.+ """+ for name, section in _PYTEST_SECTIONS:+ if (text := read(name)) is None:+ continue+ try:+ value = _testpaths_value(text, section, always=name == "pytest.ini")+ except (tomllib.TOMLDecodeError, configparser.Error):+ return ()+ if value is not None:+ paths = value.split() if isinstance(value, str) else value+ return tuple(str(v).strip("/").removeprefix("./") or "." for v in paths)+ return ()+++def _testpaths_value(text: str, section: str | None, *, always: bool) -> Any:+ """The raw ``testpaths`` of one config, ``None`` when it has no pytest section."""+ if section is None:+ block = tomllib.loads(text).get("tool", {}).get("pytest", {}).get("ini_options")+ return None if block is None else block.get("testpaths", ())+ parser = configparser.ConfigParser(interpolation=None)+ parser.read_string(text)+ if not parser.has_section(section):+ return "" if always else None+ return parser.get(section, "testpaths", fallback="")+++def _go_args(selection: Selection) -> list[str]:+ go_tests = [f for f in selection.test_files if f.endswith("_test.go")]+ dirs = {str(PurePosixPath(f).parent) for f in go_tests} | set(selection.packages)+ return sorted("." if d == "." else f"./{d}" for d in dirs)+++def _jest_args(selection: Selection) -> list[str]:+ return [f for f in selection.test_files if f.endswith(_JS)]+++def _file_args(selection: Selection) -> list[str]:+ return list(selection.test_files)+++_RUNNER_ARGS = {"pytest": _pytest_args, "go": _go_args, "jest": _jest_args}+++def runner_args(selection: Selection, runner: str) -> list[str]:+ """Arguments for *runner* (already resolved); ``[RUN_ALL]`` for a full run.++ Each runner gets only the tests it can run, so a job per language can share+ one selection. ``tests.always_run`` entries are appended as written. jest+ and vitest get file paths, meant for ``--runTestsByPath``.+ """+ if selection.run_all:+ return [RUN_ALL]+ args = _RUNNER_ARGS.get(runner, _file_args)(selection)+ return list(dict.fromkeys([*args, *selection.always_run]))+++def format_args(args: Iterable[str]) -> str:+ """One shell-quoted line."""+ return shlex.join(args)diff --git a/packages/core/src/repowise/core/ci/base.py b/packages/core/src/repowise/core/ci/base.pyindex 6888be4bf..56fde2d7e 100644--- a/packages/core/src/repowise/core/ci/base.py+++ b/packages/core/src/repowise/core/ci/base.py@@ -11,7 +11,17 @@ from __future__ import annotationsimport osfrom collections.abc import Mapping-from .. import git_refs+#: Variables whose presence marks an automated CI run. ``CI`` covers most hosts;+#: the rest catch the ones that do not set it. Telemetry reads the same list.+CI_ENV_VARS = (+ "CI",+ "GITHUB_ACTIONS",+ "GITLAB_CI",+ "BUILDKITE",+ "JENKINS_URL",+ "TEAMCITY_VERSION",+ "TF_BUILD",+)#: Variables naming the branch a change will merge into, in the order they are#: consulted; each is read from the ``origin`` remote. A branch, not a base@@ -25,6 +35,13 @@ CI_BASE_VARS = ()+def in_ci(env: Mapping[str, str] | None = None) -> bool:+ """Whether this runs in a CI job: a CI marker or a pull-request variable is set."""+ env = os.environ if env is None else env+ values = (env.get(var, "").strip().lower() for var in (*CI_ENV_VARS, *CI_BASE_VARS))+ return any(v not in ("", "false", "0") for v in values)++class BaseNotFoundError(ValueError):"""No target branch could be determined; the caller should ask for a revspec."""@@ -36,6 +53,8 @@ def default_revspec(repo_root: str, env: Mapping[str, str] | None = None) -> strbranch, else ``origin/main`` / ``origin/master``. Raises:class:`BaseNotFoundError` when none resolves."""+ from .. import git_refs+env = os.environ if env is None else envfor var in CI_BASE_VARS:if branch := env.get(var, "").strip():diff --git a/packages/core/src/repowise/core/platform/telemetry.py b/packages/core/src/repowise/core/platform/telemetry.pyindex 57bc59566..962890811 100644--- a/packages/core/src/repowise/core/platform/telemetry.py+++ b/packages/core/src/repowise/core/platform/telemetry.py@@ -47,16 +47,6 @@ GROUP_LEAF_TYPES_ATTR = "repowise_group_leaf_types"_TRUTHY = {"1", "true", "yes", "on"}-#: Common CI signals (kept in sync with the CLI's environment module).-_CI_ENV_VARS = (- "CI",- "GITHUB_ACTIONS",- "GITLAB_CI",- "BUILDKITE",- "JENKINS_URL",- "TEAMCITY_VERSION",- "TF_BUILD",-)#: Groups the events emitted by this process (e.g. one MCP server session)._SESSION_ID = uuid.uuid4().hex@@ -113,7 +103,9 @@ def get_anonymous_id() -> str | None:def _is_ci() -> bool:- return any(os.environ.get(var) for var in _CI_ENV_VARS)+ from repowise.core.ci.base import CI_ENV_VARS++ return any(os.environ.get(var) for var in CI_ENV_VARS)def _version() -> str:diff --git a/tests/unit/analysis/test_changed_lines.py b/tests/unit/analysis/test_changed_lines.pyindex 303e65601..8bad613f6 100644--- a/tests/unit/analysis/test_changed_lines.py+++ b/tests/unit/analysis/test_changed_lines.py@@ -278,3 +278,79 @@ def test_change_health_refuses_a_shallow_boundary_commit(git_repo, tmp_path_facttext=True,).stdout.strip()assert GitRevisionSource(str(git_repo)).resolve(root).base_sha+++# --- change_set: every touched path, for test selection -----------------------+++def _sha(cwd, rev: str) -> str:+ return subprocess.run(+ ["git", "rev-parse", rev], cwd=cwd, check=True, capture_output=True, text=True+ ).stdout.strip()+++def test_change_set_keeps_what_changed_lines_drops(git_repo) -> None:+ from repowise.core.analysis.changed_lines import change_set++ (git_repo / "gone.py").write_text("x = 1\n", encoding="utf-8")+ (git_repo / "old_name.py").write_text("y = 1\n", encoding="utf-8")+ _git(git_repo, "add", "-A")+ _git(git_repo, "commit", "-qm", "more")+ # A removal-only edit, a deletion, a rename and a binary file.+ (git_repo / "mod.py").write_text("a = 1\nc = 3\n", encoding="utf-8")+ (git_repo / "gone.py").unlink()+ (git_repo / "old_name.py").rename(git_repo / "new_name.py")+ (git_repo / "logo.png").write_bytes(b"\x89PNG\x00\x01")+ _git(git_repo, "add", "-A")+ _git(git_repo, "commit", "-qm", "change")++ change = change_set(str(git_repo), "HEAD~1..HEAD")+ assert "mod.py" not in changed_lines(str(git_repo), "HEAD~1..HEAD")[0]+ assert set(change.files) == {"mod.py", "new_name.py", "logo.png"}+ assert change.deleted == {"gone.py", "old_name.py"}+ assert change.files["mod.py"].new_lines == set()+ assert change.files["mod.py"].old_ranges == [(2, 2)]+ assert change.label == "HEAD~1..HEAD"+ assert (change.base, change.head) == (_sha(git_repo, "HEAD~1"), _sha(git_repo, "HEAD"))+++def test_change_set_ends_for_a_commit_a_fork_and_the_index(git_repo) -> None:+ from repowise.core.analysis.changed_lines import change_set++ first = _sha(git_repo, "HEAD")+ _git(git_repo, "branch", "-M", "main")+ _git(git_repo, "switch", "-qc", "feat")+ (git_repo / "mod.py").write_text("a = 1\nb = 22\nc = 3\n", encoding="utf-8")+ _git(git_repo, "commit", "-qam", "feat edit")+ _git(git_repo, "switch", "-q", "main")+ (git_repo / "mod.py").write_text("a = 1\nb = 2\nc = 33\n", encoding="utf-8")+ _git(git_repo, "commit", "-qam", "base edit")++ fork = change_set(str(git_repo), "main...feat")+ assert (fork.base, fork.head) == (first, _sha(git_repo, "feat"))+ one = change_set(str(git_repo), "main")+ assert (one.base, one.head) == (first, _sha(git_repo, "main"))+ (git_repo / "mod.py").write_text("a = 0\nb = 2\nc = 33\n", encoding="utf-8")+ _git(git_repo, "add", "-A")+ staged = change_set(str(git_repo))+ assert (staged.base, staged.head) == (_sha(git_repo, "HEAD"), None)+ assert staged.label == "staged changes" and set(staged.files) == {"mod.py"}+ with pytest.raises(ValueError):+ change_set(str(git_repo), "nope..HEAD")+++def test_index_gap_names_what_an_older_index_cannot_see(git_repo) -> None:+ from repowise.core.analysis.changed_lines import change_set, index_gap++ indexed = _sha(git_repo, "HEAD")+ (git_repo / "other.py").write_text("o = 1\n", encoding="utf-8")+ _git(git_repo, "add", "-A")+ _git(git_repo, "commit", "-qm", "base moves")+ (git_repo / "mod.py").write_text("a = 9\nb = 2\nc = 3\n", encoding="utf-8")+ _git(git_repo, "commit", "-qam", "change")++ change = change_set(str(git_repo), "HEAD~1..HEAD")+ assert index_gap(str(git_repo), indexed, change) == ["other.py"]+ assert index_gap(str(git_repo), _sha(git_repo, "HEAD~1"), change) == []+ assert index_gap(str(git_repo), None, change) is None+ assert index_gap(str(git_repo), "0" * 40, change) is Nonediff --git a/tests/unit/analysis/test_test_selection.py b/tests/unit/analysis/test_test_selection.pynew file mode 100644index 000000000..2c59239e7--- /dev/null+++ b/tests/unit/analysis/test_test_selection.py@@ -0,0 +1,701 @@+"""Safe impacted-test selection: every full-run rule, the subset, runner arguments.++:func:`select_tests` is pure, so each rule is pinned on a hand-written tiers+result (the shape ``impacted-tests`` builds) without an index or git.+"""++from __future__ import annotations++import pytest++from repowise.core.analysis.test_selection import (+ RUN_ALL,+ Selection,+ SelectionInput,+ TestSelectionConfig,+ doc_readers,+ format_args,+ plugin_loader,+ pytest_testpaths,+ resolve_runner,+ runner_args,+ select_tests,+)++_NONE = TestSelectionConfig()+++def _tiers(covered=None, inferred=(), unknown=()):+ return {"covered": covered or {}, "inferred": list(inferred), "unknown": list(unknown)}+++def _inferred(source, test, via):+ return {"source_file": source, "test_file": test, "via": via}+++def _select(changed, tiers=None, config=_NONE, **kwargs):+ kwargs.setdefault("index_available", True)+ deleted = kwargs.pop("deleted", ())+ return select_tests(+ SelectionInput(changed, deleted, tiers or _tiers(), config, **kwargs)+ )+++# -- full-run rules -----------------------------------------------------------+++ ("path", "why"),+ [+ ("uv.lock", "uv.lock changed: dependencies can change any test."),+ ("web/package-lock.json", "dependencies can change any test"),+ ("requirements-dev.txt", "dependencies can change any test"),+ ("pyproject.toml", "build or test configuration can change any test"),+ ("web/tsconfig.base.json", "build or test configuration can change any test"),+ ("docker-compose.ci.yml", "build or test configuration can change any test"),+ ("pkg/testdata/input.json", "shared test data can change any test"),+ ("tests/fixtures/user.yaml", "shared test data can change any test"),+ (".github/workflows/ci.yml", "CI configuration changed"),+ (".gitlab-ci.yml", "CI configuration changed"),+ ("services/api/.gitlab-ci.yml", "CI configuration changed"),+ (".gitlab/ci/test.yml", "CI configuration changed"),+ (".circleci/config.yml", "CI configuration changed"),+ ("Jenkinsfile", "CI configuration changed"),+ ("Jenkinsfile.release", "CI configuration changed"),+ ("azure-pipelines.yml", "CI configuration changed"),+ ("azure-pipelines-pr.yaml", "CI configuration changed"),+ (".azure-pipelines/build.yml", "CI configuration changed"),+ (".buildkite/pipeline.yml", "CI configuration changed"),+ ("bitbucket-pipelines.yml", "CI configuration changed"),+ (".travis.yml", "CI configuration changed"),+ (".drone.yml", "CI configuration changed"),+ (".woodpecker/test.yml", "CI configuration changed"),+ (".woodpecker.yaml", "CI configuration changed"),+ ("appveyor.yml", "CI configuration changed"),+ (".teamcity/settings.kts", "CI configuration changed"),+ (".repowise/config.yaml", "Repowise's configuration changed"),+ ],+)+def test_a_file_that_can_change_any_test_runs_everything(path, why) -> None:+ sel = _select([path])+ assert sel.run_all+ assert any(why in r for r in sel.reasons)+ assert sel.basis[path] == "full-run"+++def test_the_configured_globs_extend_the_defaults() -> None:+ config = TestSelectionConfig(full_run_on=("schema/**",))+ assert _select(["schema/user.sql"], config=config).run_all+ assert "matches tests.full_run_on" in _select(["schema/a.sql"], config=config).reasons[0]+ # The defaults still apply beside the configured globs.+ assert _select(["uv.lock"], config=config).run_all+++def test_a_deleted_lockfile_runs_everything() -> None:+ assert _select([], deleted=["poetry.lock"]).run_all+++def test_an_unknown_code_file_runs_everything() -> None:+ sel = _select(["src/new.py"], _tiers(unknown=["src/new.py"]))+ assert sel.run_all+ assert sel.reasons[0].startswith("src/new.py: no coverage")+ assert sel.basis["src/new.py"] == "unknown"+++def test_only_a_filename_guess_runs_everything() -> None:+ tiers = _tiers(inferred=[_inferred("src/a.py", "tests/test_a.py", "filename-pattern")])+ sel = _select(["src/a.py"], tiers)+ assert sel.run_all+ assert sel.reasons == ("src/a.py: only a filename guess names a test (tests/test_a.py).",)+ assert sel.basis["src/a.py"] == "filename-pattern"+++def test_no_index_runs_everything_when_code_changed() -> None:+ sel = _select(["src/a.py"], index_available=False)+ assert sel.run_all+ assert sel.reasons[0].startswith("No index:")+ # One reason, not one per file on top of it.+ assert len(sel.reasons) == 1+++ ("path", "skipped"),+ [+ ("LICENSE", True),+ ("LICENSE-APACHE", True),+ ("README.md", True),+ ("CHANGELOG.md", True),+ ("docs/guide.rst", True),+ ("docs/img/logo.png", True),+ # Outside docs/ a document or image may be package data a test reads.+ ("assets/logo.SVG", False),+ ("packages/web/public/logo.png", False),+ ("src/pkg/README.md", False),+ ("packages/core/templates/page.md", False),+ ("src/notice.py", False),+ ("data/users.json", False),+ # Code is a module whatever its name or place, and root data is data.+ ("docs/conf.py", False),+ ("docs/examples/snippet.py", False),+ ("history.py", False),+ ("security.go", False),+ ("changes.json", False),+ ],+)+def test_only_documentation_is_skipped(path, skipped) -> None:+ sel = _select([path], _tiers(unknown=[path]))+ assert (path in sel.skipped_files) is skipped+ assert sel.run_all is not skipped+++def test_no_index_with_only_docs_changed_runs_nothing() -> None:+ sel = _select(["README.md", "docs/logo.png"], index_available=False)+ assert not sel.run_all+ assert sel.tests == ()+ assert sel.skipped_files == ("README.md", "docs/logo.png")+++def test_a_deleted_code_file_with_no_known_test_runs_everything() -> None:+ sel = _select([], _tiers(unknown=["src/gone.py"]), deleted=["src/gone.py"])+ assert sel.run_all+ assert sel.reasons == ("src/gone.py was deleted and no test is known to have used it.",)+++def test_a_deleted_code_file_runs_the_tests_that_imported_it() -> None:+ tiers = _tiers(inferred=[_inferred("src/gone.py", "tests/test_user.py", "import-graph")])+ sel = _select([], tiers, deleted=["src/gone.py"])+ assert not sel.run_all+ assert sel.tests == ("tests/test_user.py",)+++def test_a_deleted_test_needs_no_run_of_its_own() -> None:+ tiers = _tiers(inferred=[_inferred("tests/test_old.py", "tests/test_old.py", "changed-test")])+ sel = _select([], tiers, deleted=["tests/test_old.py"], missing=["tests/test_old.py"])+ assert not sel.run_all+ assert sel.tests == ()+ assert sel.basis == {"tests/test_old.py": "deleted-test"}+++def test_a_deleted_test_runs_the_tests_that_imported_it() -> None:+ tiers = _tiers(+ inferred=[+ _inferred("tests/test_base.py", "tests/test_base.py", "changed-test"),+ _inferred("tests/test_base.py", "tests/test_child.py", "import-graph"),+ ]+ )+ sel = _select([], tiers, deleted=["tests/test_base.py"], missing=["tests/test_base.py"])+ assert not sel.run_all+ assert sel.tests == ("tests/test_child.py",)+++def test_an_empty_change_runs_everything() -> None:+ sel = _select([], label="origin/main...HEAD")+ assert sel.run_all+ assert sel.reasons == ("No change against origin/main...HEAD; nothing to select from.",)+++def test_a_change_of_only_documentation_needs_no_tests() -> None:+ sel = _select(["docs/guide.md", "README.md"])+ assert not sel.run_all+ assert runner_args(sel, "pytest") == []+++ "path",+ [+ "tests/helpers.py",+ "tests/utils.py",+ "tests/unit/persistence/helpers.py",+ "tests/data/users.json",+ "tests/__snapshots__/app.test.ts.snap",+ "tests/golden/report.txt",+ "tests/plugins/timing.py",+ ],+)[email protected]("deleted", [False, True])+def test_a_test_tree_file_that_is_not_a_test_runs_everything(path, deleted) -> None:+ changed, gone = ([], [path]) if deleted else ([path], [])+ sel = _select(changed, _tiers(), deleted=gone)+ assert sel.run_all+ assert any(r.startswith(f"{path} ") for r in sel.reasons), sel.reasons++[email protected]("deleted", [False, True])+def test_a_production_package_init_runs_everything(deleted) -> None:+ path = "src/pkg/__init__.py"+ sel = _select([], deleted=[path]) if deleted else _select([path])+ assert sel.run_all+ assert sel.reasons[0] == (+ f"{path} changed: every import of the package runs it, and those are not all tracked."+ )+++_KNOWN = (+ "tests/test_top.py",+ "tests/unit/test_a.py",+ "tests/unit/sub/test_b.py",+ "other/test_c.py",+)+++ ("path", "expected"),+ [+ ("tests/__init__.py", _KNOWN[:3]),+ ("tests/unit/__init__.py", _KNOWN[1:3]),+ ],+)[email protected]("deleted", [False, True])+def test_a_changed_test_package_init_selects_every_test_under_it(path, expected, deleted) -> None:+ changed, gone = ([], [path]) if deleted else ([path], [])+ tiers = _tiers(inferred=[_inferred(path, path, "changed-test")])+ sel = _select(changed, tiers, deleted=gone, known_tests=_KNOWN)+ assert not sel.run_all, sel.reasons+ assert sel.tests == expected+ assert sel.basis[path] == "test-package"+++def test_a_route_through_a_test_package_init_selects_the_tests_under_it() -> None:+ tiers = _tiers(+ inferred=[+ _inferred("src/a.py", "tests/unit/__init__.py", "import-graph"),+ _inferred("src/a.py", "other/test_c.py", "import-graph"),+ ]+ )+ sel = _select(["src/a.py"], tiers, known_tests=_KNOWN)+ assert not sel.run_all, sel.reasons+ assert sel.tests == ("other/test_c.py", "tests/unit/test_a.py", "tests/unit/sub/test_b.py")+++def test_a_route_through_another_helper_still_runs_everything() -> None:+ tiers = _tiers(+ inferred=[+ _inferred("src/a.py", "tests/unit/__init__.py", "import-graph"),+ _inferred("src/a.py", "tests/unit/helpers.py", "import-graph"),+ ]+ )+ sel = _select(["src/a.py"], tiers, known_tests=_KNOWN)+ assert sel.run_all+ assert "reached through the test helper tests/unit/helpers.py" in sel.reasons[0]+++def test_a_file_whose_only_test_this_change_deletes_runs_everything() -> None:+ tiers = _tiers(inferred=[_inferred("src/a.py", "tests/test_a.py", "call-graph")])+ sel = _select(["src/a.py"], tiers, deleted=["tests/test_a.py"], missing=["tests/test_a.py"])+ assert sel.run_all+ assert "src/a.py: its only known tests are not in the checkout." in sel.reasons+++def test_a_test_the_checkout_lacks_means_the_index_is_stale() -> None:+ tiers = _tiers(+ inferred=[+ _inferred("src/a.py", "tests/test_a.py", "call-graph"),+ _inferred("src/a.py", "tests/test_gone.py", "import-graph"),+ ]+ )+ sel = _select(["src/a.py"], tiers, missing=["tests/test_gone.py"])+ assert sel.run_all+ assert sel.reasons[0].startswith("tests/test_gone.py is a test the index names")+++def test_a_file_reached_only_through_a_test_helper_runs_everything() -> None:+ tiers = _tiers(inferred=[_inferred("src/a.py", "tests/factories/user.py", "import-graph")])+ sel = _select(["src/a.py"], tiers)+ assert sel.run_all+ assert sel.reasons[0].startswith(+ "src/a.py is reached through the test helper tests/factories/user.py, and no test "+ )+++def test_any_route_through_a_test_helper_runs_everything() -> None:+ """A real test reaching the file does not vouch for the helper's other users."""+ tiers = _tiers(+ inferred=[+ _inferred("src/a.py", "tests/test_a.py", "call-graph"),+ _inferred("src/a.py", "tests/helpers.py", "import-graph"),+ ]+ )+ sel = _select(["src/a.py"], tiers)+ assert sel.run_all+ assert "src/a.py is reached through the test helper tests/helpers.py, and no test" in sel.reasons[0]+++def test_coverage_does_not_hide_a_helper_route() -> None:+ tiers = _tiers(+ covered={+ "tests/test_a.py::t|run": {"test_file": "tests/test_a.py", "source_files": ["src/a.py"]}+ },+ inferred=[_inferred("src/a.py", "tests/helpers.py", "import-graph")],+ )+ assert _select(["src/a.py"], tiers).run_all+++ ("kwargs", "start"),+ [+ ({"graph_error": "OperationalError: locked"}, "The graph could not be read"),+ ({"map_truncated": True}, "The per-test map is at its stored row cap"),+ ({"index_problem": "The index records two commits"}, "The index records two commits"),+ ({"index_gap": None}, "Cannot tell what changed since the index was built"),+ ],+)+def test_an_index_that_cannot_be_trusted_runs_everything(kwargs, start) -> None:+ tiers = _tiers(inferred=[_inferred("src/a.py", "tests/test_a.py", "call-graph")])+ sel = _select(["src/a.py"], tiers, **kwargs)+ assert sel.run_all+ assert any(r.startswith(start) for r in sel.reasons), sel.reasons+++def test_an_index_built_before_other_files_changed_runs_everything() -> None:+ tiers = _tiers(inferred=[_inferred("src/a.py", "tests/test_a.py", "call-graph")])+ assert _select(["src/a.py"], tiers, index_gap=["README.md"]).run_all is False+ stale = _select(["src/a.py"], tiers, index_gap=["README.md", "src/b.py"])+ assert stale.run_all+ assert "The index predates 1 changed file(s) outside this change (e.g. src/b.py)" in (+ stale.reasons[0]+ )+ unknown = _select(["src/a.py"], tiers, index_gap=None)+ assert unknown.run_all+ assert unknown.reasons[0].startswith("Cannot tell what changed since the index was built")+++# -- the subset ---------------------------------------------------------------+++def test_the_subset_is_covering_ids_and_inferred_files() -> None:+ tiers = _tiers(+ covered={+ "tests/test_a.py::test_one|run": {+ "test_file": "tests/test_a.py",+ "source_files": ["src/a.py"],+ },+ "tests/test_a.py::test_one|setup": {+ "test_file": "tests/test_a.py",+ "source_files": ["src/a.py"],+ },+ },+ inferred=[+ _inferred("src/b.py", "tests/test_b.py", "call-graph"),+ _inferred("tests/test_c.py", "tests/test_c.py", "changed-test"),+ ],+ )+ sel = _select(["src/a.py", "src/b.py", "tests/test_c.py", "docs/guide.md"], tiers)+ assert not sel.run_all+ # Phases collapse to one node id.+ assert sel.tests == ("tests/test_a.py::test_one", "tests/test_b.py", "tests/test_c.py")+ assert sel.test_files == ("tests/test_a.py", "tests/test_b.py", "tests/test_c.py")+ assert sel.skipped_files == ("docs/guide.md",)+ assert sel.basis == {+ "docs/guide.md": "no-tests-needed",+ "src/a.py": "coverage",+ "src/b.py": "call-graph",+ "tests/test_c.py": "changed-test",+ }+ assert "1 changed file(s) are documentation: no tests needed." in sel.reasons+++def test_a_node_id_is_rebased_on_the_resolved_test_file() -> None:+ # The runner ran from a package directory; the map resolved its file.+ tiers = _tiers(+ covered={"tests/test_a.py::T::test_x[1]|run": {+ "test_file": "pkg/tests/test_a.py", "source_files": ["pkg/a.py"]+ }}+ )+ assert _select(["pkg/a.py"], tiers).tests == ("pkg/tests/test_a.py::T::test_x[1]",)+++def test_a_node_id_inside_a_whole_selected_file_is_dropped() -> None:+ tiers = _tiers(+ covered={"tests/test_a.py::test_one|run": {+ "test_file": "tests/test_a.py", "source_files": ["src/a.py"]+ }},+ inferred=[_inferred("src/b.py", "tests/test_a.py", "import-graph")],+ )+ assert _select(["src/a.py", "src/b.py"], tiers).tests == ("tests/test_a.py",)+++def test_coverage_naming_a_test_without_a_file_runs_everything() -> None:+ tiers = _tiers(covered={"suite-label": {"test_file": None, "source_files": ["src/a.py"]}})+ sel = _select(["src/a.py"], tiers)+ assert sel.run_all+ assert sel.reasons == ("Coverage names suite-label for src/a.py, but not its file.",)+++def test_always_run_is_appended_and_kept_on_a_full_run() -> None:+ config = TestSelectionConfig(always_run=("tests/test_smoke.py",))+ tiers = _tiers(inferred=[_inferred("src/b.py", "tests/test_b.py", "call-graph")])+ sel = _select(["src/b.py"], tiers, config=config)+ assert runner_args(sel, "pytest") == ["tests/test_b.py", "tests/test_smoke.py"]+ full = _select(["uv.lock"], config=config)+ assert full.to_dict()["always_run"] == ["tests/test_smoke.py"]+ assert runner_args(full, "pytest") == [RUN_ALL]+++def test_a_stale_map_is_stated() -> None:+ tiers = _tiers(+ covered={"t::x": {"test_file": "tests/test_a.py", "source_files": ["src/a.py"]}}+ )+ sel = _select(["src/a.py"], tiers, map_current=False)+ assert not sel.run_all+ assert sel.reasons == (+ "The per-test map was measured at another commit, so covering tests are matched "+ "by file, not by changed line.",+ )+++# -- config -------------------------------------------------------------------+++def test_config_reads_the_tests_block() -> None:+ cfg = TestSelectionConfig.from_repo_config(+ {"tests": {"full_run_on": ["schema/**"], "always_run": [" tests/test_smoke.py "]}}+ )+ assert cfg == TestSelectionConfig(("schema/**",), ("tests/test_smoke.py",))+ assert TestSelectionConfig.from_repo_config({}) == TestSelectionConfig()+++ ("block", "message"),+ [+ ("all", "tests must be a mapping"),+ ({"full_run_on": "schema/**"}, "tests.full_run_on must be a list of non-empty strings"),+ ({"always_run": ["ok", ""]}, "tests.always_run must be a list of non-empty strings"),+ ({"full_run": ["x"]}, "tests.full_run is not a setting"),+ ],+)+def test_config_refuses_what_it_cannot_use(block, message) -> None:+ with pytest.raises(ValueError, match=message):+ TestSelectionConfig.from_repo_config({"tests": block})+++# -- runner arguments ---------------------------------------------------------+++def _subset(tests=(), files=(), always=()):+ return Selection(run_all=False, reasons=(), tests=tests, test_files=files, always_run=always)+++def test_pytest_gets_node_ids_and_files() -> None:+ sel = _subset(+ tests=("tests/test_a.py::test_x[a b]", "tests/test_b.py", "web/a.test.ts"),+ files=("tests/test_a.py", "tests/test_b.py", "web/a.test.ts"),+ )+ args = runner_args(sel, "pytest")+ assert args == ["tests/test_a.py::test_x[a b]", "tests/test_b.py"]+ # Quoted for a shell: the space inside the parameter id stays one argument.+ assert format_args(args) == "'tests/test_a.py::test_x[a b]' tests/test_b.py"+++def test_go_gets_each_package_directory_once() -> None:+ sel = _subset(files=("a_test.go", "pkg/x/x_test.go", "pkg/x/y_test.go", "tests/test_a.py"))+ assert runner_args(sel, "go") == [".", "./pkg/x"]+++def test_go_runs_the_package_of_every_changed_go_file_with_tests() -> None:+ """Same-package tests import nothing, so the graph alone can miss them."""+ tiers = _tiers(+ inferred=[+ _inferred("pkg/x/x.go", "cmd/main_test.go", "call-graph"),+ _inferred("pkg/y/y.go", "cmd/main_test.go", "call-graph"),+ ]+ )+ sel = _select(["pkg/x/x.go", "pkg/y/y.go"], tiers, go_test_dirs={"pkg/x", "cmd"})+ assert sel.packages == ("pkg/x",)+ assert runner_args(sel, "go") == ["./cmd", "./pkg/x"]+++def test_jest_and_files_get_paths() -> None:+ sel = _subset(files=("web/a.test.ts", "web/b.spec.jsx", "tests/test_a.py"))+ assert runner_args(sel, "jest") == ["web/a.test.ts", "web/b.spec.jsx"]+ assert runner_args(sel, "files") == ["web/a.test.ts", "web/b.spec.jsx", "tests/test_a.py"]+++ ("files", "runner"),+ [+ (("tests/test_a.py",), "pytest"),+ (("a_test.go", "pkg/b_test.go"), "go"),+ (("web/a.test.ts", "web/b.test.js"), "jest"),+ (("tests/test_a.py", "a_test.go"), "files"),+ ((), "files"),+ ],+)+def test_auto_picks_the_runner_every_selected_file_belongs_to(files, runner) -> None:+ assert resolve_runner(_subset(files=files), "auto") == runner+ assert resolve_runner(_subset(files=files), "jest") == "jest"+++def test_a_full_run_prints_only_the_sentinel() -> None:+ full = Selection(run_all=True, reasons=("uv.lock changed",), test_files=("a_test.go",))+ for runner in ("pytest", "go", "jest", "files"):+ assert format_args(runner_args(full, runner)) == ":all"+++ ("path", "expected"),+ [+ ("conftest.py", _KNOWN),+ ("tests/conftest.py", _KNOWN[:3]),+ ("tests/unit/conftest.py", _KNOWN[1:3]),+ ],+)[email protected]("deleted", [False, True])+def test_a_changed_conftest_selects_every_test_at_or_below_it(path, expected, deleted) -> None:+ changed, gone = ([], [path]) if deleted else ([path], [])+ sel = _select(changed, _tiers(), deleted=gone, known_tests=_KNOWN)+ assert not sel.run_all, sel.reasons+ assert sel.tests == expected+ assert sel.basis[path] == "conftest"+++def test_a_route_through_a_conftest_selects_the_tests_under_it() -> None:+ tiers = _tiers(+ inferred=[+ _inferred("src/a.py", "tests/unit/conftest.py", "import-graph"),+ _inferred("src/a.py", "other/test_c.py", "call-graph"),+ ]+ )+ sel = _select(["src/a.py"], tiers, known_tests=_KNOWN)+ assert not sel.run_all, sel.reasons+ assert sel.tests == ("other/test_c.py", "tests/unit/test_a.py", "tests/unit/sub/test_b.py")+++def test_a_route_through_an_imported_helper_selects_its_importers() -> None:+ tiers = _tiers(+ inferred=[+ _inferred("src/a.py", "tests/helpers.py", "import-graph"),+ _inferred("src/a.py", "tests/test_x.py", "import-graph"),+ ]+ )+ tiers["helper_importers"] = {"tests/helpers.py": ["tests/test_x.py"]}+ sel = _select(["src/a.py"], tiers)+ assert not sel.run_all, sel.reasons+ assert sel.tests == ("tests/test_x.py",)++[email protected]("deleted", [False, True])+def test_a_changed_helper_selects_the_tests_that_import_it(deleted) -> None:+ path = "tests/helpers.py"+ changed, gone = ([], [path]) if deleted else ([path], [])+ tiers = _tiers(+ inferred=[+ _inferred(path, path, "changed-test"),+ _inferred(path, "tests/test_x.py", "import-graph"),+ _inferred(path, "tests/test_y.py", "import-graph"),+ ]+ )+ tiers["helper_importers"] = {path: ["tests/test_x.py"], "tests/test_x.py": ["tests/test_y.py"]}+ sel = _select(changed, tiers, deleted=gone)+ assert not sel.run_all, sel.reasons+ assert sel.tests == ("tests/test_x.py", "tests/test_y.py")+ assert sel.basis[path] == "helper-importers"+++# -- what the graph cannot see ------------------------------------------------+++def test_a_doc_some_code_names_runs_everything() -> None:+ readers = {"docs/agent/TOOLS.md": "tests/unit/test_tools.py"}+ sel = _select(["docs/agent/TOOLS.md", "docs/guide.md"], doc_readers=readers)+ assert sel.run_all+ assert sel.reasons[0] == (+ "docs/agent/TOOLS.md is named by tests/unit/test_tools.py, so a test may read it; "+ "the tests that do are not tracked."+ )+ assert sel.basis == {"docs/agent/TOOLS.md": "full-run", "docs/guide.md": "no-tests-needed"}+++def test_doc_readers_are_code_naming_the_doc_or_a_doctest_glob() -> None:+ docs = ["README.md", "docs/guide.md"]+ sources = [+ ("pyproject.toml", 'readme = "README.md"\n'),+ ("src/help.py", 'HINT = "use --doctest-glob"\n'),+ ("tests/test_readme.py", 'ROOT / "README.md"\n'),+ ]+ assert doc_readers(docs, sources) == {"README.md": "tests/test_readme.py"}+ glob = [("pytest.ini", "[pytest]\naddopts = --doctest-glob='*.md'\n")]+ assert doc_readers(docs, glob) == {"README.md": "pytest.ini", "docs/guide.md": "pytest.ini"}+++ ("path", "text", "loads"),+ [+ ("tests/conftest.py", 'pytest_plugins = ["tests.plugins.db"]\n', True),+ ("pyproject.toml", '[tool.pytest.ini_options]\naddopts = "-p tests.plugin"\n', True),+ ("pytest.ini", "[pytest]\naddopts = -p no:cacheprovider -v\n", False),+ ("tests/test_a.py", 'pytest_plugins = ["x"]\n', False),+ ],+)+def test_plugin_loader_finds_plugins_loaded_by_name(path, text, loads) -> None:+ assert (plugin_loader([(path, text)]) == path) is loads+++def test_a_helper_is_unknown_while_plugins_are_loaded_by_name() -> None:+ """A plugin's fixtures reach tests that never import it."""+ path = "tests/plugins/db.py"+ tiers = _tiers(+ inferred=[+ _inferred(path, path, "changed-test"),+ _inferred(path, "tests/test_x.py", "import-graph"),+ ]+ )+ tiers["helper_importers"] = {path: ["tests/test_x.py"]}+ assert not _select([path], tiers).run_all+ sel = _select([path], tiers, plugin_loader="tests/conftest.py")+ assert sel.run_all+ assert "tests/conftest.py loads pytest plugins by name" in sel.reasons[0]+ route = _tiers(+ inferred=[+ _inferred("src/a.py", path, "import-graph"),+ _inferred("src/a.py", "tests/test_x.py", "import-graph"),+ ]+ )+ route["helper_importers"] = {path: ["tests/test_x.py"]}+ reached = _select(["src/a.py"], route, plugin_loader="tests/conftest.py")+ assert reached.run_all+ assert reached.reasons[0].startswith("src/a.py is reached through a test helper:")+++def test_a_test_the_graph_cannot_see_into_runs_with_every_subset() -> None:+ tiers = _tiers(inferred=[_inferred("src/a.py", "tests/test_a.py", "import-graph")])+ sel = _select(["src/a.py"], tiers, unplaced_tests=["tests/test_cli.py"])+ assert not sel.run_all+ assert sel.tests == ("tests/test_a.py", "tests/test_cli.py")+ assert (+ "1 test file(s) the graph cannot see into run with every selection "+ "(e.g. tests/test_cli.py)." in sel.reasons+ )+ # Documentation alone still needs no test.+ assert _select(["docs/guide.md"], unplaced_tests=["tests/test_cli.py"]).tests == ()+++def test_pytest_is_not_given_production_modules_outside_testpaths() -> None:+ """``core/test_paths.py`` is test-shaped, but a bare pytest never collects it."""+ tests = ("tests/test_a.py", "src/pkg/test_paths.py", "src/pkg/tests/test_b.py")+ sel = Selection(run_all=False, reasons=(), tests=tests, pytest_testpaths=("tests",))+ assert runner_args(sel, "pytest") == ["tests/test_a.py", "src/pkg/tests/test_b.py"]+ assert runner_args(Selection(run_all=False, reasons=(), tests=tests), "pytest") == list(tests)+++ ("files", "expected"),+ [+ (+ {"pyproject.toml": '[tool.pytest.ini_options]\ntestpaths = ["tests", "./it/"]\n'},+ ("tests", "it"),+ ),+ (+ {"setup.cfg": "[tool:pytest]\ntestpaths = tests\n integration\n"},+ ("tests", "integration"),+ ),+ # pytest.ini wins even with no section, over a pyproject that has one.+ (+ {"pytest.ini": "", "pyproject.toml": '[tool.pytest.ini_options]\ntestpaths = ["t"]\n'},+ (),+ ),+ ({"pyproject.toml": "not toml ["}, ()),+ ({}, ()),+ ],+)+def test_pytest_testpaths_reads_the_config_pytest_reads(files, expected) -> None:+ assert pytest_testpaths(files.get) == expecteddiff --git a/tests/unit/cli/test_impacted_tests_cmd.py b/tests/unit/cli/test_impacted_tests_cmd.pynew file mode 100644index 000000000..574d3700c--- /dev/null+++ b/tests/unit/cli/test_impacted_tests_cmd.py@@ -0,0 +1,282 @@+"""``repowise impacted-tests --format args|json``: selection against a real repo and index."""++from __future__ import annotations++import asyncio+import inspect+import json+import subprocess+from pathlib import Path++import pytest+from click.testing import CliRunner+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++from repowise.cli.main import cli+from repowise.core.ci.base import CI_BASE_VARS, CI_ENV_VARS+++def _git(cwd, *args: str) -> str:+ return subprocess.run(+ ["git", *args], cwd=cwd, check=True, capture_output=True, text=True+ ).stdout.strip()+++def _write(root: Path, files: dict[str, str]) -> None:+ for rel, text in files.items():+ (root / rel).parent.mkdir(parents=True, exist_ok=True)+ (root / rel).write_text(text, encoding="utf-8")+++async def _index(root: Path, head_commit: str) -> None:+ """A wiki.db whose graph has tests/test_a.py importing src/a.py."""+ from repowise.cli.helpers import resolve_command_target+ from repowise.core.persistence.database import init_db+ from repowise.core.persistence.models import GraphEdge, GraphNode, Repository++ db = root / ".repowise" / "wiki.db"+ db.parent.mkdir(parents=True, exist_ok=True)+ engine = create_async_engine(f"sqlite+aiosqlite:///{db.as_posix()}")+ await init_db(engine)+ local_path = str(resolve_command_target(path=str(root)).repo_path)+ async with async_sessionmaker(engine, expire_on_commit=False)() as session:+ session.add(Repository(id="r1", name="r", local_path=local_path, head_commit=head_commit))+ for path, is_test in (("src/a.py", False), ("src/b.py", False), ("tests/test_a.py", True)):+ node = GraphNode(repository_id="r1", node_id=path, node_type="file", is_test=is_test)+ session.add(node)+ session.add(+ GraphEdge(+ repository_id="r1",+ source_node_id="tests/test_a.py",+ target_node_id="src/a.py",+ edge_type="imports",+ )+ )+ await session.commit()+ await engine.dispose()+++def repo(tmp_path):+ """``main`` holds the code and an index built there; ``feat`` edits src/a.py and a doc."""+ _git(tmp_path, "init", "-q", "-b", "main")+ _git(tmp_path, "config", "user.email", "[email protected]")+ _git(tmp_path, "config", "user.name", "t")+ _write(+ tmp_path,+ {+ "src/a.py": "A = 1\n",+ "src/b.py": "B = 1\n",+ "tests/test_a.py": "from src.a import A\n\ndef test_a():\n assert A\n",+ "README.md": "docs\n",+ ".gitignore": ".repowise/\n",+ },+ )+ _git(tmp_path, "add", "-A")+ _git(tmp_path, "commit", "-qm", "init")+ asyncio.run(_index(tmp_path, _git(tmp_path, "rev-parse", "HEAD")))+ _git(tmp_path, "switch", "-qc", "feat")+ _write(tmp_path, {"src/a.py": "A = 2\n", "README.md": "more docs\n"})+ _git(tmp_path, "commit", "-qam", "feat")+ return tmp_path+++def _run(repo, *args: str, env: dict[str, str] | None = None):+ # The host CI's own variables must not pick the change.+ env = {**dict.fromkeys((*CI_ENV_VARS, *CI_BASE_VARS), ""), **(env or {})}+ # Separate streams: click 8.1 mixes stderr into stdout unless told not to.+ split = "mix_stderr" in inspect.signature(CliRunner.__init__).parameters+ runner = CliRunner(env=env, mix_stderr=False) if split else CliRunner(env=env)+ return runner.invoke(cli, ["impacted-tests", "--path", str(repo), *args])+++def _err(result) -> str:+ """Stderr with rich's line wrapping undone."""+ return " ".join(result.stderr.split())+++def test_args_prints_the_subset_on_one_line(repo) -> None:+ result = _run(repo, "main...feat", "--format", "args")+ assert result.exit_code == 0, result.output+ assert result.stdout == "tests/test_a.py\n"+ assert "1 argument(s) for pytest." in _err(result)+ assert "documentation: no tests needed" in _err(result)+++def test_json_adds_the_selection_to_the_report(repo) -> None:+ result = _run(repo, "main...feat", "--format", "json", "--runner", "files")+ assert result.exit_code == 0, result.output+ data = json.loads(result.stdout)+ assert data["inferred_tests"] == [+ {"source_file": "src/a.py", "test_file": "tests/test_a.py", "via": "import-graph"}+ ]+ assert data["run_all"] is False+ assert data["runner"] == "files" and data["args"] == ["tests/test_a.py"]+ assert data["selected"]["skipped_files"] == ["README.md"]+ assert data["selected"]["basis"] == {"README.md": "no-tests-needed", "src/a.py": "import-graph"}+++def test_a_lockfile_change_runs_everything_and_says_why(repo) -> None:+ _write(repo, {"uv.lock": "lock\n"})+ _git(repo, "add", "-A")+ _git(repo, "commit", "-qm", "deps")+ result = _run(repo, "main...feat", "--format", "args")+ assert result.exit_code == 0, result.output+ assert result.stdout == ":all\n"+ assert "uv.lock changed: dependencies can change any test." in _err(result)+++def test_a_new_untested_file_runs_everything(repo) -> None:+ _write(repo, {"src/c.py": "C = 1\n"})+ _git(repo, "add", "-A")+ _git(repo, "commit", "-qm", "new")+ result = _run(repo, "main...feat", "--format", "json")+ data = json.loads(result.stdout)+ assert data["run_all"] is True and data["args"] == [":all"]+ assert data["reasons"][0].startswith("src/c.py: no coverage")+++def test_no_index_runs_everything(repo) -> None:+ (repo / ".repowise" / "wiki.db").unlink()+ result = _run(repo, "main...feat", "--format", "args")+ assert result.exit_code == 0, result.output+ assert result.stdout == ":all\n"+ assert "No index" in _err(result)+++def test_an_index_behind_the_base_runs_everything(repo) -> None:+ # main moves past the indexed commit, and the branch is rebased onto it.+ _git(repo, "switch", "-q", "main")+ _write(repo, {"src/b.py": "B = 2\n"})+ _git(repo, "commit", "-qam", "main moves")+ _git(repo, "switch", "-q", "feat")+ _git(repo, "rebase", "-q", "main")+ result = _run(repo, "main...feat", "--format", "args")+ assert result.stdout == ":all\n"+ assert "The index predates 1 changed file(s) outside this change (e.g. src/b.py)" in (+ _err(result)+ )+++def test_in_ci_the_default_change_is_the_pull_requests(repo) -> None:+ # Nothing is staged, so the local default would select nothing at all.+ result = _run(repo, "--format", "args", env={"CI": "true"})+ assert result.exit_code == 0, result.output+ assert result.stdout == "tests/test_a.py\n"+ # Locally the default is the staged changes, and nothing is staged: that is+ # no change to select from, never "no tests needed".+ local = _run(repo, "--format", "args")+ assert local.stdout == ":all\n"+ assert "No change against staged changes; nothing to select from." in _err(local)+++def test_a_bad_config_cannot_evaluate(repo) -> None:+ _write(repo, {".repowise/config.yaml": "tests:\n full_run_on: schema/**\n"})+ result = _run(repo, "main...feat", "--format", "json")+ assert result.exit_code == 2+ data = json.loads(result.stdout)+ assert data["error"] == "config_invalid"+ assert data["message"].startswith("tests.full_run_on must be a list")+ args = _run(repo, "main...feat", "--format", "args")+ assert args.exit_code == 2 and args.stdout == ""+++def test_config_extends_the_full_run_triggers(repo) -> None:+ _write(repo, {".repowise/config.yaml": "tests:\n full_run_on: ['README.md']\n"})+ result = _run(repo, "main...feat", "--format", "args")+ assert result.stdout == ":all\n"+ assert "README.md changed: it matches tests.full_run_on." in _err(result)+++def test_an_unknown_revision_cannot_evaluate(repo) -> None:+ result = _run(repo, "nope...feat", "--format", "args")+ assert result.exit_code == 2+ assert result.stdout == ""+++def test_json_reports_the_indexed_commit_and_map_state(repo) -> None:+ data = json.loads(_run(repo, "main...feat", "--format", "json").stdout)+ assert data["indexed_commit"] == _git(repo, "rev-parse", "main")+ assert data["map_current"] is True+++def test_list_prints_one_test_per_line(repo) -> None:+ result = _run(repo, "main...feat", "--format", "list")+ assert result.exit_code == 0, result.output+ assert result.stdout == "tests/test_a.py\n"+++def test_an_index_that_disagrees_about_its_commit_runs_everything(repo) -> None:+ (repo / ".repowise" / "state.json").write_text(+ json.dumps({"last_sync_commit": _git(repo, "rev-parse", "feat")}), encoding="utf-8"+ )+ result = _run(repo, "main...feat", "--format", "args")+ assert result.stdout == ":all\n"+ assert "The index records two commits" in _err(result)+++def test_a_graph_that_cannot_be_read_runs_everything(repo, monkeypatch) -> None:+ from repowise.cli.commands import impacted_tests_cmd++ async def _broken(*_a, **_k):+ raise RuntimeError("edge table locked")++ monkeypatch.setattr(impacted_tests_cmd, "_graph_candidates", _broken)+ result = _run(repo, "main...feat", "--format", "args")+ assert result.stdout == ":all\n"+ assert "The graph could not be read (RuntimeError: edge table locked)" in _err(result)+++def test_a_changed_file_in_the_test_tree_that_is_not_a_test_runs_everything(repo) -> None:+ _write(repo, {"tests/data/users.json": "[]\n"})+ _git(repo, "add", "-A")+ _git(repo, "commit", "-qm", "data")+ result = _run(repo, "main...feat", "--format", "args")+ assert result.stdout == ":all\n"+ assert "tests/data/users.json is in a test tree but is not code" in _err(result)+++def _land_on_main(repo, files: dict[str, str]) -> None:+ """Commit *files* on main, re-index there, and rebase the change onto it."""+ _git(repo, "switch", "-q", "main")+ _write(repo, files)+ _git(repo, "add", "-A")+ _git(repo, "commit", "-qm", "main moves")+ (repo / ".repowise" / "wiki.db").unlink()+ asyncio.run(_index(repo, _git(repo, "rev-parse", "HEAD")))+ _git(repo, "switch", "-q", "feat")+ _git(repo, "rebase", "-q", "main")+++def test_a_doc_a_test_reads_runs_everything(repo) -> None:+ _land_on_main(repo, {"tests/test_readme.py": 'README = "README.md"\n'})+ result = _run(repo, "main...feat", "--format", "args")+ assert result.stdout == ":all\n"+ assert "README.md is named by tests/test_readme.py, so a test may read it" in _err(result)+++def test_tests_the_graph_cannot_see_run_and_production_modules_do_not(repo) -> None:+ # Neither file is in the index; src/test_util.py is outside testpaths.+ _land_on_main(+ repo,+ {+ "tests/test_cli.py": "def test_cli():\n pass\n",+ "src/test_util.py": "def helper():\n pass\n",+ "pytest.ini": "[pytest]\ntestpaths = tests\n",+ },+ )+ result = _run(repo, "main...feat", "--format", "args", "--runner", "pytest")+ assert result.exit_code == 0, result.output+ assert result.stdout == "tests/test_a.py tests/test_cli.py\n"+ assert "2 test file(s) the graph cannot see into" in _err(result)+++def test_a_changed_test_package_init_selects_the_tests_under_it(repo) -> None:+ _write(repo, {"tests/__init__.py": "# package\n"})+ _git(repo, "add", "-A")+ _git(repo, "commit", "-qm", "tests package")+ result = _run(repo, "main...feat", "--format", "json")+ data = json.loads(result.stdout)+ assert data["run_all"] is False, data["reasons"]+ assert data["selected"]["basis"]["tests/__init__.py"] == "test-package"+ assert data["args"] == ["tests/test_a.py"]diff --git a/tests/unit/persistence/test_impacted_tests_resolution.py b/tests/unit/persistence/test_impacted_tests_resolution.pyindex aefa8eb32..b91a1efc7 100644--- a/tests/unit/persistence/test_impacted_tests_resolution.py+++ b/tests/unit/persistence/test_impacted_tests_resolution.py@@ -166,3 +166,150 @@ async def test_a_changed_test_file_is_its_own_candidate(async_session) -> None:}]assert out["unknown"] == []+++async def _graph(session, repo_id, tests: set[str], files: set[str], imports: list[tuple]):+ """File nodes (tests flagged) and ``imports`` edges ``(importer, imported)``."""+ from repowise.core.persistence.models import GraphEdge, GraphNode++ for path in sorted(tests | files):+ session.add(+ GraphNode(repository_id=repo_id, node_id=path, node_type="file", is_test=path in tests)+ )+ for source, target in imports:+ session.add(+ GraphEdge(+ repository_id=repo_id,+ source_node_id=source,+ target_node_id=target,+ edge_type="imports",+ )+ )+ await session.commit()+++def _pairs(out: dict, source: str) -> dict[str, str]:+ return {g["test_file"]: g["via"] for g in out["inferred"] if g["source_file"] == source}+++async def test_the_import_graph_reaches_tests_through_modules_and_other_tests(+ async_session,+) -> None:+ """A test two imports away, and one importing a test that reaches it, still run it."""+ repo = await insert_repo(async_session)+ await _graph(+ async_session,+ repo.id,+ tests={"tests/test_api.py", "tests/base.py", "tests/test_child.py"},+ files={"src/api.py", "src/core.py"},+ imports=[+ ("src/api.py", "src/core.py"),+ ("tests/test_api.py", "src/api.py"),+ ("tests/base.py", "src/core.py"),+ ("tests/test_child.py", "tests/base.py"),+ ],+ )++ out = _empty_result(1)+ await _resolve_impacted(async_session, repo.id, {"src/core.py": {1}}, set(), out)++ assert _pairs(out, "src/core.py") == {+ "tests/base.py": "import-graph",+ "tests/test_api.py": "import-graph",+ "tests/test_child.py": "import-graph",+ }+ assert out["unknown"] == []+++async def test_graph_candidates_are_not_capped(async_session) -> None:+ from repowise.core.analysis.test_reachability import MAX_TESTS_PER_TARGET++ repo = await insert_repo(async_session)+ tests = {f"tests/test_{i:03}.py" for i in range(MAX_TESTS_PER_TARGET + 5)}+ await _graph(+ async_session, repo.id, tests, {"src/hub.py"}, [(t, "src/hub.py") for t in tests]+ )++ out = _empty_result(1)+ await _resolve_impacted(async_session, repo.id, {"src/hub.py": {1}}, set(), out)+ assert set(_pairs(out, "src/hub.py")) == tests+++async def test_a_file_level_lookup_also_asks_the_graph(async_session) -> None:+ """Matched by file (a deleted file, a stale map), coverage alone is not enough."""+ repo = await _seed(async_session)+ await _graph(+ async_session,+ repo.id,+ tests={"tests/test_other.py"},+ files={"src/foo.py"},+ imports=[("tests/test_other.py", "src/foo.py")],+ )++ out = _empty_result(1)+ await _resolve_impacted(async_session, repo.id, {"src/foo.py": None}, _REPO_KEYS, out)++ assert set(out["covered"]) == {+ "tests/test_foo.py::test_a|run",+ "tests/test_foo.py::test_b|run",+ }+ assert _pairs(out, "src/foo.py") == {"tests/test_other.py": "import-graph"}+ assert out["unknown"] == []+++async def test_coverage_adds_to_the_graph_and_never_replaces_it(async_session) -> None:+ """A test the coverage run missed still runs when the graph shows it reaching the file."""+ repo = await _seed(async_session)+ await _graph(+ async_session,+ repo.id,+ tests={"tests/test_other.py"},+ files={"src/foo.py"},+ imports=[("tests/test_other.py", "src/foo.py")],+ )++ out = _empty_result(1)+ await _resolve_impacted(async_session, repo.id, {"src/foo.py": {2}}, _REPO_KEYS, out)++ assert set(out["covered"]) == {"tests/test_foo.py::test_a|run"}+ assert _pairs(out, "src/foo.py") == {"tests/test_other.py": "import-graph"}+++async def test_a_graph_read_failure_is_reported_not_swallowed(async_session, monkeypatch) -> None:+ from repowise.cli.commands import impacted_tests_cmd++ async def _broken(*_a, **_k):+ raise RuntimeError("edge table locked")++ monkeypatch.setattr(impacted_tests_cmd, "_graph_candidates", _broken)+ repo = await insert_repo(async_session)+ out = _empty_result(1)+ await _resolve_impacted(async_session, repo.id, {"src/a.py": {1}}, set(), out)+ assert out["graph_error"] == "RuntimeError: edge table locked"+++async def test_data_files_are_not_routes_and_helper_importers_are_reported(+ async_session,+) -> None:+ """A JSON file flagged as test material is data; a helper's importers are listed."""+ repo = await insert_repo(async_session)+ await _graph(+ async_session,+ repo.id,+ tests={"tests/golden/out.json", "tests/helpers.py", "tests/test_a.py"},+ files={"src/a.py"},+ imports=[+ ("tests/golden/out.json", "src/a.py"),+ ("tests/helpers.py", "src/a.py"),+ ("tests/test_a.py", "tests/helpers.py"),+ ],+ )++ out = _empty_result(1)+ await _resolve_impacted(async_session, repo.id, {"src/a.py": {1}}, set(), out)++ assert _pairs(out, "src/a.py") == {+ "tests/helpers.py": "import-graph",+ "tests/test_a.py": "import-graph",+ }+ assert out["helper_importers"]["tests/helpers.py"] == ["tests/test_a.py"]diff --git a/tests/unit/test_ci.py b/tests/unit/test_ci.pyindex c731ffbc5..6505b3470 100644--- a/tests/unit/test_ci.py+++ b/tests/unit/test_ci.py@@ -74,3 +74,19 @@ def test_default_revspec_falls_back_to_remote_trunk(detached_repo) -> None:def test_default_revspec_raises_when_nothing_names_a_base(detached_repo) -> None:with pytest.raises(BaseNotFoundError):default_revspec(str(detached_repo), {})+++ ("env", "expected"),+ [+ ({"CI": "true"}, True),+ ({"GITHUB_BASE_REF": "main"}, True),+ ({"CI": "false"}, False),+ ({"CI": "", "GITHUB_BASE_REF": " "}, False),+ ({}, False),+ ],+)+def test_in_ci_reads_the_ci_variables(env, expected) -> None:+ from repowise.core.ci.base import in_ci++ assert in_ci(env) is expecteddiff --git a/tests/unit/test_ci_action.py b/tests/unit/test_ci_action.pyindex 776a52d83..2b04e74fa 100644--- a/tests/unit/test_ci_action.py+++ b/tests/unit/test_ci_action.py@@ -374,3 +374,179 @@ def test_no_check_selected_is_refused(tmp_path, fake_repowise) -> None:code, _, calls = _run(tmp_path, fake_repowise, CHECKS=" ")assert code == 2assert calls == ""+++# -- test selection -----------------------------------------------------------++SELECTOR = ROOT / "ci" / "github" / "impacted-tests.sh"+++def fake_selector(tmp_path: Path) -> Path:+ """A ``repowise`` that logs its arguments; ``update`` exits ``$FAKE_UPDATE``,+ anything else prints ``$FAKE_OUT`` and exits ``$FAKE_CODE``."""+ bin_dir = tmp_path / "bin"+ bin_dir.mkdir()+ fake = bin_dir / "repowise"+ fake.write_text(+ "#!/usr/bin/env bash\n"+ 'echo "$*" >> "$FAKE_LOG"\n'+ 'if [ "$1" = update ]; then exit "${FAKE_UPDATE:-0}"; fi\n'+ 'echo "why it chose" >&2\n'+ 'printf "%s\\n" "${FAKE_OUT-}"\n'+ 'exit "${FAKE_CODE:-0}"\n',+ encoding="utf-8",+ newline="\n",+ )+ fake.chmod(fake.stat().st_mode | stat.S_IEXEC)+ return bin_dir+++def _outputs(text: str) -> dict[str, str]:+ """``$GITHUB_OUTPUT`` parsed the way the runner does, delimiter form included."""+ out: dict[str, str] = {}+ lines = iter(text.splitlines())+ for line in lines:+ if "<<" in line:+ name, delim = line.split("<<", 1)+ out[name] = "\n".join(iter(lambda: next(lines), delim))+ else:+ name, value = line.split("=", 1)+ out[name] = value+ return out+++def test_the_selection_step_reads_only_what_the_action_passes() -> None:+ step = next(s for s in _action()["runs"]["steps"] if s.get("id") == "impacted")+ read = set(re.findall(r"\$\{?([A-Z][A-Z_]+)", SELECTOR.read_text(encoding="utf-8")))+ assert read - {"GITHUB_OUTPUT", "GITHUB_BASE_REF", "RANDOM"} <= set(step["env"])+ assert set(step["env"]) - {"PYTHONUTF8"} <= read+ assert step["if"] == "inputs.impacted-tests == 'true'"+ outputs = _action()["outputs"]+ assert outputs["impacted-tests"]["value"] == "${{ steps.impacted.outputs.impacted-tests }}"+ assert outputs["run-all-tests"]["value"] == "${{ steps.impacted.outputs.run-all-tests }}"+++def _select(+ tmp_path: Path, bin_dir: Path, *, cached: bool = False, **env: str+) -> tuple[int, dict[str, str], list[str]]:+ bash = _bash()+ if bash is None:+ pytest.skip("bash is not available")+ repo = tmp_path / "repo"+ repo.mkdir(exist_ok=True)+ subprocess.run(["git", "init", "-q"], cwd=repo, check=True)+ if cached:+ (repo / ".repowise").mkdir(exist_ok=True)+ (repo / ".repowise" / "state.json").write_text("{}", encoding="utf-8")+ out, log = tmp_path / "out", tmp_path / "log"+ full = {+ **os.environ,+ "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}",+ "GITHUB_OUTPUT": str(out),+ "GITHUB_BASE_REF": "",+ "FAKE_LOG": str(log),+ "BASE": "",+ "RUNNER": "auto",+ **env,+ }+ proc = subprocess.run([bash, str(SELECTOR)], cwd=repo, env=full, capture_output=True, text=True)+ calls = log.read_text(encoding="utf-8").splitlines() if log.exists() else []+ return proc.returncode, _outputs(out.read_text(encoding="utf-8")), calls+++def test_the_selection_step_passes_the_subset_on(tmp_path, fake_selector) -> None:+ code, outputs, calls = _select(+ tmp_path,+ fake_selector,+ BASE="origin/main...HEAD",+ RUNNER="pytest",+ FAKE_OUT="tests/test_a.py 'tests/test_b.py::test_x[a b]'",+ )+ assert code == 0+ assert calls == ["impacted-tests origin/main...HEAD --format args --runner pytest"]+ assert outputs == {+ "impacted-tests": "tests/test_a.py 'tests/test_b.py::test_x[a b]'",+ "run-all-tests": "false",+ }+++def test_the_selection_step_flags_a_full_run(tmp_path, fake_selector) -> None:+ code, outputs, calls = _select(tmp_path, fake_selector, FAKE_OUT=":all")+ assert code == 0+ # Without a base the CLI reads the pull request's target itself.+ assert calls == ["impacted-tests --format args --runner auto"]+ assert outputs == {"impacted-tests": ":all", "run-all-tests": "true"}+++ "env",+ [+ {"FAKE_OUT": "", "FAKE_CODE": "2"}, # could not evaluate+ {"FAKE_OUT": "tests/test_a.py\nrun-all-tests=false"}, # not one line+ ],+)+def test_a_selection_that_cannot_be_trusted_runs_every_test(tmp_path, fake_selector, env) -> None:+ code, outputs, _ = _select(tmp_path, fake_selector, **env)+ assert code == 0+ assert outputs == {"impacted-tests": ":all", "run-all-tests": "true"}+++def test_the_selection_step_updates_a_cached_index_first(tmp_path, fake_selector) -> None:+ code, outputs, calls = _select(tmp_path, fake_selector, cached=True, FAKE_OUT="t.py")+ assert code == 0+ assert calls == ["update --index-only", "impacted-tests --format args --runner auto"]+ assert outputs["run-all-tests"] == "false"+ failed, outputs, calls = _select(tmp_path, fake_selector, cached=True, FAKE_UPDATE="1")+ assert failed == 0+ assert calls[-1] == "update --index-only"+ assert outputs == {"impacted-tests": ":all", "run-all-tests": "true"}+++def _gitlab_select(tmp_path, bin_dir, *, cached: bool = False, **env) -> tuple[int, str, str]:+ if cached:+ (tmp_path / ".repowise").mkdir(exist_ok=True)+ (tmp_path / ".repowise" / "state.json").write_text("{}", encoding="utf-8")+ code = _run_gitlab_job(+ tmp_path, bin_dir, "repowise-impacted-tests", REPOWISE_IMPACTED_TESTS_RUNNER="go", **env+ )+ report = (tmp_path / "repowise-impacted-tests.env").read_text(encoding="utf-8")+ return code, report, (tmp_path / "impacted-tests.txt").read_text(encoding="utf-8")+++ ("out", "exit_code", "args", "run_all"),+ [+ ("./pkg/x", "0", "./pkg/x\n", "false"),+ (":all", "0", ":all\n", "true"),+ ("", "2", ":all\n", "true"), # could not evaluate+ ("./a\n./b", "0", ":all\n", "true"), # not one line+ ],+)+def test_the_gitlab_selection_job_fails_closed(+ tmp_path, fake_selector, out, exit_code, args, run_all+) -> None:+ job = _gitlab_jobs()["repowise-impacted-tests"]+ assert "allow_failure" not in job # it never fails: a failure means run everything+ assert job["artifacts"]["reports"]["dotenv"] == "repowise-impacted-tests.env"+ assert job["artifacts"]["paths"] == ["impacted-tests.txt"]+ assert "$REPOWISE_IMPACTED_TESTS" in job["rules"][0]["if"]+ code, report, written = _gitlab_select(+ tmp_path, fake_selector, FAKE_OUT=out, FAKE_CODE=exit_code+ )+ assert code == 0+ assert (tmp_path / "log").read_text(encoding="utf-8").strip() == (+ "impacted-tests origin/main...HEAD --format args --runner go"+ )+ # Only the flag travels as a variable; the arguments are an artifact.+ assert report == f"RUN_ALL_TESTS={run_all}\n"+ assert written == args+++def test_the_gitlab_job_runs_everything_when_the_cache_cannot_update(+ tmp_path, fake_selector+) -> None:+ code, report, written = _gitlab_select(tmp_path, fake_selector, cached=True, FAKE_UPDATE="1")+ assert code == 0+ assert report == "RUN_ALL_TESTS=true\n" and written == ":all\n"+ assert (tmp_path / "log").read_text(encoding="utf-8").strip() == "update --index-only"