Skip to content

Unable to use logging.NOTSET with assertLogs or assertNoLogs #136958

@MadLittleMods

Description

@MadLittleMods

Bug report

Bug description:

Since logging.NOTSET equals 0 (a falsey value), the naive conditional check in _AssertLogsContext prevents it from being used as a valid level parameter with unittest.TestCase.assertLogs() or unittest.TestCase.assertNoLogs().

Example:

import logging
import unittest


class LoggerTestCase(unittest.TestCase):
    def test_logging(self):
        root_logger = logging.getLogger()
        root_logger.setLevel(logging.ERROR)

        logger = logging.getLogger("foo")

        with self.assertLogs(logger=logger, level=logging.NOTSET) as cm:
            logger.debug("first message")
            logger.error("second message")
            # This test currently fails because `assertLogs(...)` sees the falsey
            # `logging.NOTSET` and sets the level to `logging.INFO` by default; so we
            # end up seeing the "DEBUG:foo:first message" in the output.
            self.assertEqual(cm.output, ["ERROR:foo:second message"])

In my real life use case, the logging.NOTSET interaction is useful in context of creating a custom class ExplicitlyConfiguredLogger(logging.Logger) that only logs when the logger is configured with something other than logging.NOTSET (used in element-hq/synapse#18474) and wanting to write some tests for it.

CPython versions tested on:

3.13

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-bugAn unexpected behavior, bug, or error

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions