0
0
PyTesttesting~10 mins

caplog for log messages in PyTest - Test Execution Trace

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

Test Code - pytest
PyTest
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
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test startspytest test runner initialized-PASS
2Function greet("Alice") is called inside caplog context at INFO levelLogging system captures INFO messages-PASS
3greet logs message: 'Greeting Alice'Log record with message 'Greeting Alice' stored in caplog-PASS
4Function greet returns 'Hello, Alice!'Return value captured in variable resultassert result == 'Hello, Alice!'PASS
5Check if 'Greeting Alice' is in captured logscaplog.text contains logged messagesassert 'Greeting Alice' in caplog.textPASS
6Test endsAll 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 caplog fixture capture during the test?
AReturn values of functions
BExceptions raised in the test
CLog messages emitted during the test
DTest execution time
Key Result
Use caplog to verify that your code logs important messages correctly. This helps catch issues early by checking logs during tests.