Test Overview
This test checks if a specific log message is generated during the execution of a function. It verifies that the log contains the expected text at the correct log level.
This test checks if a specific log message is generated during the execution of a function. It verifies that the log contains the expected text at the correct log level.
import logging import pytest logger = logging.getLogger(__name__) def greet(name): logger.info(f"Greeting {name}") return f"Hello, {name}!" def test_greet_logs_info(caplog): with caplog.at_level(logging.INFO): result = greet("Alice") assert result == "Hello, Alice!" assert "Greeting Alice" in caplog.text assert any(record.levelname == "INFO" for record in caplog.records)
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | pytest test runner is ready | — | PASS |
| 2 | Calls greet("Alice") inside caplog context at INFO level | Logger is set to capture INFO messages | — | PASS |
| 3 | greet function logs message "Greeting Alice" at INFO level | Log record created with message and INFO level | — | PASS |
| 4 | greet returns "Hello, Alice!" | Function output available | Check result equals "Hello, Alice!" | PASS |
| 5 | Assert log text contains "Greeting Alice" | caplog.text contains captured logs | Verify "Greeting Alice" in caplog.text | PASS |
| 6 | Assert at least one log record has level INFO | caplog.records list available | Check any record.levelname == "INFO" | PASS |
| 7 | Test ends successfully | All assertions passed | — | PASS |
caplog fixture in pytest when testing log messages?caplogcaplog fixture is designed to capture log messages during pytest test runs.caplog captures logs [OK]caplog in pytest?caplog.set_level(logging.WARNING) sets the capture level to WARNING, capturing WARNING and above.import logging
def test_log_message(caplog):
with caplog.at_level(logging.ERROR):
logging.error('Error occurred')
assert 'Error occurred' in caplog.textcaplog.text, which contains all captured logs as text.caplog to assert a log message:
import logging
def test_info_log(caplog):
logging.info('Info issued')
assert 'Info issued' in caplog.textcaplog to capture INFO level logs, so no logs are captured.caplog.text is empty and the assertion fails.caplog assertion correctly verifies this?caplog.records is a list of log record objects with attributes like message and levelname.Pass the test and this pattern moves unknown