0
0
PyTesttesting~15 mins

Asserting log messages in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify that a specific log message is generated during function execution
Preconditions (2)
Step 1: Run the function that should produce a log message
Step 2: Capture the log output during the function execution
Step 3: Check if the expected log message appears in the captured logs
✅ Expected Result: The expected log message is found in the captured logs, confirming the function logs correctly
Automation Requirements - pytest
Assertions Needed:
Assert that the expected log message is present in the captured logs
Best Practices:
Use pytest's caplog fixture to capture logs
Use explicit log level filtering to capture relevant logs
Keep assertions clear and focused on the expected message
Automated Solution
PyTest
import logging
import pytest

# Sample function that logs a message

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


def test_greet_logs_message(caplog):
    with caplog.at_level(logging.INFO, logger='myapp'):
        result = greet('Alice')
    
    assert result == 'Hello, Alice!'
    assert any('Greeting Alice' in message for message in caplog.messages)

The code defines a simple function greet that logs an info message when called.

The test test_greet_logs_message uses pytest's caplog fixture to capture logs from the myapp logger at INFO level.

Inside the with caplog.at_level() block, the function is called, and logs are captured.

Assertions check that the function returns the expected greeting string and that the expected log message 'Greeting Alice' is present in the captured logs.

This approach ensures the test only captures relevant logs and verifies the logging behavior precisely.

Common Mistakes - 3 Pitfalls
{'mistake': 'Not using the caplog fixture and trying to capture logs manually', 'why_bad': "Manual log capturing is error-prone and more complex than using pytest's built-in caplog fixture", 'correct_approach': 'Use the caplog fixture provided by pytest to capture and assert log messages easily'}
{'mistake': 'Not setting the log level in caplog.at_level, causing no logs to be captured', 'why_bad': 'If the log level is not set or set too high, the expected log messages may not be captured, causing false test failures', 'correct_approach': "Use caplog.at_level with the correct log level matching the function's log calls"}
Asserting exact match on caplog.text instead of checking messages list
Bonus Challenge

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

Show Hint