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
.
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.
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")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With