在Python的“unittest”中,在try except中发生异常/警告之后,如何返回值?

2024-04-25 06:05:41 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码。在

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()

self.assertTrue(is_this_True)中的is_this_True是{},因此测试失败。在

我想要的是self.assertTrue(is_this_True)中的is_this_True是{}。但是,返回值不是“捕获”的,因为值是在function_that_raises_CustomWarning()中发出警告之后返回的。在

如何返回function_that_raises_CustomWarning()中的值,同时“捕获”了except中的警告?在


Tags: testimportselftruethatisdeffunction
1条回答
网友
1楼 · 发布于 2024-04-25 06:05:41

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

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()

相关问题 更多 >