Verify that a specific log message is generated during function execution
Preconditions (2)
✅ Expected Result: The expected log message is found in the captured logs, confirming the function logs correctly
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.
Now add data-driven testing with 3 different names to verify the log messages for each
caplog fixture in pytest when testing log messages?caplogcaplog fixture is designed to capture log messages during pytest test runs.caplog captures logs [OK]caplog in pytest?caplog.set_level(logging.WARNING) sets the capture level to WARNING, capturing WARNING and above.import logging
def test_log_message(caplog):
with caplog.at_level(logging.ERROR):
logging.error('Error occurred')
assert 'Error occurred' in caplog.textcaplog.text, which contains all captured logs as text.caplog to assert a log message:
import logging
def test_info_log(caplog):
logging.info('Info issued')
assert 'Info issued' in caplog.textcaplog to capture INFO level logs, so no logs are captured.caplog.text is empty and the assertion fails.caplog assertion correctly verifies this?caplog.records is a list of log record objects with attributes like message and levelname.Pass the test and this pattern moves unknown