我有一个测试函数来操纵对象的内部状态。该对象使用 logging.info()
记录以下内容。
INFO:root:_change: test light red
INFO:root:_change: test light green
INFO:root:_change: test light yellow
如何将其合并到 Nose 或单元测试函数中,以便我可以进行与此类似的测试?
def test_thing():
expected_log_output = "INFO:root:_change: test light red\n" +\
"INFO:root:_change: test light green\n" +\
"INFO:root:_change: test light yellow\n"
run_thing()
assert actual_log_output matches expected_log_output
最佳答案
在测试我的日志记录时,我通常做的是模拟我的记录器并确保使用适当的参数调用它。我通常会做这样的事情:
class TestBackupInstantiation(TestCase):
@patch('core.backup.log')
def test_exception_raised_when_instantiating_class(self, m_log):
with self.assertRaises(IOError) as exc:
Backup(AFakeFactory())
assert_equal(m_log.error.call_count, 1)
assert_that(exc.exception, is_(IOError))
因此,您甚至可以调用电话进行测试,以确保调用记录器来验证消息。
我相信你可以做这样的事情:
m_log.error.assert_used_with("foo")
我还可以补充一点,当涉及到这种测试时,我喜欢使用像 flexmock 这样的测试框架。和 mock
此外,在验证匹配器时,py-hamcrest太棒了。
关于Python:在nose/unittest中使用日志信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32792061/