【问题标题】:Python: Using logging info in nose/unittest?Python:在鼻子/单元测试中使用日志信息?
【发布时间】:2015-09-25 23:35:30
【问题描述】:

我有一个操作对象内部状态的测试函数。该对象使用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

【问题讨论】:

    标签: python nose python-unittest nosetests


    【解决方案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 很棒。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-09
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-28
      • 1970-01-01
      相关资源
      最近更新 更多