Metadata-Version: 2.5
Name: pytest-regsmart
Version: 0.9.3
Summary: A Pytest plugin for faster fault detection via regression test prioritization and selection.
Project-URL: Homepage, https://github.com/leticosta4/pytest-regsmart
Author-email: leticosta4 <leticiacostaoa@gmail.com>
Maintainer-email: leticosta4 <leticiacostaoa@gmail.com>
License-Expression: GPL-2.0-or-later
License-File: LICENSE
License-File: NOTICE.md
Keywords: pytest,regression testing,software testing,test prioritization,test selection
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: Pytest
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Topic :: Software Development :: Testing
Requires-Python: >=3.11
Requires-Dist: gitpython>=3.2.0
Requires-Dist: numpy
Requires-Dist: pyan3>=2.8.0
Requires-Dist: pytest>=9.0.3
Description-Content-Type: text/markdown

# pytest-regsmart

A Pytest plugin that implements Regression Test Selection (RTS) and Regression Test Prioritization (RTP) for faster regression fault detection.

This [pytest](https://github.com/pytest-dev/pytest) plugin allows you to find regression test failures faster and receive testing feedback sooner from CI build.
When enabled with `--regsmart`, it first **selects** only the tests affected by the changes since the last baseline (RTS), then **prioritizes** them so that the tests that are faster or recently failed run earlier (RTP).

## Installation

```bash
uv pip install pytest-regsmart
```

Or using pip:

```bash
pip install pytest-regsmart
```

## Usage

Pytest will automatically find the plugin and use it when you run ``pytest``.
You can run `pytest-regsmart` with its default configuration, which selects only the affected tests and runs faster tests first, by passing the ``--regsmart`` option:

```bash
pytest --regsmart
```

Note that `--regsmart` requires the project to be a `git` repository (the regression test selection is computed from the changes since the base branch). Running it outside a git repo raises a `UsageError`.

The **base branch must be resolvable in the local clone** for the diff to be computed. `pytest-regsmart` always compares the current branch against the repository's default branch — `main`, or `master` if that is its name — never against the currently checked-out branch. The candidate refs are tried according to the **diff source** (see below): in the committed mode the remote-tracking `origin/main`/`origin/master` comes first — which is what a full checkout (`fetch-depth: 0` in `actions/checkout`) leaves available on a GitHub Actions PR or push — and the local branch is the fallback; in the local mode the local branch comes first, since it may be ahead with unpushed commits. On a shallow clone (e.g. `actions/checkout` with the default `fetch-depth: 1`), the base branch is not fetched, so it cannot be resolved — `pytest-regsmart` raises a `UsageError` telling you what to fix instead of silently running the whole suite. In CI, fetch the full history (see [Deployment](https://github.com/leticosta4/pytest-regsmart/blob/main/DEPLOYMENT.md)).

### Choosing the diff source (committed vs local)

By default, `pytest-regsmart` selects tests from the **committed** changes: the diff between the merge-base with the base branch and `HEAD`. That is what CI checks out, so build steps that rewrite files on disk before pytest runs (rewriting imports, removing `src/`, generating files) do not leak into the selection and cannot accidentally force the full suite. Untracked files are ignored in this mode.

To select from the **local, uncommitted** changes — the working tree plus untracked files, what you expect while developing — use the `--local-diff` boolean flag, or set `local_diff = true` in `pytest.ini`:

```bash
pytest --regsmart --local-diff
```

```ini
[pytest]
local_diff = true
```

The mode in use is reported in the terminal header: `Diff source: committed changes (default)` or `Diff source: local changes (--local-diff)`.

Before the test run starts, if `--regsmart` is passed, the terminal header will report `pytest-regsmart`'s configuration of this run, for example:

```
Starting Smart Regression Test Management (RTS + RTP)
Using --diff-level=function
Diff source: committed changes (default)
Using --ranking-weight=0-1
Using --ranking-level=put
Using --ranking-hist-len=50
Using --ranking-seed=123
Using --ranking-replay=None
```

After the test run finishes, the terminal summary reports the number of tests actually executed (selection and prioritization included), together with the overhead of `pytest-regsmart` in this run, for example:

```
=================================== pytest-regsmart summary info ===================================
Default branch used for comparison: origin/main
Time to run the regression test selection (s): 12.50 ms (0.0125 s)
Time to run the regression test prioritization (s): 2.50 ms (0.0025 s)
Time to collect test features (s): 0.63 ms (0.000625 s)
Tests executed: 84
```

`Tests executed` is the final count reported by pytest. When selection is skipped or the whole suite runs because of it, the summary also prints the reason as a line starting with `WARNING:` (see [How Regression Test Selection (RTS) works](#how-regression-test-selection-rts-works)).

When using `pytest-xdist`, the controller summary also includes selection and prioritization timings, the comparison branch, and warnings reported by the workers. For each timing, it reports the slowest worker duration; no prioritization timing is shown when prioritization is disabled or skipped.

### Disabling ranking (RTP)

You can disable the regression test prioritization while keeping the plugin active with the `--no-rank` flag:

```bash
pytest --regsmart --no-rank
```

This is useful when you want to run only the selected tests (RTS) without reordering them (RTP).
With `--no-rank`, the header instead reports:

```
Starting RTS (Regression Test Selection)
Using --no-rank (RTP disabled).
Diff source: committed changes (default)
```

Note that `--no-rank` **cannot be combined with other `--ranking-*` flags**: passing any of them together raises a `UsageError`. It only disables the prioritization step; the regression test selection still applies.

### Choosing the diff granularity

You can set at which level the changes are identified and tests are selected, by passing the optional `--diff-level` flag in one of these values: `function`, `file`. For example:

```bash
pytest --regsmart --diff-level=file
```

- `function` (default): maps each changed line range from the git diff to the functions or methods that contain it, then selects only the test functions affected directly or transitively through the call graph. Diff hunks outside any function (e.g., imports or module constants) fall back to selecting the whole file.
- `file`: a change in one module selects every test file that transitively depends on it, which may include more tests than strictly necessary.

This option can also be configured via the `diff_level` ini option (see [Setting configurable options via config file](#setting-configurable-options-via-config-file)).

The function-level graph augments pyan's call graph for some dynamic and indirect access patterns. For example, a test may call a function through a qualified module path such as `pkg.module.submodule.function()`, while the package exposes `module` or `submodule` dynamically; the graph uses the imported module and qualified path to connect the call to a matching function. It follows package re-exports and `import *` bindings when those bindings can be identified. It also follows inheritance relationships found in the repository: calls such as `self.method()` are connected to known overrides, and base classes with subclasses are connected to their public methods so changes to inherited APIs can reach tests that use a concrete subclass, including one imported through a package re-export. Since the receiver type of `self.method()` is not always known, changing an override can select tests for sibling subclasses too. For local variables, receiver types are used when evident from direct construction (for example, `instance = Child()`) or a type annotation; types are not inferred across functions, arbitrary factories, or collections. A root name shadowed by a local variable or parameter is not treated as an imported module. Some dynamic calls or re-exports may still be unresolved and leave the selection empty; when that happens with `--diff-level=function`, `pytest-regsmart` retries at the coarser `file` level. With an explicit `--diff-level=file`, an empty selection instead produces the full-suite warning.

Tests that call pytester's `runpytest_subprocess()` or `runpytest()` helpers are also retained by function-level selection whenever a Python diff exists. The nested pytest run has a separate call graph, so RegSmart cannot reliably connect its generated tests to changed functions in the parent analysis. This fallback does not execute or analyze the child process and may select these tests even when the change is unrelated to them.

```
WARNING: Function-level selection found no affected tests; falling back to file-level selection (1 test file(s)).
```

### Optimizing test prioritization heuristics

You can set the weights of different test prioritization heuristics by passing the optional `--ranking-weight` flag with formatted values:

```bash
pytest --regsmart --ranking-weight=0-1
```

- Weights are separated by ``-``
  - The first weight is for running faster tests
  - The second weight is for running recently failed tests
- All weights must be integers or floats, and their sum will be normalized to 1
- A higher weight means that a corresponding heuristic is favored.

The default value is ``0-1``, which only prioritizes faster tests.

### Optimizing test prioritization levels

You can set at which level of your test suite will be reordered, by passing the optional `--ranking-level` flag in one of these values: `put`, `function`, `module`. For example:

```bash
pytest --regsmart --ranking-level=function
```

- The smallest test item that can be reordered in pytest test suite is [parametrized unit test](https://docs.pytest.org/en/7.1.x/example/parametrize.html) (PUT)
- This option allows you to set at which level the reordering takes place:
  - `put` reorders the each PUT and re-arranges their order based on their assigned priority scores
  - `function` reorders each test function, parametrized values of a test function follow their default order
  - `module` reorders each test file, all tests in the test file follow their default order

The default value is `put`.

### Replaying specified test order

You can run/replay tests in a specific order by listing the to-be-run test IDs in a text file, where each line is a test ID, and pass the file path to the optional `--ranking-replay` flag:

```bash
pytest --regsmart --ranking-replay=replay_order.txt
```

Note that `--ranking-replay` **cannot be combined with random order** (`--ranking-weight=0-0`): passing both raises a `UsageError`.

### Tracking data from historical runs

You can also set the maximum value of *the number test runs since a test's last failure* that could be recorded for each test, by passing the optional `--ranking-hist-len` flag:

```bash
pytest --regsmart --ranking-hist-len=30
```

The default value is 50.
`pytest-regsmart` stores per-test feature data in pytest's cache: the most recent call duration and the number of successful runs since the last failure. Each run updates those values from tests that reached the call phase; skipped tests are not recorded. A failure resets that test's failure counter to zero, while a pass increments it up to `--ranking-hist-len`. This is cached feature data, not a complete log of prior test runs.

### Running tests in random order

You can prompt `pytest-regsmart` to run tests in random order, by setting the sum of `--ranking-weight` option to 0, e.g., `--ranking-weight=0-0`.
You can also set the seed used when running tests in random order, via setting an integer to the option `--ranking-seed`.
For example, the command below runs tests randomly with seed `1234`:

```bash
pytest --regsmart --ranking-weight=0-0 --ranking-seed=1234
```

By default, `pytest-regsmart` uses `0` as the seed.

### Setting configurable options via config file

You can always apply available options by adding them to the ``addopts`` setting in your [pytest.ini](https://docs.pytest.org/en/latest/reference/customize.html#configuration).

For example, create `pytest.ini` in your codebase root folder as such:

```ini
[pytest]
addopts = --regsmart --ranking-weight=1-0 --ranking-hist-len=30
```

and run `pytest` on the command line.

Alternatively, you can set values directly as ini options (without `addopts`) and run `pytest --regsmart` on the command line:

```ini
[pytest]
diff_level = function
local_diff = false
no_rank = false
ranking_weight = 1-0
ranking_replay =
ranking_level = put
ranking_hist_len = 50
ranking_seed = 0
```

## How Regression Test Selection (RTS) works

When `--regsmart` is used, `pytest-regsmart` runs a Regression Test Selection step before the tests are executed:

1. **Compute the changed files.** It uses git to inspect the repository against the **base** branch — the repository's default branch (`main`, or `master` if that is how it is named), never the currently checked-out branch:
   - the base is resolved according to the diff source: in the committed mode (default) it prefers the remote-tracking `origin/main`/`origin/master` — what a full checkout (`fetch-depth: 0` in `actions/checkout`) leaves available on a GitHub Actions PR or push — and falls back to the local branch; in the local mode (`--local-diff`) it prefers the local branch and falls back to the remote-tracking ref;
   - the diff is the merge-base with that base, so every commit on a PR/branch is compared against `main`/`master`, not against itself;
   - by default (committed mode) it collects the files changed between the merge-base and `HEAD` and ignores untracked files; with `--local-diff` it collects modified (`staged` + `unstaged`) and untracked files from the working tree instead. If the repository has no commits yet, only untracked files are considered.

2. **Build a dependency graph when changes exist.** If a diff is detected, [`pyan3`](https://pypi.org/project/pyan3/) parses every `*.py` file in the repository (excluding `.venv`, `venv`, `.git`, `__pycache__`, `dist`, `build`, `site-packages`, `.pixi`, and directories ending in `.egg-info`) and builds a dependency graph whose granularity follows `--diff-level`: a function-level call graph when `function` (default), or a module-level import graph when `file`. The graph is then inverted so that, for each node, it knows *which* other nodes depend on it.
3. **Propagate changes transitively.** A depth-first traversal (DFS, implemented with a LIFO stack) starts from the changed units — changed files at the `file` level, or the functions containing the changed lines at the `function` level — and walks through their dependents, collecting every test unit affected directly or indirectly: test files (files named `test_*.py` or `*_test.py`) or individual test functions, respectively.
   At the `function` level, this also follows the fixtures pytest resolved for each collected test and members invoked implicitly through their class, such as special methods and properties.
4. **Filter the test suite.** At the `file` level, test items whose file is not in the selected set are removed; at the `function` level, only collected items matching a selected pytest nodeid are kept. Only affected tests are actually executed. As a safety net, if the filter would remove *every* collected test (a nodeid mismatch between the graph and pytest's collection), the original list is restored and a warning is reported, instead of pytest exiting with "no tests ran".

If there is no diff in Python files since the baseline, `pytest-regsmart` skips both dependency-graph generation and test selection, reports a warning, and runs the full test suite. Changes to non-Python files alone do not trigger RTS. RTP still runs unless `--no-rank` is set; with no Python diff and `--no-rank`, the plugin reports that it has no work to do.

Two additional edge cases also cause selection to be skipped (the full suite runs):

- **`conftest.py` changed.** Because `conftest.py` can alter collection and fixture behaviour globally, any change to it disables test selection for that run — the full suite executes instead. In the committed mode (default) only a committed change counts, so a `conftest.py` rewritten only in the working tree (e.g. by a CI step) does not disable selection.
- **No shared history with the base branch.** If the base branch (`main`/`master`) is resolved but has no merge-base with the current HEAD (e.g. unrelated histories), selection is skipped with a warning.

A fourth case is different: a diff exists and the graph is built, but the selection comes back empty. That never happens silently:

- at the `function` level (the default), the selection is retried at the `file` level, and the summary reports `WARNING: Function-level selection found no affected tests; falling back to file-level selection (N test file(s)).`;
- if the `file` level also finds nothing — or was requested explicitly with `--diff-level=file` — the summary reports `WARNING: Diff detected but no affected tests found at file level: running the full suite.` and the full suite runs.

Deleted Python files are included in the Git diff. Since the dependency graph is built from files present in the working tree, a deleted file has no graph node to trace to its dependents. If that leaves no affected tests, the same empty-selection behavior applies: function-level selection retries at file level, and an empty file-level result runs the full suite with a warning. This favors running extra tests over silently skipping tests after a deletion.

Because selection granularity follows `--diff-level`, the default `function` level narrows the selection down to the affected test functions, while `file` selects whole files and is therefore intentionally conservative: a change in one module selects every test file that transitively depends on it, which may include more tests than strictly necessary. See [Choosing the diff granularity](#choosing-the-diff-granularity).

## How Regression Test Prioritization (RTP) works

After selection, `pytest-regsmart` reorders the remaining tests so that failures are exposed sooner. Each test receives a priority score computed as the weighted sum of two heuristics:

- **Faster tests first**, based on their recorded execution durations from previous runs;
- **Recently failed tests first**, based on how many runs have passed since each test's last failure.

Weights are set with `--ranking-weight`, normalized to sum 1 (default `0-1`, recent failures), and scores are aggregated per group according to `--ranking-level` (`put`, `function`, or `module`). Two special modes replace these heuristics: replaying a fixed order listed in a text file (`--ranking-replay`) and random order (`--ranking-weight=0-0`, seeded by `--ranking-seed`). 

RTP is skipped whenever there is nothing to reorder, independently of which ranking flags are in use. If the selection leaves a single test, the prioritization step is skipped and the summary reports `RTP skipped: only 1 test was selected, nothing to reorder.` When pytest itself collects exactly one test (e.g. a single node id passed on the command line or a `-k` filter matching one test), both RTS and RTP are skipped entirely, and the summary reports `RTS and RTP skipped: only 1 test was collected.`

See [Usage](#usage) for all available options.

## Deployment

`pytest-regsmart` is easy to deploy into a CI workflow; see [Deployment](https://github.com/leticosta4/pytest-regsmart/blob/main/DEPLOYMENT.md).

## Local development

Install the package and dependencies with uv:

```bash
uv sync
```

### Running tests

```bash
uv run pytest -xv tests/
```

To test across all supported Python versions, use [tox](https://tox.readthedocs.io/en/latest/):

```bash
tox
```

To run a specific environment only (e.g. Python 3.12):

```bash
tox -e py312
```

To pass extra arguments to pytest via tox:

```bash
tox -- -k "test_name"
```

## Compatibility

`pytest-regsmart` works with [_pytest_ test filtering](https://docs.pytest.org/en/6.2.x/usage.html#specifying-tests-selecting-tests) and [parallelization](https://pypi.org/project/pytest-xdist).
It also works with plugins for ordering tests, e.g., [pytest-order](https://pypi.org/project/pytest-order), [pytest-dependency](https://pypi.org/project/pytest-dependency) by running ordered tests first in their declared order. Pytest options that order tests generally (e.g., [`--ff`](https://docs.pytest.org/en/stable/how-to/cache.html#usage)), or plugins that randomly order tests (e.g., [pytest-randomly](https://github.com/pytest-dev/pytest-randomly), [pytest-random-order](https://github.com/pytest-dev/pytest-random-order), [pytest-reverse](https://github.com/adamchainz/pytest-reverse)), can interfere with `pytest-regsmart` as they use the same reordering hook.

`pytest-regsmart` supports Python 3.11+.

## Contributing

Contributions are very welcome.

## License

Distributed under the terms of the [GNU General Public License v2.0 or later](https://www.gnu.org/licenses/old-licenses/gpl-2.0.html), `pytest-regsmart` is free and open-source software.
See [NOTICE.md](https://github.com/leticosta4/pytest-regsmart/blob/main/NOTICE.md) for attribution of the incorporated third-party code (pytest-ranking under the MIT License and pyan3 under the GPLv2+).

## Issues

If you encounter any problems, please [file an issue](https://github.com/leticosta4/pytest-regsmart/issues) or [pull request](https://github.com/leticosta4/pytest-regsmart/pulls) along with a detailed description.

## Reference

### From _pytest-ranking_:

**Demo video**

A 5-minute demo video with walkthrough of `pytest-ranking`: [YouTube link](https://youtu.be/SrnkgTs3uok?feature=shared)
(pytest-regsmart: TBA)

**Bibtex citation**

```
@inproceedings{cheng2025pytest,
  title={{pytest-ranking: A Regression Test Prioritization Tool for Python}},
  author={Cheng, Runxiang and Ke, Kaiyao and Marinov, Darko},
  booktitle={Companion Proceedings of the 33rd ACM International Conference on the Foundations of Software Engineering},
  year={2025},
}
```
