0
0
PyTesttesting~10 mins

Asserting log messages in PyTest - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - pytest
PyTest
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)
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test startspytest test runner is ready-PASS
2Calls greet("Alice") inside caplog context at INFO levelLogger is set to capture INFO messages-PASS
3greet function logs message "Greeting Alice" at INFO levelLog record created with message and INFO level-PASS
4greet returns "Hello, Alice!"Function output availableCheck result equals "Hello, Alice!"PASS
5Assert log text contains "Greeting Alice"caplog.text contains captured logsVerify "Greeting Alice" in caplog.textPASS
6Assert at least one log record has level INFOcaplog.records list availableCheck any record.levelname == "INFO"PASS
7Test ends successfullyAll assertions passed-PASS
Failure Scenario
Failing Condition: The function does not log the expected message or logs at a different level
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test verify about the log messages?
AThat the log contains the message "Greeting Alice" at INFO level
BThat the log contains any message at DEBUG level
CThat no log messages are generated
DThat the log contains the message "Hello, Alice!"
Key Result
Always capture and assert log messages explicitly in tests to verify that important events are logged correctly, improving observability and debugging.