Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Pytest Knowledge Patch?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/nevaberry-pytest-knowledge-patch)
---
name: pytest-knowledge-patch
description: pytest
version: "9.2.0"
license: MIT
metadata:
author: Nevaberry
---
# Pytest compatibility guidance
Load this skill when updating pytest tests, configuration, fixtures, or plugins,
or diagnosing collection, assertion, capture, and reporting behavior.
Use the topic references for complete guidance and version-specific details.
| Reference | Topics |
| --- | --- |
| [Migrations and deprecations](references/migrations-and-deprecations.md) | Invalid tests, fixture and parametrization deprecations, removed APIs, hook migrations, optional imports |
| [Configuration and execution](references/configuration-and-execution.md) | TOML, strictness, warnings, collection, caching, logging, debugging, JUnit XML, runtime requirements |
| [Assertions and parametrization](references/assertions-and-parametrization.md) | Parameter IDs and scopes, subtests, expected failures, exception and warning assertions, approximate comparisons, diffs |
| [Plugin and fixture APIs](references/plugin-and-fixture-apis.md) | Typed settings, plugin loading, fixture registration and finalization, collection nodes, markers, hooks, pytester |
## Breaking changes and deprecations
### Test functions and fixture requests
Async tests fail without a suitable plugin. Tests returning a non-`None` value
fail, and a `yield` in a test function produces an explicit error.
Requesting an async fixture emits `DeprecationWarning` unless a
`pytest_fixture_setup` hook resolves it; this can affect synchronous tests and
async autouse fixtures.
An empty `@pytest.mark.usefixtures()` emits a warning. A `usefixtures` mark
passed to `pytest.param(..., marks=...)` raises an error.
Calling `request.getfixturevalue()` during teardown for a fixture that has yet
to be requested is deprecated and will raise an error in pytest 10. Declare
the fixture as a dependency or request it during setup.
Class-, module-, package-, and session-scoped fixtures defined as instance
methods are deprecated. Move them to module level or use a class or static
method when they belong on a class. A class-scoped fixture's instance is
separate from the instances used by tests; use `@classmethod` to work with
the test class. Put `@pytest.fixture` above `@classmethod` or `@staticmethod`.
Pytest warns when an outer decorator prevents fixture discovery.
`@pytest.yield_fixture` is scheduled for removal in pytest 10 or 11.
Use `@pytest.fixture` with `yield` for generator fixtures.
With `--doctest-modules`, module-, package-, or session-scoped autouse fixtures
in a test module can run twice if it is collected for tests and doctests.
Move the fixture to `conftest.py` if it needs to run once for both.
### Parametrization and selection
Pass `indirect`, `ids`, and `scope` by keyword to `Metafunc.parametrize()` and
`@pytest.mark.parametrize`; positional arguments in these slots raise
`TypeError`. Generators, iterators, and other non-`Collection` iterables as
`argvalues` are deprecated; use a collection such as a list.
```python
import pytest
@pytest.mark.parametrize("value", [1], ids=["one"], scope="module")
def test_positive(value):
assert value > 0
```
A parameter suffix on a file argument, such as `pytest x.py[a]`, raises a
usage error. Attach it to a test node: `pytest 'x.py::test_case[a]'`.
`-k` no longer matches incidental function attributes such as `pytestmark`
or bookkeeping attributes from `functools.wraps` and `functools.lru_cache`.
Select by actual marker name or test name.
### Plugin migrations
- Replace reads of the private `config.inicfg` with `config.getini("option_name")` for registered options.
- Passing `baseid` to `FixtureDef` or a `nodeid` string to fixture registration APIs is deprecated and will be removed in pytest 10. Pass the collection node as `node=`, or `node=session` for the former `nodeid=None` case.
- Hook configuration through pytest marks is scheduled for removal in pytest 10; use `@pytest.hookimpl`, for example `@pytest.hookimpl(tryfirst=True)`.
- The private `FixtureDef.has_location` is deprecated and will be removed in pytest 10.
- `pytest.console_main()` is deprecated and will be removed in pytest 10; use `pytest.main(["-q"])` to run pytest from Python.
- Switch private `_pytest.python.CallSpec2` imports to `_pytest.python.CallSpec`; the old name remains an alias until removal in pytest 10 or 11.
- The built-in `--pastebin` option is deprecated; `pytest-pastebin` provides the same functionality.
### Configuration and import failures
`pytest -c PATH` raises a usage error for a missing path, a directory, or an
unloadable format. A non-regular source such as `/dev/null` no longer sets
`rootdir` from its location.
In `[tool.pytest.ini_options]`, quote options registered as strings: a
non-string emits `pytest.PytestRemovedIn10Warning` in 9.2 and will raise
`TypeError` in pytest 10.
`config.getini()` raises `pytest.UsageError` for a configured value that fails
its registered type and `ValueError` for an unregistered option name.
The CLI and `pytest.main()` return `pytest.ExitCode.USAGE_ERROR` (`4`) for a
plugin named through `-p`, `pytest_plugins`, or `PYTEST_PLUGINS` that cannot
be found. A plugin that fails while importing, including a missing dependency
or broken `pytest11` entry point, produces a traceback and
`pytest.ExitCode.INTERNAL_ERROR` (`3`).
## Configuration and strictness
Use `[tool.pytest]` in `pyproject.toml`, or `[pytest]` in `pytest.toml` or
`.pytest.toml`, for native TOML types. In `pyproject.toml`, choose one of
`[tool.pytest]` and `[tool.pytest.ini_options]`.
```toml
[tool.pytest]
addopts = ["-ra", "-q"]
testpaths = ["tests", "integration"]
```
With `pytest -c custom.toml`, use `[pytest]`, `[tool.pytest]`, or
`[tool.pytest.ini_options]`. Top-level options in `pytest.toml` and
`.pytest.toml` without `[pytest]` raise an error.
Native TOML accepts integer logging levels and verbosity settings; existing
string values still work. `log_auto_indent` also accepts booleans. The full
list of numeric settings is in the configuration reference.
Set `strict = true` or pass `--strict` to enable `strict_config`,
`strict_markers`, `strict_parametrization_ids`, and `strict_xfail`.
Individual settings override the global setting; future strictness checks
are included automatically. `strict_xfail` aliases `xfail_strict`.
`strict_parametrization_ids` can independently make duplicate IDs an error.
With `strict_markers`, register every marker used in a `-m` expression:
`pytest --strict-markers -m 'not slow'` requires `slow` even if no test uses it.
## Parametrization and subtests
For auto-generated IDs of `str` and `bytes` values over 100 characters,
`parametrize_long_str_id_strategy` defaults to `short`, using the argument
name plus parameter index. Use `legacy` for the full value, `sha256` for a
SHA-256 hex digest, or `disallow` to require `ids=[...]` or
`pytest.param(..., id=...)`.
`@pytest.mark.parametrize("arg,", [(1,), (2,)])` unpacks the tuples into `arg`,
passing `1` and `2`, like `("arg",)` as the argument names.
Above function scope, equal hashable values group even across separate
parametrization calls. This can change order and reduce fixture setups and
teardowns; unhashable values still group by parameter index.
Use `subtests` for cases discovered during execution. Each block reports its
own failure or error and lets the surrounding test continue.
`unittest.TestCase.subTest` is also supported. The failure-report format is
experimental. Subtest context values under `pytest-xdist` can include objects
that cannot be JSON-serialized.
```python
import pytest
def test_names(subtests: pytest.Subtests):
for name in ("alpha", "beta"):
with subtests.test(name=name):
assert name.isalpha()
```
## Assertion and exception helpers
`@pytest.mark.xfail(raises=pytest.RaisesGroup(ValueError))` expects a group
containing one `ValueError`. `raises=` also accepts `pytest.RaisesExc`, which
can apply a `check=` predicate to an individual exception.
`pytest.raises(..., match="")` warns because the pattern matches every
message. Use `match="^$"` for an empty message; an anchored pattern such as
`"^" + re.escape(expected) + "$"` produces a string diff on mismatch.
`pytest.approx` accepts `datetime` and `timedelta` values with an explicit
`timedelta` tolerance: use `abs=` for datetimes and `abs=` or `rel=` for durations.
```python
from datetime import datetime, timedelta
import pytest
expected = datetime(2026, 6, 13, 12)
actual = expected + timedelta(milliseconds=2)
assert actual == pytest.approx(expected, abs=timedelta(milliseconds=5))
```
Mixed-type nested containers, such as a list of dictionaries, raise
`TypeError` in `pytest.approx()` too; compare individual rows or fields.
For `Decimal` comparisons, an inexact float tolerance can emit
`pytest.PytestApproxDecimalToleranceWarning` when widened to its exact binary
value. Pass an exact decimal tolerance, such as `abs=Decimal("0.1")`.
## Capture, warnings, and reports
`capteesys` captures Python stdout and stderr while forwarding them to the
handler selected by `--capture=`. Run this with `pytest --capture=tee-sys`
to see the line live and assert on it:
```python
def test_output(capteesys):
print("ready")
assert capteesys.readouterr().out == "ready\n"
```
- `pytest -vv --force-short-summary` keeps the short summary condensed at high verbosity.
- `console_output_style = times` under `[pytest]` shows each test's execution time.
- `truncation_limit_lines` and `truncation_limit_chars` configure assertion truncation; `pytest -vvv` shows untruncated function arguments in assertion explanations.
- `assertion_text_diff_style` can show failed string equality as separate `Left:` and `Right:` blocks.
- `pytest --max-warnings=5` or `max_warnings = 5` fails a run with more than five warnings.
- `caplog` and captured-log reports capture records from loggers with `propagate = False`.
- Plugin import warnings through `-p`, `PYTEST_PLUGINS`, or entry point autoloading are captured and filtered. Configured warning filters also apply to `pytest_configure` warnings.
- `--no-summary` suppresses pytest's own summary and still runs `pytest_terminal_summary`, so plugins can print their summaries.
## Fixture and plugin APIs
Use `pytest.register_fixture()` for programmatic registration when declarative
discovery is impractical. For same-name registrations, visibility from a more
specific collection node wins even if a general definition was registered
later. The last registration wins when visibility is equal or incomparable.
`parser.addini()` accepts `str`, `bool`, `int`, `float`, string `Literal` types,
and their unions as `type=`; existing string tags remain supported.
Pass `aliases=` when renaming a setting; the canonical name wins if both are set.
`pytest_plugins` and `PYTEST_PLUGINS` accept installed plugin entry point names,
as `-p` does, for example `pytest_plugins = ["xdist"]`.
Use `pytest.ParameterSet` and `pytest.Approx` for annotations and `isinstance()`
checks on `pytest.param()` and `pytest.approx()` results, respectively.
`pytest.ScopeName` annotates fixture scope names, and `pytest.TerminalReporter`
annotates the `terminalreporter` argument of `pytest_terminal_summary`.