Python 检查某个函数是否会通过鼻子测试发出警告

Python 检查某个函数是否会通过鼻子测试发出警告,python,unit-testing,warnings,nose,Python,Unit Testing,Warnings,Nose,我正在使用编写单元测试,我想检查函数是否引发警告(函数使用warnings.warn)。这是很容易做到的吗 def your_code(): # ... warnings.warn("deprecated", DeprecationWarning) # ... def your_test(): with warnings.catch_warnings(record=True) as w: your_code() assert le

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

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])==“已弃用”

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

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

至少有两种方法可以做到这一点。您可以在
警告的
列表
中捕获警告。测试中的警告消息
s或使用
模拟
在模块中修补导入的
警告

我认为
补丁
版本更通用

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) 

测试不应该是
len(w)>0
,我们只想检查
WarningMessage
列表是否为空。或者,仅测试空序列是否为假