2015-09-25 64 views
1

我有一个测试函数来操纵对象的内部状态。该对象使用logging.info()记录以下内容。Python:在鼻子/单元测试中使用记录信息?

INFO:root:_change: test light red 
INFO:root:_change: test light green 
INFO:root:_change: test light yellow 

我怎样才能将它纳入鼻子或unittest功能,以便我可以有一个类似的测试呢?

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 

回答

1

当谈到测试我的日志记录时,我通常做的是模拟我的记录器并确保它被调用相应的参数。我通常做这样的事情:

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_called_with("foo")

我还可以补充说,当涉及到这种测试我喜欢用测试框架,如flexmockmock

此外,当它来验证匹配,py-hamcrest是真棒。

相关问题