Test Overview
This test checks if a function logs the expected messages using pytest's caplog fixture. It verifies that the log contains a specific info message.
This test checks if a function logs the expected messages using pytest's caplog fixture. It verifies that the log contains a specific info message.
import logging import pytest logging.basicConfig(level=logging.INFO) def greet(name): logging.info(f"Greeting {name}") return f"Hello, {name}!" def test_greet_logs(caplog): with caplog.at_level(logging.INFO): result = greet("Alice") assert result == "Hello, Alice!" assert "Greeting Alice" in caplog.text
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | pytest test runner initialized | — | PASS |
| 2 | Function greet("Alice") is called inside caplog context at INFO level | Logging system captures INFO messages | — | PASS |
| 3 | greet logs message: 'Greeting Alice' | Log record with message 'Greeting Alice' stored in caplog | — | PASS |
| 4 | Function greet returns 'Hello, Alice!' | Return value captured in variable result | assert result == 'Hello, Alice!' | PASS |
| 5 | Check if 'Greeting Alice' is in captured logs | caplog.text contains logged messages | assert 'Greeting Alice' in caplog.text | PASS |
| 6 | Test ends | All assertions passed | — | PASS |
caplog in pytest tests?caplog to capture only WARNING level logs in a test function?at_level() to set the log level temporarily.with caplog.at_level(logging.WARNING): to capture warnings.import logging
def test_log_message(caplog):
with caplog.at_level(logging.INFO):
logging.info('Test started')
assert 'Test started' in caplog.textimport logging
def test_error_log(caplog):
caplog.at_level(logging.ERROR)
logging.error('An error occurred')
assert 'An error occurred' in caplog.textcaplog to check this behavior?Pass the test and this pattern moves unknown