检查函数是否在nose测试中引发警告

9 投票
2 回答
2566 浏览
提问于 2025-04-16 03:24

我正在使用nose来编写单元测试,我想检查一个函数是否会发出警告(这个函数使用了warnings.warn)。请问这个可以简单实现吗?

2 个回答

1

有至少两种方法可以做到这一点。你可以在测试中捕捉到警告,方法是查看 warnings.WarningMessage 的列表,或者使用 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) 
10
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"

撰写回答