Metadata-Version: 2.5
Name: pytest-admission
Version: 0.1.0
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 still have their own collection-only
subprocesses. 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.

## Release

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

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

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.

Every session 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.

## 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 --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 an existing count.
It refuses an increase and leaves the file untouched on collection or
admission errors. JSON `gaps` (the selection-coverage record) is preserved.
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. Shell/workflow expressions in pytest arguments fail
closed; resolve those selections into literal commands. Workflow shell, test
bodies and launcher scripts are never executed by the check; collection does
import tests and conftests. Every source is collected in a fresh subprocess
with its paths, markers, deselections and plugin options intact.
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.

An unconditional `skip` or literal-true `skipif` fails collection.
Conditions may be positional or supplied as `condition=`; false boolean and
string-expression conditions are not classified as unconditional skips.
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 `python` (`field` naming
one module-level literal tuple/list, read by AST without importing it).
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.
