2015-09-25 63 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是真棒。

相關問題