8

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

4

2 回答 2

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"

于 2010-08-27T19:41:26.763 回答
1

有(至少)两种方法可以做到这一点。list您可以在测试中的of warnings.WarningMessages 中捕获警告,也可以将其用于模块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) 
于 2015-08-19T07:30:40.153 回答