gpt4 book ai didi

Python 3 单元测试 - 未调用断言记录器

转载 作者:行者123 更新时间:2023-12-03 09:30:13 33 4
gpt4 key购买 nike

我知道如何断言已生成日志消息,但我似乎无法弄清楚如何断言未生成日志消息。这是我现在的单元测试(已清理)。请注意,XYZ 类将记录器作为参数,而 test_check_unexpected_keys_found 按预期通过。

import unittest
import logging

class TestXYZ(unittest.TestCase):

@classmethod
def setUpClass(cls):
cls.test_logger = logging.getLogger('test_logger')
cls.test_logger.addHandler(logging.NullHandler())

def test_check_unexpected_keys_found(self):
test_dict = {
'unexpected': 0,
'expected1': 1,
'expected2': 2,
}
xyz = XYZ(self.test_logger)
with self.assertLogs('test_logger', level='WARNING'):
xyz._check_unexpected_keys(test_dict)

def test_check_unexpected_keys_none(self):
test_dict = {
'expected1': 1,
'expected2': 2,
}
xyz = XYZ(self.test_logger)
xyz._check_unexpected_keys(test_dict)
# assert that 'test_logger' was not called ??

我尝试使用 unittest.patch 像这样:
with patch('TestXYZ.test_logger.warning') as mock_logwarn:
xyz._check_unexpected_keys(test_dict)
self.assertFalse(mock_logwarn.called)

但我收到 ImportError: No module named 'TestXYZ'
我也尝试了一些变体,但一无所获。

有谁知道如何处理这个?

最佳答案

全新 assertNoLogs方法是 on route to be added to a future version of Python .
在此之前,这里有一个解决方法:添加一个虚拟日志,然后断言它是唯一的日志。

with self.assertLogs(logger, logging.WARN) as cm:
# We want to assert there are no warnings, but the 'assertLogs' method does not support that.
# Therefore, we are adding a dummy warning, and then we will assert it is the only warning.
logger.warn("Dummy warning")
# DO STUFF

self.assertEqual(
["Dummy warning"],
cm.output,
)

如果您需要这样做不止一次,那么为了避免重复,您可以执行以下操作。假设您有一个所有测试类都继承自的基类,覆盖 assertLogs在该类中如下:
class TestBase(TestCase):
def assertLogs(self, logger_to_watch=None, level=None) -> 'CustomAssertLogsContext':
"""
This method overrides the one in `unittest.case.TestCase`, and has the same behavior, except for not causing a failure when there are no log messages.
The point is to allow asserting there are no logs.
Get rid of this once this is resolved: https://github.com/python/cpython/pull/18067
"""
return CustomAssertLogsContext(self, logger_to_watch, level)

class CustomAssertLogsContext(_AssertLogsContext):
def __exit__(self, exc_type, exc_val, exc_tb) -> Optional[bool]:
# Fool the original exit method to think there is at least one record, to avoid causing a failure
self.watcher.records.append("DUMMY")
result = super().__exit__(exc_type, exc_val, exc_tb)
self.watcher.records.pop()
return result

关于Python 3 单元测试 - 未调用断言记录器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35871815/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com