如何测试Django测试案例中是否记录了某些日志消息? [英] How do I test if a certain log message is logged in a Django test case?

查看:91
本文介绍了如何测试Django测试案例中是否记录了某些日志消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确保代码中的特定条件导致将日志消息写入django日志。



是否有地方可以检查已记录的消息,就像我可以检查已发送的电子邮件一样?



我的单元测试扩展了 django.test.TestCase

解决方案

mock 模块,用于模拟日志记录模块或logger对象。完成此操作后,检查用于调用日志记录函数的参数。



例如,如果您编写的代码如下所示:

 导入日志记录

logger = logging.getLogger('my_logger')

logger.error(您的日志消息在这里)

它看起来像:

  from unittest.mock import patch#对于python 2.x,请使用模拟导入补丁

@patch('this.is.my.module .logger')
def test_check_logging_message(自己,mock_logger):
mock_logger.error.assert_call_with(此处的日志消息)


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.

解决方案

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")

这篇关于如何测试Django测试案例中是否记录了某些日志消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