在 Python `unittest` 中,我如何 return 在 exception/warning 发生在 try - except 之后的值?

In Python `unittest`, how can I return a value after exception/warning happened in try - except?

这是我的代码。

import unittest
import warnings

def function_that_raises_CustomWarning():
    warnings.warn("warning")
    return True

class test(unittest.TestCase):

    def test(self):
        is_this_True = False
        is_CustomWarning_raised = False

        try:
            is_this_True = function_that_raises_CustomWarning()
        except Warning:
            is_CustomWarning_raised = True

        self.assertTrue(is_this_True)
        self.assertTrue(is_CustomWarning_raised)

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

is_this_True in self.assertTrue(is_this_True)False,因此测试失败。

我想要的是 self.assertTrue(is_this_True) 中的 is_this_True 成为 True。但是,return 值不是 "captured",因为该值是 returned afterfunction_that_raises_CustomWarning() 中引发警告。

如何 return function_that_raises_CustomWarning() 中的值以及 "captured" except 中的警告?

当我 运行 你的代码在 Windows 上使用 3.6 时,失败是 self.assertTrue(is_CustomWarning_raised)。默认情况下,警告不是异常,不能用 except: 捕获。解决方案是使用 assertWarnsassertWarnsRegex。我使用后者来展示如何使用它来添加额外的测试。

import unittest
import warnings

def function_that_raises_CustomWarning():
    warnings.warn("my warning")
    return True

class test(unittest.TestCase):

    def test(self):
        is_this_True = False

        with self.assertWarnsRegex(Warning, 'my warning'):
            is_this_True = function_that_raises_CustomWarning()
        self.assertTrue(is_this_True)


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