Metadata-Version: 2.5
Name: pytest-admission
Version: 0.2.1
Summary: Project-configured admission checks for pytest
License: MIT License
        
        Copyright (c) 2026 Daniel Lassiter
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Classifier: Framework :: Pytest
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.11
Requires-Dist: pytest<10,>=8.3.4
Requires-Dist: pyyaml>=6
Provides-Extra: test
Requires-Dist: pytest<10,>=8.3.4; extra == 'test'
Description-Content-Type: text/markdown

# 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

```sh
python -m pip install pytest-admission
```

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

```sh
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

```sh
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.1 is released by pushing tag `v0.2.1` 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:

```toml
[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.

Version 0.2.1 preserves each refused callable's original identity, including its
wrapped reference. Calls to a sink through a helper in the sink's own module
therefore remain simulation-bearing while collection has the refusal armed.
The refusal still fails without invoking the original callable.

## Contract admission

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

```toml
[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.

```sh
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:

```toml
[[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

```toml
[[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.

```sh
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.
