Skip to content

gh-136958: fix unittest.TestCase.assertLogs() to properly handle logging.NOTSET level #137555

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Lib/test/test_unittest/test_case.py
Original file line number Diff line number Diff line change
Expand Up @@ -1936,6 +1936,35 @@ def testAssertLogsWithFormatter(self):
self.assertEqual(cm.output, ["[No.1: the larch] INFO:foo:1"])
self.assertLogRecords(cm.records, [{'name': 'foo'}])

def testAssertLogsWithNOTSET(self):
# Check that logging.NOTSET level is handled correctly
# (not treated as falsey and defaulted to INFO)
with self.assertNoStderr():
with self.assertLogs(level=logging.NOTSET) as cm:
log_foo.info("1")
log_foobar.debug("2")
log_quux.error("3")
self.assertEqual(cm.output, ["INFO:foo:1", "DEBUG:foo.bar:2", "ERROR:quux:3"])
self.assertLogRecords(cm.records, [
{'name': 'foo', 'levelno': logging.INFO},
{'name': 'foo.bar', 'levelno': logging.DEBUG},
{'name': 'quux', 'levelno': logging.ERROR}
])

def testAssertNoLogsWithNOTSET(self):
# Check that logging.NOTSET level is handled correctly in assertNoLogs
# (not treated as falsey and defaulted to INFO)
with self.assertNoStderr():
with self.assertNoLogs(level=logging.NOTSET):
pass

with self.assertRaises(self.failureException) as cm:
with self.assertNoLogs(level=logging.NOTSET):
log_foo.debug("debug message")

self.assertIn("Unexpected logs found", str(cm.exception))
self.assertIn("DEBUG:foo:debug message", str(cm.exception))

def testAssertNoLogsDefault(self):
with self.assertRaises(self.failureException) as cm:
with self.assertNoLogs():
Expand Down
2 changes: 1 addition & 1 deletion Lib/unittest/_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class _AssertLogsContext(_BaseTestCaseContext):
def __init__(self, test_case, logger_name, level, no_logs, formatter=None):
_BaseTestCaseContext.__init__(self, test_case)
self.logger_name = logger_name
if level:
if level is not None:
self.level = logging._nameToLevel.get(level, level)
else:
self.level = logging.INFO
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
:meth:`unittest.TestCase.assertLogs` and :meth:`unittest.TestCase.assertNoLogs`
now correctly accept :data:`logging.NOTSET` as a valid level parameter instead
of treating it as falsey and defaulting to ``logging.INFO``.
Loading