Skip to content
Back to skills

Pytest Knowledge Patch

ASecurity

pytest

  • 25 stars
  • 0 votes
  • 0 copies
  • 7 views
  • Added September 5, 2026
developmentpythonnodeexpressdebuggingapi

Works with

  • terminal
  • cli
  • api

Security analysis

A100/100

Pro scans all 8 files and shows the line behind each finding

Scanned December 1, 2026

npx -y skills add Nevaberry/nevaberry-plugins --skill pytest-knowledge-patch --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Pytest Knowledge Patch?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Pytest Knowledge Patch
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/nevaberry-pytest-knowledge-patch-nevaberry-plugins/badge)](https://www.skillsdirectory.com/skills/nevaberry-pytest-knowledge-patch-nevaberry-plugins)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: pytest-knowledge-patch
description: pytest
version: "9.2.0"
license: MIT
metadata:
  author: Nevaberry
---


# pytest knowledge patch

Load this skill when updating pytest tests, configuration, fixtures, plugins,
or reports. It covers compatibility changes, deprecations, and behavior details
for those tasks. Use the quick reference below, then read the relevant topic
file for complete conditions, examples, and historical behavior.

## Reference index

| Reference | Topics |
| --- | --- |
| [Migrations and deprecations](references/migrations-and-deprecations.md) | Invalid tests, fixture and plugin migrations, removal warnings, runtime dependencies, source builds |
| [Configuration and CLI](references/configuration-and-cli.md) | TOML, strictness, configuration types, terminal output, startup, stepwise runs, cache |
| [Collection, parametrization, and subtests](references/collection-parametrization-and-subtests.md) | Collection paths and nodes, parameter IDs, grouping, markers, doctests, subtests |
| [Fixtures, plugins, and hooks](references/fixtures-plugins-and-hooks.md) | Fixture scope and caching, finalizers, plugin loading, pytester, reporting hooks, runner packaging |
| [Assertions, exceptions, and logging](references/assertions-exceptions-and-logging.md) | Exception groups, xfail, assertion output, approximate comparisons, output and log capture |
| [Warnings and diagnostics](references/warnings-and-diagnostics.md) | Warning filters and limits, debugging, timeouts, test summaries, JUnit XML |

## Breaking changes and deprecations

- 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. Synchronous tests and async autouse
  fixtures can be affected.
- Class-scoped fixtures defined as instance methods are deprecated; this
  also extends to `module`, `package`, and `session` scopes. Move them to
  module level or use a class or static method when they belong on a class.
  The class-scoped fixture's instance is separate from the test instances.
- Place `@pytest.fixture` above `@classmethod` or `@staticmethod` in test
  classes. Pytest warns when an outer decorator prevents fixture discovery.
- Requesting a not-yet-requested fixture through `request.getfixturevalue()`
  during teardown is deprecated and will error in pytest 10. Declare a fixture
  dependency or request it during setup.
- Non-`Collection` iterables such as generators and iterators are deprecated
  as parametrization `argvalues`; use a collection such as a list.
- Pass parametrization `indirect`, `ids`, and `scope` by keyword. Passing
  them positionally raises `TypeError`.
- `@pytest.yield_fixture` is scheduled for removal in pytest 10 or 11.
  Use `@pytest.fixture` with `yield` for generator fixtures.
- Read registered options with `config.getini("option_name")`; the private
  `config.inicfg` attribute is deprecated.
- 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` where you previously passed `nodeid=None`.
- `FixtureDef.has_location` is deprecated and will be removed in pytest 10.
- Hook configuration through pytest marks is scheduled for removal in pytest
  10. Use implementation flags such as `@pytest.hookimpl(tryfirst=True)`.
- `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.
- An empty `@pytest.mark.usefixtures()` warns; a `usefixtures` mark inside
  `pytest.param(..., marks=...)` raises an error.

## Configuration and startup

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 the INI-compatible `[tool.pytest.ini_options]`.

```toml
[tool.pytest]
addopts = ["-ra", "-q"]
testpaths = ["tests", "integration"]
```

- `pytest -c PATH` raises a usage error for a missing path, a directory, or
  an unsupported format. In `pytest.toml` and `.pytest.toml`, top-level
  options without a `[pytest]` table raise an error.
- Native TOML accepts integers for the assertion truncation limits, warning
  limit, verbosity settings, retention count, logging levels, log indentation,
  and faulthandler timeout listed in the configuration reference. Existing
  string values work; `log_auto_indent` also accepts booleans.
- In `[tool.pytest.ini_options]`, quote options registered as strings.
  Non-string values emit `pytest.PytestRemovedIn10Warning` in 9.2 and will
  raise `TypeError` in pytest 10.
- `strict = true` or `--strict` enables `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`.
- With `strict_markers`, register every marker used in a `-m` expression,
  even when no test uses it. Duplicate parameter IDs are errors with
  `strict_parametrization_ids`, which can also be enabled independently.
- `config.getini()` raises `pytest.UsageError` for a configured value that
  fails its registered type, and `ValueError` for an unregistered option.
- `parser.addini()` accepts Python type expressions as well as existing
  string tags. With `aliases=`, the canonical setting wins if both names
  appear in a configuration file.
- `pytest_plugins` and `PYTEST_PLUGINS` accept installed plugin entry point
  names, as `-p` does; for example, `pytest_plugins = ["xdist"]`.
- A plugin specified via `-p`, `pytest_plugins`, or `PYTEST_PLUGINS` that
  cannot be found produces
  `pytest.ExitCode.USAGE_ERROR` (`4`). A plugin failing during import,
  including a missing dependency or broken `pytest11` entry point, produces
  a traceback and `pytest.ExitCode.INTERNAL_ERROR` (`3`).
- A single `pytest --version` prints the version before plugins load.
  Use `pytest --version --version` for plugin information; `--version` must
  be passed on the command line.

## Collection, parameters, and subtests

- Attach parameter selectors to test nodes: `pytest 'x.py::test_case[a]'`.
  A file-only selector such as `pytest x.py[a]` raises a usage error.
- Repeating `pytest x.py x.py` collects the file once; `--keep-duplicates`
  requests repeated file runs. Overlapping directory arguments collect the
  entire parent tree in either argument order.
- For auto-generated IDs of `str` and `bytes` values over 100 characters,
  `parametrize_long_str_id_strategy` defaults to `short` (argument name plus
  parameter index). `legacy` keeps the full value, `sha256` uses a SHA-256
  hex digest, and `disallow` requires an explicit ID.
- `@pytest.mark.parametrize("arg,", [(1,), (2,)])` unpacks the tuples into
  values `1` and `2`, following the same rules as argument names `("arg",)`.
- Above function scope, equal hashable parameter values group even across
  separate parametrization calls. This can change order and reduce fixture
  setups and teardowns. Unhashable values still group by parameter index.
- `-k` no longer matches incidental function attributes such as `pytestmark`
  and bookkeeping attributes from `functools.wraps` or `functools.lru_cache`.
  Select by the actual marker name or test name.
- Use `pytest.ParameterSet` for annotations and `isinstance()` checks on
  values returned by `pytest.param()`.

Use `subtests` for cases discovered during execution. Each `subtests.test(...)`
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 contexts under `pytest-xdist` can contain 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()
```

## Fixtures and plugin hooks

- With `--doctest-modules`, module-, package-, or session-scoped autouse
  fixtures in a test module can run twice if both tests and doctests collect
  that module. Move a fixture to `conftest.py` if it needs to run once for both.
- `pytest.register_fixture()` supports programmatic registration when
  declarative discovery is impractical. For definitions with the same name,
  a more specific collection node's definition wins over a general one even
  if the general one was registered later. Last registration wins for equal
  or incomparable visibility.
- Declare parametrized fixtures as test arguments or fixture dependencies
  so pytest can generate cases during collection. First requesting one through
  `request.getfixturevalue()` during execution reports a missing parameter.
- Pytester subprocesses load plugin names in `pytester.plugins` and reject
  non-string entries. Use names or `pytester.runpytest_inprocess()` for objects.
- Annotate fixture scope names with `pytest.ScopeName` and the terminal
  summary's `terminalreporter` argument with `pytest.TerminalReporter`.

## Assertions, output, and logging

- `@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 it matches every message;
  use `match="^$"` for an empty message.
- `pytest.approx` accepts `datetime` and `timedelta` values with an explicit
  `timedelta` tolerance: `abs=` for datetimes, `abs=` or `rel=` for durations.
- Mixed-type nested containers, such as a list of dictionaries, raise
  `TypeError` with `pytest.approx()`. Compare individual rows or fields.
- For `Decimal` comparisons, float tolerances can emit
  `pytest.PytestApproxDecimalToleranceWarning` when widened to the exact binary
  value of an inexact float. Use an exact tolerance such as `abs=Decimal("0.1")`.
- Use `pytest.Approx` for annotations and `isinstance()` checks on
  `pytest.approx()` results.
- `capteesys` captures Python stdout and stderr while forwarding them to the
  handler selected by `--capture=`. `pytest --capture=tee-sys` shows output live.
- Loggers with `propagate = False` are captured in `caplog` and captured-log
  reports. `caplog.set_level()` can override the fixture's capture level while
  a failure report's captured-log section still uses the configured threshold.
- Set `truncation_limit_lines` and `truncation_limit_chars` in `pytest.ini`
  for assertion truncation. `pytest -vvv` shows untruncated function arguments.

## Warnings, reports, and resuming runs

- `pytest --max-warnings=5` or `max_warnings = 5` fails a run emitting more
  than five warnings. Warning filters cover plugin imports, configuration
  hooks, and late cleanup; late unraisable or unhandled thread exceptions can
  fail a run when their warnings are errors.
- `pytest -vv --force-short-summary` keeps the final summary condensed.
  `console_output_style = times` shows each test's execution time.
- `--no-summary` suppresses pytest's own summary while still calling
  `pytest_terminal_summary`, so plugins can print their summaries.
- JUnit XML `<failure>` and `<error>` messages are shortened at whole-line
  boundaries within 500 characters. The element text contains the full report.
- Runs without `--stepwise` preserve its remembered failure. A changed
  collected test count resets it; `--stepwise-reset` (alias `--sw-reset`)
  resets it explicitly. `--stepwise-skip` enables stepwise mode and continues
  past the first failure; `--sw-skip` is its alias.
- `Cache.get()`, `Cache.set()`, and `Cache.mkdir()` reject keys resolving
  outside the cache directory; `--cache-show` skips outside matches too.

Files in this skill

  • SKILL.md8.8 KB
  • coverage.json516 B
  • references/assertions-exceptions-and-logging.md2.1 KB
  • references/collection-parametrization-and-subtests.md2.7 KB
  • references/configuration-and-cli.md3.3 KB
  • references/fixtures-plugins-and-hooks.md1.8 KB
  • references/migrations-and-deprecations.md2.9 KB
  • references/warnings-and-diagnostics.md1.7 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.