簡體   English   中英

Python:在鼻子/單元測試中使用日志記錄信息嗎?

[英]Python: Using logging info in nose/unittest?

我有一個測試功能,可以操縱對象的內部狀態。 該對象使用logging.info()記錄以下內容。

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

如何將其合並到鼻子或單元測試功能中,以便可以進行與此類似的測試?

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

我可能還會添加,當涉及到這種測試時,我喜歡使用諸如flexmock嘲笑之類的測試框架

另外,在驗證匹配器時, py-hamcrest非常棒。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM