【问题标题】:Check that a function raises a warning with nose tests检查函数是否通过鼻子测试引发警告
【发布时间】:2010-08-27 19:13:48
【问题描述】:

我正在使用nose 编写单元测试,我想检查一个函数是否引发警告(该函数使用warnings.warn)。这是一件很容易做到的事情吗?

【问题讨论】:

  • import warnings; import nose 然后with nose.tools.assert_warns(DeprecationWarning): warnings.warn(DeprecationWarning)

标签: python unit-testing warnings nose


【解决方案1】:
def your_code():
    # ...
    warnings.warn("deprecated", DeprecationWarning)
    # ...

def your_test():
    with warnings.catch_warnings(record=True) as w:
        your_code()
        assert len(w) > 1

不只是检查长度,你当然可以深入检查:

assert str(w.args[0]) == "deprecated"

在 python 2.7 或更高版本中,您可以通过最后一次检查来执行此操作:

assert str(w[0].message[0]) == "deprecated"

【讨论】:

  • 测试不应该是len(w) > 0,我们只是想检查warnings.WarningMessage列表是否为空。或者,跟随PEP8 只是测试空序列是否为假
【解决方案2】:

有(至少)两种方法可以做到这一点。您可以在测试中捕获warnings.WarningMessages 的list 中的警告,或者在您的模块中使用mockpatch 导入的warnings

我觉得patch这个版本更通用。

raise_warning.py:

import warnings

def should_warn():
    warnings.warn('message', RuntimeWarning)
    print('didn\'t I warn you?')

raise_warning_tests.py:

import unittest
from mock import patch
import raise_warning

class TestWarnings(unittest.TestCase):

    @patch('raise_warning.warnings.warn')
    def test_patched(self, mock_warnings):
        """test with patched warnings"""
        raise_warning.should_warn()
        self.assertTrue(mock_warnings.called)

    def test_that_catches_warning(self):
        """test by catching warning"""
        with raise_warning.warnings.catch_warnings(True) as wrn:
            raise_warning.should_warn()
            # per-PEP8 check for empty sequences by their Truthiness 
            self.assertTrue(wrn) 

【讨论】:

    猜你喜欢
    • 2016-04-08
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多