pypi / pytest
pytest
What changed in pytest 8 to 9, from its official release notes, upgrade guides and advisories. Sources checked 2026-11-30.
28 breaking1 security17 deprecations19 new APIs and options3 performance22 behavior and defaults2 tooling45 fixes and other
See which of these apply to your code, ranked, in your agent:
npx @unstale/cli initpytest 9135 changes
Breaking changes 28
A nonexistent path, directory, or unsupported format now produces a usage error instead of being ignored or causing an unhandled FileNotFoundError.
TOML files passed via -c now read configuration from [pytest]; existing [tool.pytest] and [tool.pytest.ini_options] styles remain supported, but mixing styles is an error.
Cache keys resolving outside the cache directory are rejected.
A registered option whose configured value does not match its type now raises UsageError rather than TypeError or ValueError.
An implicit destination that conflicts with an existing option now produces a clear error instead of silently overriding it.
Tests are reordered by parameter value rather than index, grouping equal values to share fixture setup; test order may change and unhashable values retain index-based grouping.
Accepted values are registered; invalid values now produce a usage error, and pytest --help lists accepted values.
Invalid values are now reported as a usage error.
The indirect, ids, and scope arguments are now keyword-only; positional use fails with a TypeError.
The flag suppresses only pytest's own summary and no longer skips the pytest_terminal_summary hook, allowing plugins to write summaries.
The method now stores a Mark in node.keywords, matching marks applied during collection, rather than storing a MarkDecorator.
pluggy>=1.6 is now required; older versions could leave the logging plugin's wrapper suspended and cause a subsequent test's caplog to see no records.
Infinite relative tolerances for datetime.timedelta values now raise a clear ValueError instead of OverflowError.
Nested containers of any type now raise TypeError rather than being accepted and silently compared without applying tolerance.
Plugin import failures are classified as usage or internal errors, and pytest.main returns the corresponding exit codes instead of raising ImportError.
Top-level options now raise an error when no [pytest] table is present instead of being silently ignored.
Unmatched warnings are no longer re-emitted with module="warnings", so module-based warning filters are applied using the warning filename.
Building pytest from a git checkout now requires setuptools-scm >= 10.1.
Autouse fixtures with module, package, or session scope defined inline in Python test modules may execute twice when doctest modules are enabled.
Fixture overrides are resolved first by visibility in the collection tree, so a more specific node takes precedence over a more general node regardless of registration order.
Unraisable exceptions from finalizers are collected during
pytest_unconfigurebefore session warning filters are torn down, so matching error filters promote them to failures regardless of plugin cleanup order.It is no longer considered an interactive exception, so
pytest_exception_interactis no longer called for it.Disallows blocking a
conftest.pyfile and raises a clearUsageErrorexplaining that conftest files are not plugins and cannot be disabled via-p.CI mode is activated only when
CIorBUILD_NUMBERis defined and has a non-empty value.A file argument with parametrization syntax is now reported as a usage error instead of silently being treated as the file path.
Warnings of this type now raise errors by default; affected features are slated for removal in pytest 9.1.
pytest no longer supports Python 3.9.
A single
--versionno longer loads the plugin infrastructure; passing it twice retains the behavior of showing pytest and plugin information. It only works when passed directly on the command line.
Security 1
Fixes the use of an insecure temporary directory.
Deprecations 17
The private name has been renamed to CallSpec; the old alias remains temporarily and is scheduled for removal in pytest 10 or 11.
Module-, package-, and session-scoped fixtures defined as instance methods are deprecated.
Pytest warns when a decorator prevents correct fixture discovery, including classmethod or staticmethod above pytest.fixture.
Passing a non-string value to a string-typed ini option in pyproject.toml now warns; pytest 10 will raise TypeError.
Passing bytes is deprecated; pass a str instead.
The yield_fixture decorator is scheduled for removal in pytest 10 or 11.
Class-scoped fixtures defined as instance methods without
@classmethodnow emit a deprecation warning; use@classmethodinstead.The private
config.inicfgattribute is deprecated; useconfig.getini()to access configuration values.Passing
nodeidstrings to fixture registration APIs is deprecated; use thenodeparameter for fixture scoping.Passing
baseidtoFixtureDefis deprecated; use thenodeparameter for fixture scoping.The private
FixtureDef.has_locationattribute is deprecated and will be removed in pytest 10.Configuring hooks using markers, deprecated since pytest 7.2, is now scheduled for removal in pytest 10.
The option is deprecated; the same functionality is available in the external
pytest-pastebinplugin.This function is deprecated and will be removed in pytest 10; use
pytest.maininstead.Type checkers now recognize
yield_fixtureas deprecated through thedeprecateddecorator.The attribute will be deprecated in pytest 9.1 and removed in pytest 10.
Prints a warning when configuration is spread over more than one file, clarifying that only one is used.
New APIs and options 19
Controls handling of long str and bytes values in generated test IDs; supports short, sha256, legacy, and disallow strategies.
Exposed as the return type of pytest.approx for type annotations and isinstance checks.
Exposed as the return type of pytest.param for type annotations and isinstance checks.
Adds a setting to render string equality failures as separate
Left:andRight:blocks instead ofndiffoutput.Adds a command-line threshold that fails the test run when the number of warnings exceeds the given value.
Adds a configuration threshold that fails the test run when the number of warnings exceeds the given value.
Supports comparisons with
datetimeandtimedelta; datetime comparisons require an explicit absolute or relative tolerance as atimedelta, and relative tolerance is unsupported.Adds an imperative interface for registering fixtures, intended for plugins where declarative registration is cumbersome or unviable.
The callable overload uses
ParamSpecinstead ofAnyfor type hints, andfunccan now be passed as a keyword argument.Adds
pytest.tomlas a separate native TOML configuration file.Adds
.pytest.tomlas a separate native TOML configuration file.Adds a configuration option that enables
strict_config,strict_markers,strict_parametrization_ids, andstrict_xfail; individual options can override it.Adds
strict_configas a configuration option alias for the--strict-configflag.Adds
strict_markersas a configuration option alias for the--strict-markersflag.When enabled, emits an error for non-unique parameter set IDs instead of automatically making them unique.
Adds
strict_xfailas an alias toxfail_strict.Adds subtests as an alternative to parametrization when values are not all known at collection time; failures are reported individually. The feature is experimental.
Adds native TOML configuration in the
[tool.pytest]table ofpyproject.toml; it cannot be used alongside[tool.pytest.ini_options].pytest now supports unittest subTest.
Performance 3
Default fd-level output capturing skips reading the capture buffer for tests that produce no output, reducing per-test overhead.
Temporary directory allocation no longer lists the whole base directory on each call; per-prefix counters skip names that already exist.
Quadratic-time behavior when handling unittest subtests in Python 3.10 was fixed.
Behavior and default changes 22
Large diffs are built lazily and capped to the truncation budget; the truncation footer no longer gives the exact number of hidden lines.
Assertion diffs for dict.items() and dict.keys() comparisons now identify missing items, as set comparisons do.
RecursionError tracebacks whose origin cannot be located show only the first and last 10 frames by default; this flag shows every frame.
The option now accepts native integer and boolean values in TOML configuration files while continuing to accept strings.
The default argument now accepts a MarkDecorator and returns its wrapped Mark.
The type argument now accepts Python type expressions, string Literals, and unions, in addition to existing string tags.
Warnings emitted while importing plugins through -p, PYTEST_PLUGINS, or entry point autoloading are captured, filtered, and reported like other warnings.
Cached rewritten modules are invalidated using a source hash and checked-hash pyc format rather than modification times, allowing caches to survive fresh checkout timestamps.
The variable now accepts installed plugin entry point names as well as importable module names.
The environment variable now accepts installed plugin entry point names as well as importable module names.
A warning is emitted when a float tolerance cannot be represented exactly for a Decimal comparison.
When strict_markers is enabled, marker names in -m expressions are validated against registered markers.
The option now accepts native integer values in TOML configuration files while continuing to accept strings.
Pytest no longer formats tracebacks for tests marked xfail(run=False).
Help and error messages identify
pytest,python -m pytest, orpytest.main()according to how pytest was invoked.Output excludes internal-implementation fixtures generated by
@pytest.mark.parametrizeand similar.When warnings were emitted but the match pattern did not match, the message now says “Regex pattern did not match” instead of “DID NOT WARN”.
A
PytestCollectionWarningis emitted when module-level__getattr__returnsNoneforpytestmark; collection then continues normally.Output now prints a space after the test name and any listed fixtures to separate them from the test result.
The default number of
gc.collect()passes is reduced from five to one on CPython; PyPy retains five passes.Terminal progress is disabled by default except on Windows; enable it with -p terminalprogress.
The previously-deprecated flag now enables strict mode.
Tooling 2
Assertion diffs for dict.items() and dict.keys() comparisons now identify missing items, as set comparisons do.
GitHub source archives of arbitrary commits can now build into an sdist or wheel with a correct version; the file carries the describe output needed by setuptools-scm.
Fixes and other changes 43
Walrus expressions are no longer evaluated more than once during rewriting, preserving Python's left-to-right evaluation and reported values.
Glob matches outside the cache directory are ignored.
With the times style, durations just below a unit boundary are displayed in the next unit.
tryshort=True now strips the AssertionError prefix for failed assert statements in ExceptionInfo objects created by pytest.raises.
Fixture argument discovery is fixed for custom collectors that pass bound methods to pytest.Function.
Failure and error element message attributes are shortened to whole lines within 500 characters, with a note pointing to the full report in the element text.
The option no longer matches incidental attributes in a test function's __dict__ that are not intended as keywords.
Mapping diff key matching follows the mappings' own key equivalence, avoiding false missing-key reports for mappings such as case-insensitive header mappings.
Undoing a patch to an inherited instance attribute no longer creates an instance dictionary entry that shadows the class attribute.
A non-sequence parameter set now produces a clear collection error instead of crashing.
Cache writes now emit this warning when writing or closing the cache file fails.
The root directory is no longer derived from a configuration file that is not a regular file.
Restored loading files under
<invocation dir>/test*as initial conftests when pytest is invoked without arguments, so hooks in those files can run.Fixed mypy list-item typing errors for the argvalues parameter.
Fixed incorrect match messages that could pair an exception with the wrong error.
Logging capture now works for non-propagating loggers, not only logs that reach the root logger.
Fixes doubled output when
capteesysis used with--capture=no(-s).Fixes duplicated
-Woption values inConfig.known_args_namespace.Fixture values are released more promptly when a test is interrupted by
KeyboardInterruptor early exit.High Unicode supplementary-plane characters, such as emoji, are no longer incorrectly escaped in test failure messages.
An exception from this hook no longer prevents fixtures from being torn down, avoiding additional errors in following tests.
Recognizes types with
__array_interface__as numpy-like arrays.A trailing-comma single argument name such as
"arg,"now unpacks single-element tuple values like("arg",).The callable overload uses
ParamSpecinstead ofAnyfor type hints, andfunccan now be passed as a keyword argument.Assertion verbosity is propagated so the
-vhint in match-diff output works.Adds official support for Python 3.15.
Fixes a regression where
--strict-configspecified throughaddoptswas silently ignored.Fixes a regression where
--strict-markersspecified throughaddoptswas silently ignored.Autouse fixtures defined inside a skipped or
skipIf-decorated test case no longer run.The short form of
--versionnow displays the current version correctly.Correctly takes mapping key order into account when comparing mappings.
Fixes a crash when a test raises an exception group with
__tracebackhide__ = True.Non-string messages passed to
subTest()are now printed.The private attribute is restored to working order with a compatibility shim after a breaking change in pytest 9.0.0.
When TERM is dumb, pytest no longer emits escape codes, even if the terminal progress plugin is enabled.
Fixes a UserWarning on some earlier Python 3.12 and 3.13 point versions.
The plugin is automatically disabled when iTerm2 is detected because it generated desktop notifications instead of the desired functionality.
Raising unittest.SkipTest once again skips tests.
Fixes teardown handling for an
ExceptionGroupcontaining only skipped exceptions, which previously appeared as an error.Improves assertion and error messages when comparing mappings with differing lengths or keys.
Hidden
.pytest.inifiles are now selected as the configuration file even when empty.Type annotations for
pytest.skipand related functions are more spec-compliant to work across more type checkers.A filter referencing a class that cannot be imported now produces a message instead of failing.
pytest 82 changes
Fixes and other changes 2
Avoids microseconds exceeding 1_000_000 when the date format uses the
%fspecifier, preventing the test suite from crashing.The reason of a skip mark is now properly escaped when writing JUnit XML files.