检查功能是否通过鼻子测试发出警告

时间:2010-08-27 19:13:49

标签: python unit-testing warnings nose

我正在使用nose编写单元测试,我想检查函数是否引发警告(函数使用warnings.warn)。这是否可以轻松完成?

2 个答案:

答案 0 :(得分:9)

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"

答案 1 :(得分:1)

至少有两种方法可以做到这一点。您可以在测试的warnings.WarningMessage mock中捕获警告,或使用模块中导入的patch warningspatch

我认为import warnings def should_warn(): warnings.warn('message', RuntimeWarning) print('didn\'t I warn you?') 版本更为通用。

raise_warning.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) 

raise_warning_tests.py:

{{1}}