python - 如何测试某个日志消息是否记录在 Django 测试用例中?

标签 python django unit-testing testing python-unittest

我想确保我的代码中的某个条件导致将日志消息写入 django 日志。我将如何使用 Django 单元测试框架来做到这一点?

是否有一个地方可以让我检查已记录的消息,就像我可以检查已发送的电子邮件一样?我的单元测试扩展了 django.test.TestCase

最佳答案

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

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

import logging

logger = logging.getLogger('my_logger')

logger.error("Your log message here")

看起来像:

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

关于python - 如何测试某个日志消息是否记录在 Django 测试用例中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14690267/

相关文章:

python - mongoengine 保存时操作错误

python - 为 df1 中的每个项目查找 df2 中最接近的项目

python - 理解 django admin readonly_fields

python - 限制来自 Django QuerySet 的结果数量,而不使用切片

c++ - 我可以通过 boost 测试检查我的程序的输出吗?

unit-testing - 在未安装 Visual Studio 的情况下使用 vstest.console.exe 运行 c++ unittest

ruby-on-rails - 关于 Rails fixtures 创建顺序的问题

python - 我不确定 pygame.mixer.init 是否有效

python - 在docker中激活conda环境

mysql - 我使用django和mysql,但是使用DateTimeField时时间不对