0
0
PyTesttesting~5 mins

caplog for log messages in PyTest

Choose your learning style9 modes available
Introduction

We use caplog to check if our program writes the right messages in the log. This helps us catch problems early.

When you want to test if a function logs an error message on failure.
When you want to confirm that a warning is logged under certain conditions.
When you want to check that info messages appear during normal operation.
When you want to verify that debug messages are created for troubleshooting.
When you want to ensure no unexpected log messages are produced.
Syntax
PyTest
import logging

def test_function(caplog):
    with caplog.at_level(logging.INFO):
        function_to_test()
    assert 'expected message' in caplog.text

caplog is a pytest fixture that captures log messages during tests.

You can set the log level inside caplog.at_level() to capture messages of that level and above.

Examples
This test checks if an info message is logged.
PyTest
import logging

def test_logs_info(caplog):
    with caplog.at_level(logging.INFO):
        print('Running test')
        logging.info('Info message')
    assert 'Info message' in caplog.text
This test captures error messages and checks for a specific error log.
PyTest
import logging

def test_logs_error(caplog):
    with caplog.at_level(logging.ERROR):
        logging.error('Error happened')
    assert 'Error happened' in caplog.text
This test verifies that a warning message is logged.
PyTest
import logging

def test_logs_warning(caplog):
    with caplog.at_level(logging.WARNING):
        logging.warning('Warning issued')
    assert 'Warning issued' in caplog.text
Sample Program

This test checks that the greet function logs an info message when given a name and an error message when the name is empty.

PyTest
import logging
import pytest

def greet(name):
    logging.info(f'Greeting {name}')
    if not name:
        logging.error('No name provided')
    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

    with caplog.at_level(logging.ERROR):
        greet('')
    assert 'No name provided' in caplog.text
OutputSuccess
Important Notes

Always import the logging module to use logging functions.

Use caplog.text to get all captured log messages as one string.

You can also access caplog.records for detailed log record objects.

Summary

caplog helps you check log messages during tests.

Use caplog.at_level() to set which log levels to capture.

Assert that expected messages appear in caplog.text.