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 |