0
0
PyTesttesting~15 mins

caplog for log messages in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify log messages using caplog in pytest
Preconditions (2)
Step 1: Run the function that generates log messages
Step 2: Capture the log messages using the caplog fixture
Step 3: Check that the expected log message appears in the captured logs
✅ Expected Result: The expected log message is found in the captured logs during the test run
Automation Requirements - pytest
Assertions Needed:
Assert that the expected log message is present in caplog.text
Assert the log level of the captured message if applicable
Best Practices:
Use caplog fixture parameter in the test function
Set caplog level explicitly if needed
Avoid hardcoding log message substrings; use exact or partial matching carefully
Automated Solution
PyTest
import logging
import pytest

# Function to test

def greet(name):
    logger = logging.getLogger('myapp')
    logger.info(f'Greeting {name}')
    return f'Hello, {name}!'

# Test function using caplog

def test_greet_logs_message(caplog):
    with caplog.at_level(logging.INFO):
        result = greet('Alice')
    assert result == 'Hello, Alice!'
    assert 'Greeting Alice' in caplog.text
    # Optional: check log level of the first record
    assert caplog.records[0].levelname == 'INFO'

The greet function logs an info message with the name. The test test_greet_logs_message uses the caplog fixture to capture logs.

Inside the test, caplog.at_level(logging.INFO) sets the log level to INFO to capture info messages. The function is called with 'Alice'.

Assertions check that the function returns the expected greeting string and that the log message 'Greeting Alice' appears in the captured logs. Additionally, it verifies the log level of the first captured record is INFO.

This approach ensures logs are captured and verified without printing them, making tests clean and reliable.

Common Mistakes - 3 Pitfalls
Not using caplog fixture parameter in the test function
Not setting the log level with caplog.at_level()
Asserting on printed output instead of caplog.text
Bonus Challenge

Now add data-driven testing with 3 different names to verify log messages for each

Show Hint