如何使用Python的unittest测试是否已经抛出警告?

时间:2010-10-08 15:51:35

标签: python unit-testing exception-handling warnings

我在Python中有以下函数,我想用unittest测试如果函数得到0作为参数,它会抛出警告。我已经尝试过assertRaises,但由于我没有提出警告,这不起作用。

def isZero(i):
    if i != 0:
        print "OK"
    else:
        warning = Warning("the input is 0!") 
        print warning
    return i

5 个答案:

答案 0 :(得分:48)

您可以使用catch_warnings上下文管理器。实质上,这允许您模拟警告处理程序,以便您可以验证警告的详细信息。有关更全面的说明和示例测试代码,请参阅official docs

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings(record=True) as w:
    # Cause all warnings to always be triggered.
    warnings.simplefilter("always")
    # Trigger a warning.
    fxn()
    # Verify some things
    assert len(w) == 1
    assert issubclass(w[-1].category, DeprecationWarning)
    assert "deprecated" in str(w[-1].message)

答案 1 :(得分:34)

从Python 3.2开始,您只需使用assertWarns()方法。

with self.assertWarns(Warning):
    do_something()

答案 2 :(得分:18)

您可以编写自己的assertWarns函数来填充catch_warnings上下文。我刚刚通过以下方式实现了它:mixin:

class WarningTestMixin(object):
    'A test which checks if the specified warning was raised'

    def assertWarns(self, warning, callable, *args, **kwds):
        with warnings.catch_warnings(record=True) as warning_list:
            warnings.simplefilter('always')

            result = callable(*args, **kwds)

            self.assertTrue(any(item.category == warning for item in warning_list))

用法示例:

class SomeTest(WarningTestMixin, TestCase):
    'Your testcase'

    def test_something(self):
        self.assertWarns(
            UserWarning,
            your_function_which_issues_a_warning,
            5, 10, 'john', # args
            foo='bar'      # kwargs
        )

如果your_function发出的警告中至少有一个是UserWarning类型,则测试将通过。

答案 3 :(得分:5)

@ire_and_curses'answer非常有用,而且我认为是规范的。这是另一种做同样事情的方法。这个需要Michael Foord的优秀Mock library

import unittest, warnings
from mock import patch_object

def isZero( i):
   if i != 0:
     print "OK"
   else:
     warnings.warn( "the input is 0!")
   return i

class Foo(unittest.TestCase):
    @patch_object(warnings, 'warn')
    def test_is_zero_raises_warning(self, mock_warn):
        isZero(0)
        self.assertTrue(mock_warn.called)

if __name__ == '__main__':
    unittest.main()

漂亮的patch_object可让您模拟warn方法。

答案 4 :(得分:0)

warnings.catch_warnings方法的一个问题是,在不同测试中产生的警告可以通过保留在__warningregistry__属性中的全局状态以奇怪的方式进行交互。

要解决此问题,我们应该在每次检查警告的测试之前清除每个模块的__warningregistry__属性。

class MyTest(unittest.TestCase):

  def setUp(self):
    # The __warningregistry__'s need to be in a pristine state for tests
    # to work properly.
    for v in sys.modules.values():
      if getattr(v, '__warningregistry__', None):
        v.__warningregistry__ = {}

  def test_something(self):
    with warnings.catch_warnings(record=True) as w:
      warnings.simplefilter("always", MySpecialWarning)
      ...
      self.assertEqual(len(w), 1)
      self.assertIsInstance(w[0].message, MySpecialWarning)

Python 3的assertWarns()方法就是implemented

相关问题