diff --git a/Lib/test/test_unittest/test_case.py b/Lib/test/test_unittest/test_case.py index cf10e956bf2bdc..9e380caaf3c037 100644 --- a/Lib/test/test_unittest/test_case.py +++ b/Lib/test/test_unittest/test_case.py @@ -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(): diff --git a/Lib/unittest/_log.py b/Lib/unittest/_log.py index 3d69385ea243e7..fcda134b31f088 100644 --- a/Lib/unittest/_log.py +++ b/Lib/unittest/_log.py @@ -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 diff --git a/Misc/NEWS.d/next/Library/2025-08-08-00-55-24.gh-issue-136958.A7bX9z.rst b/Misc/NEWS.d/next/Library/2025-08-08-00-55-24.gh-issue-136958.A7bX9z.rst new file mode 100644 index 00000000000000..3615d3fce2d4f4 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-08-08-00-55-24.gh-issue-136958.A7bX9z.rst @@ -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``.