Skip to content

Conversation

@Yuheng3107
Copy link
Contributor

@Yuheng3107 Yuheng3107 commented Jan 17, 2026

Closes #89900

Description

The Problem

At the moment, assertLogs removes the handlers attached to the logger. In general this is good, because it reduces message spamming in the test logs. However, if the code being tested is relying on a handler to do something, then the test fails because the handler is being removed. This leads to the situation that the same exact test must be run twice:

  • first time within the context manager, to assert that specific messages were logged (using with self.assertLogs())
  • second time, without the assertLogs to ensure the code that uses a handler does the right thing

The Fix

Added optional keep_handlers param in assertLogs inside Lib/unittest/case.py to optionally preserve existing handlers for assertLogs, preventing the situation described above where the same exact test must be run twice

Since keep_handlers is False by default, this change is backwards-compatible.

Tests

Added new test cases in Lib/test/test_unittest to ensure keep_handlers=True preserves existing handlers.

Validation

Ran ./python.exe -m test test_unittest and passed all 1093 tests


📚 Documentation preview 📚: https://cpython-previews--143970.org.readthedocs.build/

…tLogs

added documentation for new keep_handlers kwarg for assertLogs function in unittest
@Yuheng3107
Copy link
Contributor Author

@vsajip Could you review this PR when you have time? Thanks so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

assertLogs to optionally not disable existing handlers

1 participant