【问题标题】:Can I use nose to check that a function raises a warning, but also keep that warning message from printing on the terminal?我可以用鼻子检查一个函数是否引发了警告,但也可以防止该警告消息在终端上打印?
【发布时间】:2014-01-11 00:53:12
【问题描述】:

我想编写一个鼻子单元测试来确认一个函数发出了预期的警告。 This answer 展示了如何。

但是,我也不想在运行鼻子测试的终端窗口中看到警告消息。 (它会使鼻子测试的输出变得混乱。)

有没有办法在不显示警告文本的情况下进行鼻子测试以查看函数是否发出警告?

【问题讨论】:

标签: python unit-testing nose


【解决方案1】:

我会考虑使用https://pypi.python.org/pypi/mock 模块的patch 装饰器来伪造warnings.warn 函数。然后,您可以验证调用是否已发出,而实际上并未调用它。

类似这样的东西(未经测试):

@mock.patch('yourmodule.warnings')
def your_test(self, mock_warnings):
    your_code()
    mock_warnings.warn.assert_called_with("deprecated", DeprecationWarning)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-03
    • 2022-01-11
    • 1970-01-01
    • 2013-05-12
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多