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

发布于 2024-09-16 10:49:50 字数 176 浏览 7 评论 0原文

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

I'm writing unit tests using nose, and I'd like to check whether a function raises a warning (the function uses warnings.warn). Is this something that can easily be done?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

染墨丶若流云 2024-09-23 10:49:50
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"

def your_code():
    # ...
    warnings.warn("deprecated", DeprecationWarning)
    # ...

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

Instead of just checking the lenght, you can check it in-depth, of course:

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

In python 2.7 or later, you can do this with the last check as:

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

娇纵 2024-09-23 10:49:50

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

我认为 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) 

There are (at least) two ways of doing this. You can catch the warning in the list of warnings.WarningMessages in test or use mock to patch the imported warnings in your module.

I think the patch version is more general.

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) 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文