Complete worked example
python
import logging
logger = logging.getLogger("owned.counts")
def normalize_count(value):
if value < 0:
logger.warning("negative count: %s", value)
return 0
return value
def test_negative_count_warning(caplog):
with caplog.at_level(logging.INFO, logger="owned.counts"):
assert normalize_count(-1) == 0
records = [r for r in caplog.records if r.name == "owned.counts"]
assert [(r.levelname, r.getMessage()) for r in records] == [("WARNING", "negative count: -1")]- Reasoning
- The complete function logs a warning for negative counts and returns zero. caplog.at_level enables capture for the named logger during the call. The test filters records from that logger and checks the level and rendered message. caplog.records contains LogRecord objects; getMessage applies the message arguments. Formatter changes should not break this assertion because a timestamp or colour prefix is not part of the required diagnostic. The return value is asserted separately.