Skip to main content

pytest-leela

Type-aware mutation testing for Python.

PyPI version Python versions License CI


What it does

pytest-leela runs mutation testing inside your existing pytest session. It injects AST mutations via import hooks (no temp files), maps each mutation to only the tests that cover that line, and uses type annotations to skip mutations that can't possibly fail your tests.

It's opinionated: we target latest Python, favour speed over configurability, and integrate with pytest without separate config files or runners. If that fits your workflow, great. MIT licensed — fork it if it doesn't.


Install

pip install pytest-leela

Quick Start

Run mutation testing on your whole test suite:

pytest --leela

Print compact agent guidance for writing good mutation tests, without running tests:

pytest --noconftest --skill > SKILL.md

Leela skips test collection, but pytest can import conftest.py before Leela prints the skill. Use --noconftest when exporting the Markdown from a project so its conftest files cannot add output or prevent the export.

After the normal pytest run, Leela reports its baseline check and prints a progress line before each mutant, with the active location and completed/runnable count. Pruned mutants are listed separately. Each completed mutant also gets a verdict and wall time covering the whole runner call, including any control and confirmation runs. Leela lists up to five slowest completed mutants at the end.

--leela-optimize-order is an experimental ordering option, off by default—not a guaranteed speedup. On a cold cache it runs the cheapest covering file blocks first within adjacent sibling files, using the sum of the selected tests' measured durations. It also sorts tests by duration within each contiguous collector group. File blocks never cross directory/package transitions, split files, or files containing selected parametrized tests. Parametrized items themselves stay put. Ties preserve collection order and unmeasured tests or files sort last within their group. Leave optimize-order off if your suite depends on an order set by another collection hook.

On warm runs, the last fresh call-phase killing test for that exact mutation runs first once, only if it is still in the current coverage selection. It must execute and fail again to kill the mutant; a hint never skips tests or reuses a verdict. If it survives, the remaining tests run in the same timing order as a cold run, without repeating the hinted test. A missing/unselected hint is cold. This promotion can cross the cold ordering's fixture boundaries, so warm runs also require order-independent tests. The baseline and ordinary tests are not reordered. Existing first-failure short-circuiting is unchanged.

Hints identify the checkout-relative file, the enclosing function's lexical name and location-independent AST, and the mutation's position within that function. Adding a mutant in an unrelated function in the same file does not discard existing hints. Changed functions use fresh hints; module-level or ambiguous locations fall back to a conservative file identity. Integer mutant IDs and absolute checkout paths are never keys. Only a fresh call-phase failure can become a hint—not timeouts, runner errors, or inconclusive setup/teardown/import/collection failures and their controls. No extra clean control is added. Hints contain test node IDs, not verdicts.

The bounded cache is .pytest_cache/d/leela/order-v2.json under pytest's root (or the equivalent under a configured cache_dir). .pytest_cache/ is gitignored; for a custom cache directory, gitignore that directory too. At most 2,048 hints and 1 MiB are retained; oldest entries are discarded. Writes use same-directory atomic replacement. Concurrent writers are last-writer-wins: lost hints only lose optimization, and readers see complete snapshots. Missing, invalid, unsupported-version, or unwritable caches behave cold. Disabling the option never reads or writes hints; -p no:cacheprovider keeps timing-only ordering. Delete the hint file to reset it. Older v1 hints are not used; the first run with v2 starts cold and can seed a new cache. There is no old-flag alias.

Optimize-order does not run a clean check to verify a call-phase kill after reordering. Use it only if you have verified that the selected tests are order-independent. For example, if a fast test expects a slower test to prepare shared state, optimize-order may run it first. That test can fail even without the mutation, so Leela can report a false kill and inflate the score. Rerun without --leela-optimize-order to compare with the original ordering.

The option does not change which tests are selected, the baseline order, or the timeout calculation. Leela still uses clean controls for inconclusive setup, teardown, collection, and import failures.

Save and restore ordering hints in CI

For warm runs on GitHub Actions, restore and save the gitignored v2 hint file around the test step. Run with the same Leela version and test environment when you compare timings:

