Unable to use `logging.NOTSET` with `assertLogs` or `assertNoLogs`
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
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.info("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 "INFO: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 https://github.com/element-hq/synapse/pull/18474) and wanting to write some tests for it.
CPython versions tested on:
3.13
Operating systems tested on:
Linux
Linked PRs
- gh-137555
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start in Lib/unittest/_log.py at the _AssertLogsContext conditional referenced in the issue. Reproduce the example with logging.NOTSET through assertLogs and assertNoLogs, then verify that both contexts accept the level without defaulting to INFO and that regression coverage exercises this behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- testing
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 25/100