Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 345
Krystian Cybulski Avatar asked Feb 04 '13 15:02

Krystian Cybulski


People also ask

Should you unit test log messages?

I would definitely consider unit tests for logging scenarios. when testing, think about the information you would require in a situation where the code has failed. if you have a live issue you'd want to be reassured that you have enough information to find the cause of the issue.


2 Answers

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") 
like image 79
Simeon Visser Avatar answered Oct 14 '22 15:10

Simeon Visser


You can also use assertLogs from django.test.TestCase

When you code is

import logging  logger = logging.getLogger('my_logger')  def code_that_throws_error_log():     logger.error("Your log message here") 

This is the test code.

with self.assertLogs(logger='my_logger', level='ERROR') as cm:      code_that_throws_error_log()      self.assertIn(         "ERROR:your.module:Your log message here",         cm.output     ) 

This lets you avoid patching just for logs.

like image 37
manu Avatar answered Oct 14 '22 17:10

manu