- uses: actions/cache@v4
  with:
    path: .pytest_cache/d/leela/order-v2.json
    key: ${{ runner.os }}-leela-order-v2-${{ github.sha }}
    restore-keys: |
      ${{ runner.os }}-leela-order-v2-
- run: python -m pytest --leela --target src/your_package --leela-optimize-order

The cache action restores before the test step and saves after a successful job on a miss. A cache first saved by a pull-request workflow can be reused by reruns of that PR, but not by the base branch or other PRs. To share a warm cache across PRs, seed it on the trusted default branch. Check that a fresh runner actually restores the v2 file before counting on a warm-run speedup. See GitHub’s cache scope rules.

For Forgejo Actions, use the same path/key/restore/save pattern with uses: https://github.com/actions/cache@v4 (or your runner's supported mirror) on a runner with a configured Actions cache service; github.sha is the compatibility context. Keep your existing checkout/setup/install steps on both runners. Cache keys should be repository/trust scoped, not shared across untrusted repositories. If your runner has no cache service, leave it out: runs remain cold and correct. A restored hint is still only ordering advice, never a saved verdict.

To tune a mixed unit/integration suite, write a fresh --leela-jsonl results.jsonl report. Choose a soft wall-time budget appropriate for your project and look for killed mutants whose wall_time_seconds exceeds it. Use the file and line to add a cheap covering test that kills the same mutation, then compare the reports with all integration tests still selected. A budget overrun is a profiling signal, not a verdict. Surviving mutants may still need every covering test.

When no --target is given, pytest-leela auto-discovers source files:

  1. Looks for a target/ or src/ directory (in that order) and mutates all .py files inside it
  2. If neither exists, falls back to the project root (skipping .venv, build, dist, __pycache__, node_modules, .git, and similar non-source directories)

Test files (test_*.py, *_test.py, conftest.py, tests.py) are always excluded from mutation.

Exclude patterns from [tool.pytest-leela] (see Configuration) are applied after target discovery, so you can auto-discover src/ while still excluding specific paths.

Target specific modules (pass --target multiple times):

pytest --leela --target myapp/models.py --target myapp/views.py

Only mutate lines changed vs a branch:

pytest --leela --diff main

Limit CPU cores:

pytest --leela --max-cores 4

Cap memory usage:

pytest --leela --max-memory 4096

Combine flags:

pytest --leela --diff main --max-cores 4 --max-memory 4096

Generate an interactive HTML report:

pytest --leela --leela-html report.html

The HTML report and terminal summary both show Mutation test order. Standard means optimization is off. Optimized means --leela-optimize-order was enabled; a cold cache can still use timing only. The report shows both the inner attempt's elapsed time (time_seconds) and the full runner wall time (wall_time_seconds) for each mutant. The latter includes any control and confirmation runs and matches the JSON Lines measurement when both outputs are enabled. If a report is generated from an untimed programmatic run, its per-mutant wall time is null and the viewer shows only the inner elapsed time.

Stream completed mutant results to a local JSON Lines file:

pytest --leela-jsonl mutant-events.jsonl

This enables mutation testing and creates a new file after the normal pytest run passes. Use a fresh path for each invocation, distinct from any HTML report path; an existing file is never overwritten. Each completed mutant produces one UTF-8 JSON object and newline, flushed before Leela moves on. No baseline, progress, or summary records are written; a mutation run with no completed mutants leaves an empty file.

