Skip to main content

pytest-admission

Project-configured admission for pytest. Requires Python 3.11+ and pytest 8.3.4 through 9.x. Licensed under the MIT license in LICENSE.

Install

python -m pip install pytest-admission

The pytest11 entry point loads the plugin automatically. For a source checkout:

python -m pip install -e '.[test]'
python -m pytest -q

CI runs Python 3.11 and 3.12 with both pytest 8.3.4 and the newest available pytest below 10. Acceptance tests use isolated pytester subprocess sessions and a file-writing stand-in, not a solver or compiler.

Admission command

pytest-admission check --base <review-base>
# Source-checkout alternative:
python -m pytest_admission.cli check --base <review-base>

The command collects the full project once, never running test bodies or fixtures. Configured workflow sources have collection-only subprocesses, started when the command's session configures so they overlap its collection. It ignores pytest addopts and PYTEST_ADDOPTS so they cannot narrow the population. Each failing check prints one line prefixed with its arm (selection, contract, or simulation); collection/configuration errors also fail closed. Exit status is 0 on a clean collection and 1 on failure. --base defaults to HEAD; --root <directory> selects another project. The existing pytest-admission record command remains the sole record writer.

Ordinary pytest sessions (including source collections and xdist workers) install the runtime sink refusal only: no reach walk, admission checks, reach artifacts or source-collection subprocesses. Admission checks belong to the command's collection; the record writer retains its own collection.

Release

Version 0.2.0 is released by pushing tag v0.2.0 after configuring the repository's PyPI trusted publisher for .github/workflows/release.yml and the GitHub pypi environment. The workflow builds the wheel and source distribution without publishing credentials, checks the tag against package metadata, then publishes through PyPI's trusted-publishing action. Tagging and configuring/approving publication are maintainer actions.

Declare launch sinks

Put configuration in the pyproject.toml at pytest's root directory:

[tool.pytest-admission]
sinks = ["myproject.launch:compile_model", "myproject.runner:Runner.launch"]

[tool.pytest-admission.relax]
env = "PROJECT_BUILD_VENUE"
values = ["toolchain"]

