python / python/cpython

Unable to use `logging.NOTSET` with `assertLogs` or `assertNoLogs`

Aperta
#136,958 3 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

pending stdlib
Lingua principale
Python
Stelle
77.2k
Fork
35.9k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia in Lib/unittest/_log.py, nella condizione _AssertLogsContext indicata nell’issue. Riproduci l’esempio con logging.NOTSET tramite assertLogs e assertNoLogs, quindi verifica che entrambi i contesti accettino il livello senza impostare INFO come valore predefinito e che la copertura della regressione eserciti questo comportamento.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
testing
Tipo di issue
Bug
Difficoltà
2/5
Tempo stimato
1-3 ore
Stato di attività
Ferma
Chiarezza
Specificata chiaramente
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.