Schema version 1 has schema_version (the integer 1), mutant_id (Leela's existing run-local integer ID), file_path (absolute), module_name, lineno (one-based), col_offset (zero-based UTF-8 byte offset), original_op, replacement_op, verdict (killed, survived, or error), and wall_time_seconds (the full runner call, including any control and confirmation). The file is not a success marker: check pytest's exit status. A sink error aborts mutation testing with a diagnostic and a nonzero exit; the file may be incomplete.

Run experimental shards on separate machines:

pytest --leela-write-plan leela-plan.json --leela-shard-count 2
pytest --leela-plan leela-plan.json --leela-shard 0/2 --leela-jsonl shard-0.jsonl
pytest --leela-plan leela-plan.json --leela-shard 1/2 --leela-jsonl shard-1.jsonl
python -m pytest_leela.shard leela-plan.json shard-0.jsonl shard-1.jsonl

Copy the plan from the first command to both workers. Use matching checkouts, Python, pytest, dependencies, configuration and test arguments. Every worker runs the ordinary tests, reconstructs the full mutation plan and checks the full clean baseline before executing its assigned occurrences serially. Workers reject differences in the checked inputs or selectors and reuse the planner's timing inputs. Don't divide --target between workers.

Run each index once and collect each JSONL file with its .receipt.json sidecar. The verifier checks every assigned mutant_id, the plan identity and the exact event bytes. It returns 0 for complete passing results, 1 for complete results that fail mutation policy, and 2 for invalid or incomplete evidence. Do not use worker exit codes alone as proof of completion. Source locations can repeat; file_path is local to each worker.

Use a regular checkout without symlinked project directories and with its Python environment outside the checkout. The fingerprint includes local .py files, effective Leela config, pytest config, platform and dependency versions. It does not check all external state (e.g. data files, environment variables, native libraries or installed package contents); those must be equivalent separately. Checksums detect accidental changes, not untrusted inputs. This is not a distributed runner or a speed guarantee. Diff, optimize-order, HTML, benchmark and xdist modes cannot be combined with sharding.

Benchmark optimization layers:

pytest --leela-benchmark

Features

  • Type-aware mutation pruning — uses type annotations to skip mutations that can't possibly trip your tests (e.g. won't swap + to - on a str operand)
  • Per-test coverage mapping — each mutant runs only the tests that exercise its lines, not the whole suite
  • In-process execution via import hooks — mutations applied via sys.meta_path, zero filesystem writes, fast loop
  • Git diff mode — --diff <ref> limits mutations to lines changed since that ref
  • Framework-aware — clears Django URL caches between mutants so view reloads work correctly
  • Resource limits — --max-cores N requests a CPU-affinity limit where supported; it does not set a worker count. --max-memory MB guards memory.
  • Concurrency reporting — the terminal reports the observed peak for serial mutant execution (one if any mutant ran, zero otherwise). Pytest worker concurrency during mutation is not measured. The configured --max-cores and outer pytest -n are reported separately.
  • HTML report — --leela-html generates an interactive single-file report with source viewer, survivor navigation, and test source overlay
  • CI exit codes — exits non-zero when mutants survive or error, so CI pipelines fail on incomplete kill rates
  • Benchmark mode — --leela-benchmark measures the speedup from each optimization layer

Configuration

Configure pytest-leela in your pyproject.toml under [tool.pytest-leela]:

[tool.pytest-leela]
exclude = [
    "*/migrations/*",
    "manage.py",
    "*/conftest.py",
]
operators = [
    "arithmetic",
    "comparison",
    "boolean",
    "return",
]
fail_on_error = true

exclude

