How do I test if a certain log message is logged in a Django test case?

Krystian Cybulski picture Krystian Cybulski · Feb 4, 2013 · Viewed 13.8k times · Source

I want to ensure that a certain condition in my code causes a log message to be written to the django log. How would I do this with the Django unit testing framework?

Is there a place where I can check logged messages, similarly to how I can check sent emails? My unit test extends django.test.TestCase.

Answer

Simeon Visser picture Simeon Visser · Feb 4, 2013

Using the mock module for mocking the logging module or the logger object. When you've done that, check the arguments with which the logging function is called.

For example, if you code looks like this:

import logging

logger = logging.getLogger('my_logger')

logger.error("Your log message here")

it would look like:

from unittest.mock import patch # For python 2.x use from mock import patch

@patch('this.is.my.module.logger')
def test_check_logging_message(self, mock_logger):
    mock_logger.error.assert_called_with("Your log message here")