Each sink is importable.module:qualified.callable; dotted attributes after the colon can name methods. Declare the callable at the entry point used by the project, not a copied alias. Target modules must be importable at session configuration time (use an installed package or pytest's pythonpath setting). Importing a target module must not itself launch work.

Before collection, pytest_configure imports and resolves every declared sink, then replaces each with a callable that fails with pytest-admission: refused sink <configured name>. No original call is made. A call from a fixture fails during setup. Originals are restored when pytest cleans up its configuration, including failed sessions.

The refusal is armed by default in every session. Only an exact, case-sensitive match between the configured environment variable and one of values leaves the original callables untouched. Missing, empty, misspelt, and other unrecognised tokens do not relax it. Without relax, sinks remain armed. The plugin is a test guard, not a sandbox: it does not intercept aliases that were already copied before configuration or launches outside declared sinks.

No table (or no sinks) means no declared sinks. Configuration accepts only sinks, relax, project_roots, simulation_list, registry, record, simulation_lists, jobs, launchers, and hand_kept_lists; relax accepts only env and values. Unknown keys, malformed tables, malformed callable names, non-string or duplicate array entries, missing relaxation fields, and unresolvable/non-callable sinks fail configuration with an error naming the field or sink. sinks may be empty; relax.values must contain at least one non-empty string. Environment variable names use letters, digits and underscores and cannot start with a digit.

Collection reach analysis

project_roots = ["."] names directories relative to the pytest root (the default is the whole project). simulation_list = ["tests/test_model.py::test_run"] lists admitted simulation-bearing node IDs; shell-style patterns are accepted, including for parametrized IDs. The default list is empty. Being listed does not relax runtime refusal: only the venue token does that.

The admission command's collection walks test bodies and every fixture in each item's closure, following statically resolved Python calls inside those roots. Reaching a declared sink, or an ambiguous call beneath a declared sink module, places a test in the simulation-bearing tier; otherwise it is fast. Unlisted simulation-bearing tests fail collection admission. Dynamic string-based getattr calls are not resolved: they can remain fast and still be refused at runtime.

Each admission collection writes .pytest_cache/admission/<session-id>.json, keyed by node ID, with tier, sinks, routes (call chains), and unresolved_calls. The artifact is written even when admission fails. Tier is also exposed as the admission_tier item user property. The walk does not execute user calls and is not a proof of absence of simulation; runtime refusal remains independent. Each function's analysis and each module file's top-level imports are cached for that collection. Every item's depth-first traversal replays those analyses with its own visited set, preserving route order and unresolved-call counts.

Contract admission

Enable the contract check by configuring both project-relative paths:

[tool.pytest-admission]
registry = "tests/contracts.toml"
record = "tests/admission_record.json"

The registry is a TOML contracts table keyed by contract name (its values may hold descriptions), or contracts = ["name", ...]. An empty file is an empty registry. Mark each covered test with @pytest.mark.contract("name"). Unknown names, multiple markers on one item, malformed markers, and registered names with no collected item fail admission.

Run the whole collection with pytest-admission check --base <revision>. Git's committed <revision>...HEAD diff defines added or edited tests; their function spans include decorators. Unmarked changed definitions fail. --base defaults to HEAD for an unchanged-tree run; pass the review base to check a change. The pytest project root may be a subdirectory of the Git repository; changed paths are resolved from the repository toplevel, not the project root. The unmarked count counts collected items, including each parametrized case, and must equal the record's unmarked_tests. It may not rise above the base record, and removing an unmarked item requires lowering the record in the same change. A zero record permits no unmarked item.

pytest-admission record
# Source-checkout alternative:
python -m pytest_admission.record record --root .

This command is the only record writer. It collects without running test bodies or fixtures, initializes a missing record, or lowers the existing unmarked_tests and simulation_listed counts. With configured jobs it computes gaps from the same source collections as the check, without needing a committed record. Later runs refuse added gaps and drop closed ones; without jobs, existing gaps are preserved. An increased count, added gap, collection error or admission error leaves the file untouched. Commit the first record before the first check. Ordinary pytest sessions never rewrite the admission record. Commit the record together with the tests that lower it.

Selection coverage

Declare up to six logical jobs, each with one or more workflow sources:

[[tool.pytest-admission.jobs]]
name = "fast"
capabilities = ["network"]
sources = [{ workflow = ".github/workflows/tests.yml", job = "unit" }]

[[tool.pytest-admission.hand_kept_lists]]
path = "tests/allowlist.toml"
format = "toml"
field = "tests.nodes"

Each source reads its pytest arguments from that workflow job's run steps. Literal pytest, python -m pytest, and prefixed commands such as uv run pytest are supported. Workflow/job/step working directories and simple cd commands are respected. $NAME and ${NAME} in pytest arguments resolve from the same step's env, then the job's env, then workflow env (never the host environment). Scalar values remain one argument, including quoted marker expressions. An env value may use ${{ matrix.KEY }} from a finite strategy.matrix: literal axes, include and exclude are expanded, and distinct argument sets are unioned. This supports step env declarations such as SHARD: ${{ matrix.shard }} with --ci-shard "${SHARD}/${SHARD_COUNT}". Single-quoted or backslash-escaped dollar signs in pytest arguments fail closed instead of being expanded; ordinary double-quoted references remain supported. Unknown references, dynamic matrices, other workflow expressions and command substitutions fail closed. Workflow shell, test bodies and launcher scripts are never executed by the check; collection does import tests and conftests. Distinct invocations are collected in fresh subprocesses with their paths, markers, deselections and plugin options intact. An invocation is its resolved working directory together with its resolved arguments: identical invocations share one subprocess across sources and jobs, but equal arguments in different directories do not. At most os.cpu_count() collections run at once (one when the CPU count is unavailable), and the item hook joins their results. File-descriptor redirects such as 2>&1, including before | tee log, do not become positional pytest arguments. Only an unquoted number directly adjacent to < or > is an fd prefix. Numeric pytest arguments separated from the redirect, such as -n 4 > log or --maxfail 2 > log, are preserved.

Set launchers = ["scripts/collect_launcher.py"] in the main admission table for a command whose pytest arguments follow --. Sources within one logical job are unioned, then all logical jobs are unioned. Fewer than six jobs permits only gaps already in the HEAD-committed admission record's JSON gaps; six jobs permits no gaps. A second source is not another job. The check does not rewrite the record, and jobs require the configured registry/record pair.

A skip mark or a skipif with no condition fails admission. Conditions may be positional or supplied as condition=; a supplied condition is conditional even when it evaluates to True in the collecting environment. A capability skip uses @pytest.mark.skipif(condition, capability="network", reason="..."); at least one configured logical job must declare that capability.

List formats are lines (one ID per nonblank line, # comments permitted), toml (a dotted field selecting a string array or projecting a string field from an array of tables, e.g. field = "node.id" for [[node]] entries), or python (field naming one module-level literal tuple/list, read by AST without importing it). Missing fields and non-string or empty IDs fail closed. Entries must resolve to collected items; pytest parent selectors, including unparametrized function IDs, are accepted. Missing positional workflow node selectors also fail source collection. All checks use the full population passed to admission, so invoke admission without -k, -m, or path narrowing.

Exact simulation lists and seed report

[[tool.pytest-admission.simulation_lists]]
path = "tests/simulation_list.txt"
format = "lines"

simulation_lists uses the same lines, toml and python declarations described above, but every entry must equal a collected node ID exactly. Patterns and parent selectors admit nothing except their literal ID; an entry naming no item fails. The existing inline simulation_list still accepts shell-style patterns. Neither form disables runtime sink refusal.

pytest-admission simulation-bearing --root .
pytest-admission record --root .
pytest-admission check --root . --base <review-base>

The first command prints only the walk's simulation-bearing IDs, sorted and one per line. It collects without running fixtures or bodies, runs no contract, list, selection or count checks, and needs no existing list file or record. Collection/configuration errors exit 1 rather than producing a partial seed. Review that output before saving it as the initial list.

The record writer stores the total number of file entries as simulation_listed (duplicates count as entries, including across files; inline patterns do not). The check requires that count to match the record and refuses a recorded count above the review-base record. Removing entries therefore requires lowering the record in the same change. The writer refuses to increase an existing count. Pre-0.2.0 records without the field can be initialized by the writer.

Metadata

Release files for pytest-admission 0.2.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-admission 0.2.0
File Size Uploaded Provenance Actions
pytest_admission-0.2.0.tar.gz 37.2 kB With provenance Details for pytest_admission-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pytest-admission 0.2.0
File Interpreter ABI Platform Actions
pytest_admission-0.2.0-py3-none-any.whl Python 3 none any Details for pytest_admission-0.2.0-py3-none-any.whl

Total release size: 65.7 kB

Release files / pytest_admission-0.2.0.tar.gz

Download URL pytest_admission-0.2.0.tar.gz
Size 37.2 kB
Tags Source
SHA-256 checksum
How to use checksums
562711a937e613cb80a1e3c3ee6b2df1ad4163faf6f7b68f73401b39ce29adad
BLAKE2b-256 checksum
How to use checksums
cafec2b3febd104cba4f0957182662d374af29d60ae1e84139c6f2628ff74583
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 1, 2026.

Transparency log

Release files / pytest_admission-0.2.0-py3-none-any.whl

Download URL pytest_admission-0.2.0-py3-none-any.whl
Size 28.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a5b5272d31db03e72e7871d4aef121a28e337d8fee96dc4f6f407717b445f810
BLAKE2b-256 checksum
How to use checksums
8e4dc5595f1d8aad6a5624c416d86593fbfe118ccd67c30a0b61cf83770a3666
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 1, 2026.

Transparency log

Security for pytest-admission 0.2.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_admission-0.2.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 1, 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.

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