Fix nested caplog.filtering early removal#14284
Fix nested caplog.filtering early removal#14284oaksprout wants to merge 8 commits intopytest-dev:mainfrom
Conversation
Closes pytest-dev#14189 by checking if the filter is already present before adding or removing it.
for more information, see https://pre-commit.ci
themavik
left a comment
There was a problem hiding this comment.
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.
Closes #14189. Nested
caplog.filteringusage 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.