A list of glob patterns. Files whose path (relative to the project root) matches any pattern are excluded from mutation. Uses fnmatch matching — * matches within a single directory, */migrations/* matches any migrations directory at any depth.

Default: [] (nothing excluded).

operators

A list of operator category names controlling which mutation types are applied. Use "all" as a shorthand to enable every category.

Default: ["arithmetic", "comparison", "boolean", "unary", "return"]

Category What it mutates Default
arithmetic + - * / // % ** on
comparison == != < <= > >= is in and negations on
boolean and / or, and negation of bare if / elif / assert / while predicates and comprehension filters (flag, obj.flag, check()) on
unary unary - + not on
return return values (True/False, None, literals, expressions) on
bitwise & | ^ << >> off
assignment replace the right-hand side of a simple name assignment with None off
augmented_assign += -= *= etc. off
ternary x if cond else y branch swaps off
control_flow break / continue swaps off
exception except handler broadening, body-to-raise off
decorator remove one decorator from a function, async function, or class off

Bare assert negation changes assert check(), message to assert not check(), message. It leaves the message in place and adds no whole-predicate mutant for assert a and b, assert not a, or assert a == b; those expressions retain their existing operator mutations. In --diff mode bare assertion negation is selected by the line containing the assert keyword.

Bare while negation changes while check(): to while not check():, leaving its body and any else intact. It still checks the predicate once per condition evaluation. A negated loop can fail to terminate; Leela's in-process timeout checks between tests and cannot interrupt a stuck test. In --diff mode this mutation is selected by the line containing the while keyword.

Bare filter negation applies to list, set, and dict comprehensions and generator expressions. For example, [x for x in items if ready(x) if x.active] can become [x for x in items if not ready(x) if x.active]. Each mutant changes one filter and leaves the other filters and for clauses intact. Compound filters keep their existing operator mutations. In --diff mode, the filter expression's starting line must change, which can differ from the line containing if.

Add "decorator" to your operator list (or use "all") to enable decorator removal. For a stack like @wrap followed by @suffix("!"), Leela generates two separate mutants. Each removes one decorator expression, leaving the other in place. In --diff mode the decorator expression's starting line must be changed.

Add "assignment" to your operator list (or use "all") to enable assignment RHS replacement. It changes name = expression, a = b = expression, or name: Type = expression to assign None without evaluating expression. It creates one mutant per RHS, preserving all name targets and any annotation. It skips literal None, annotation-only declarations, any assignment with an unpacking, attribute, or subscript target (including mixed chains), augmented assignments, and assignment expressions. In --diff mode the RHS expression's starting line must be changed.

fail_on_error

Whether errored mutants fail the session (non-zero exit). Default: true.

See Mutant statuses. Set it to false only when you accept that some mutants go untested, for example while fixing a known collection problem.


Mutant statuses

Each mutant ends in exactly one of three states:

Status Meaning Counts toward the score
killed A call-phase test failure or mutant timeout, or a setup/teardown/collection/import failure confirmed by a passing clean control and recurrence of the same failure under the mutant yes
survived Tests ran and all of them passed yes
error No trustworthy verdict: an inconclusive setup/teardown/collection/import failure, pytest crash, deliberate skip/exit, abnormal exit without a test failure, or zero tests run (for example everything skipped). An inconclusive error may have zero or positive call-phase tests_run no

The mutation score is killed / (killed + survived). Errors are listed separately, with their reason, in the terminal report, the HTML report and the JSON output, and they fail the session unless fail_on_error = false. An error means leela could not tell whether your tests catch the mutant, so it is reported as neither a kill nor a survival.

The initial clean baseline proves only that the selected tests passed before mutation. A setup, teardown, collection or import failure without a call-phase failure is initially inconclusive, even if earlier tests passed. Leela runs at most one clean unmutated control through the same selection and, only if that passes, one additional mutant confirmation. It counts a kill only when the actual phase, node, exception identity/message and meaningful visible chained cause recur. A failed control, different failure, surviving confirmation or insufficient exception evidence remains error, with the original and control/confirmation diagnostics. Ambient or flaky failures therefore do not automatically kill unrelated mutants. These are bounds on attempts, not a hard wall-clock execution limit or perfect proof against all nondeterminism.

This check preserves genuine mutation-caused target imports and test-module collection failures, including module-level assertions such as assert calc.RATIO == 5; the killing nodes name the files that failed to collect. A conftest's own check failing during collection can also kill after this confirmation. Before the session starts, a failed conftest import is eligible when the mutated target itself raised during import; a conftest's own check without such a target import failure remains an error. A conftest that catches an error and calls pytest.exit() or pytest.skip() remains an error, not a confirmed kill.

If a test caught the import error and the suite completed green, the mutant survived: no test noticed it. If the mutant made the tests skip themselves (a module-level pytest.skip, a skipif marker, or a conftest or test module that skips or calls pytest.exit() at import), the mutant is an error: no test ran.

Known limits of these rules:

  • A module that can only be imported once per process. If a test module imports something that refuses to load twice (for example it raises when a process-global registry is already installed), every re-import fails to collect. Through pytest --leela the outer session has already imported it, so the clean baseline fails and the run aborts. When Engine.run is called directly with use_coverage=False and a test directory, the baseline may be the first import and pass. Later re-import failures also fail the clean per-mutant control: those mutants are inconclusive errors, commonly with tests_run: 0, excluded from the score. Leela does not make non-idempotent registration safe to repeat in-process.
  • A deliberate exit hides every kill not yet reported. When a conftest or a test module catches the target's import error and calls pytest.exit(), the inner run ends there and the mutant is an error. Tests run only after collection, so no test failure is ever reported, including a test that imports the target inside its body; nor is a sibling module's collection failure that pytest would have reached after the exit. A module that already failed to collect before the exit stops the run first (-x) can still kill after same-failure confirmation.

Clean baseline before any mutant

Before the first mutant, leela runs the selected tests once with no mutation applied, through the same in-process path every mutant uses. If anything fails or errors there, the run aborts with leela: aborted: tests do not pass with no mutation applied (...) and a non-zero exit, and no mutants are scored. Without this check, a test that fails for an unrelated reason (a fixture that cannot run in-process, a missing service) would score every mutant as killed.

pytest-django

pytest-django blocks database access for the whole session and only restores it at unconfigure, after leela has run. Leela lifts that outer block for the duration of its run (through pytest-django's own django_db_blocker.unblock()), so database tests in the inner sessions can open connections as they do in a normal run.

Django model and admin modules are never reloaded between mutants (unless one is itself a --target), and neither is any project module they reference. Re-executing them registers models and admin classes a second time, which Django rejects, and re-importing a module they reference would split class identity (a kept model subclassing the old copy of a reloaded mixin). The trade-off: if a model or admin module imports a function from your target at module level, calls through that reference run the unmutated code, which shows up as a survivor, never as a fake kill.

Installed packages are never reloaded

Between mutants leela evicts the project's own modules so that mutated code is re-imported. Installed packages are left loaded, even when the virtualenv sits inside the project directory (uv's default .venv): anything under sys.prefix, sys.base_prefix, site.getsitepackages(), site.getusersitepackages(), or a site-packages / dist-packages directory. Re-importing them would break C extensions such as numpy, which CPython can load only once per process.


Pragma Skip

Add # leela: skip to suppress mutations on individual lines:

result = x + y  # leela: skip

To skip an entire file, place the pragma on line 1:

# leela: skip
"""This module is excluded from mutation testing."""

def legacy_code():
    ...

The pragma is detected via Python's tokenize module, so it only matches actual comments — not string literals or docstrings that happen to contain the text.


HTML Report

--leela-html report.html generates a single self-contained HTML file with no external dependencies.

What it shows:

  • Overall mutation score badge
  • Per-file breakdown with kill/survive/error counts
  • Source code viewer with syntax highlighting

Interactive features:

  • Click any line to see mutant details (original → mutated code, status, relevant tests)
  • Survivor navigation overlay — keyboard shortcuts: n next survivor, p previous, l list all, Esc close
  • Test source overlay — click any test name to see its source code

Uses the Catppuccin Mocha dark theme.


Requirements

  • Python >= 3.12
  • pytest >= 7.0

License

MIT

Metadata

Release files for pytest-leela 0.24.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pytest-leela 0.24.0
File Size Uploaded Provenance Actions
pytest_leela-0.24.0.tar.gz 221.6 kB With provenance Details for pytest_leela-0.24.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pytest-leela 0.24.0
File Interpreter ABI Platform Actions
pytest_leela-0.24.0-py3-none-any.whl Python 3 none any Details for pytest_leela-0.24.0-py3-none-any.whl

Total release size: 302.7 kB

Release files / pytest_leela-0.24.0.tar.gz

Download URL pytest_leela-0.24.0.tar.gz
Size 221.6 kB
Tags Source
SHA-256 checksum
How to use checksums
09643176bb5eb88f10ee5bb261755693c9c5c6af3071f91f5f52000194b2cf71
BLAKE2b-256 checksum
How to use checksums
036790b70bdb51e5873eb0b0bbbca946262acfee1d805d52ddc08b4ce71b7886
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

Release files / pytest_leela-0.24.0-py3-none-any.whl

Download URL pytest_leela-0.24.0-py3-none-any.whl
Size 81.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9995621b9bccd6afc81faa572464cd23a8a713f391600205f32729934ee0836d
BLAKE2b-256 checksum
How to use checksums
511c1e59673d0cecf0cefcfc220635fbae31f178176d42043cfecd9d96e98544
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

Security for pytest-leela 0.24.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pytest_leela-0.24.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.24.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page