我想确保我的代码中的某个条件导致将日志消息写入 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/