Skip to content

Preserve warning filters set during collection for the test run - #14879

Open
arronKler wants to merge 3 commits into
pytest-dev:mainfrom
arronKler:fix/13485-warning-filters-collection
Open

Preserve warning filters set during collection for the test run#14879
arronKler wants to merge 3 commits into
pytest-dev:mainfrom
arronKler:fix/13485-warning-filters-collection

Conversation

@arronKler

Copy link
Copy Markdown

Summary

pytest_collection is wrapped in warnings.catch_warnings, so any warnings.filterwarnings() / simplefilter() calls made by collected modules or conftest.py were discarded when that context exited. The later per-test catching context then started from the pre-collection filters, which is why module-level filters had no effect during the run (regression of #2430, introduced when collection-time warning capture was added).

The existing test_works_with_filterwarnings did not catch this unless the suite was run with -Wdefault, because the in-process inner run inherited the outer suite's filterwarnings=error.

Solution

Remember filters that user code adds while the initial-conftest and collection catching contexts are active. Re-apply them (in front of pytest's configured filters) in later catching contexts, and promote them into the enclosing warnings context when those phases finish. @pytest.mark.filterwarnings is still applied after that, so marks keep precedence.

test_works_with_filterwarnings now runs in a subprocess with -Wdefault. Additional tests cover ignore filters from a collected module and from conftest.py.

Fixes #13485

  • Include documentation when adding new features.
  • Include new tests or update existing tests when applicable.
  • Allow maintainers to push and squash when merging my commits.
  • Add text like closes #XYZW / Fixes #13485.
  • Changelog: changelog/13485.bugfix.rst
  • Added myself to AUTHORS

Collection is wrapped in warnings.catch_warnings, so module-level
warnings.filterwarnings() calls were discarded when collection
finished and had no effect while tests ran. Keep those newly added
filters and re-apply them in later catching contexts.

Fixes pytest-dev#13485
@psf-chronographer psf-chronographer Bot added the bot:chronographer:provided (automation) changelog entry is part of PR label Aug 14, 2026
typeshed types warnings.filters as Sequence, but it is a mutable list
and we need to prepend filters persisted from collection.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:provided (automation) changelog entry is part of PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

warnings: warning filters set by collected code during collection have no effect during test run

1 participant