Skip to content

Fix nested caplog.filtering early removal#14284

Open
oaksprout wants to merge 8 commits intopytest-dev:mainfrom
oaksprout:fix-nested-caplog-filtering
Open

Fix nested caplog.filtering early removal#14284
oaksprout wants to merge 8 commits intopytest-dev:mainfrom
oaksprout:fix-nested-caplog-filtering

Conversation

@oaksprout
Copy link

Closes #14189. Nested caplog.filtering usage was eagerly removing filters when the inner context manager exited, even if the filter was already present from the outer context manager. This PR ensures the filter is only removed if it wasn't already present when the context manager was entered.

Closes pytest-dev#14189 by checking if the filter is already present before adding or removing it.
@psf-chronographer psf-chronographer bot added the bot:chronographer:provided (automation) changelog entry is part of PR label Mar 13, 2026
Copy link

@themavik themavik left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR fixes nested caplog.filtering() removing filters early when the same filter was already present.

Done well: The fix is minimal and correct: already_present = filter_ in self.handler.filters before add, and if not already_present guards both addFilter and removeFilter. This preserves the invariant that we only remove what we added. test_with_statement_filtering_already_present directly tests the bug scenario (filter pre-added, then used in a with block) and verifies the filter remains after context exit. test_with_statement_nested_filtering covers the nested case.

Note: The in check uses object identity, so two distinct filter instances with identical logic would both be added and both removed on exit. That matches typical usage where filters are single instances. Good fix.

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.

Nested caplog.filtering usage may remove filters early

2 participants