Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python“unittest”中,在try-except中发生异常/警告后,如何返回值?_Python_Unit Testing_Warnings_Try Except - Fatal编程技术网

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

在Python“unittest”中,在try-except中发生异常/警告后,如何返回值?,python,unit-testing,warnings,try-except,Python,Unit Testing,Warnings,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

这是我的密码

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中的
is this\u True
。assertTrue(is\u this\u True)
is
False
,因此测试失败

我想要的是在self.assertTrue(这是真的)中的
这是真的
成为
真的
。但是,返回值不是“捕获”的,因为该值是在
函数\u中发出警告后返回的,该警告会引发\u CustomWarning()


如何在
函数\u中返回值,该值会引发\u CustomWarning()
,但在
中也会“捕获”除
之外的警告?

当我在Windows上使用3.6运行代码时,失败的原因是
self.assertTrue(是\u CustomWarning\u引发的)
。默认情况下,警告不是异常,不能通过
捕获,除非:
。解决方案是使用
assertWarns
assertWarnsRegex
。我使用后者来说明如何使用它添加额外的测试

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

哦,谢谢!我知道我也可以根据提出的警告来断言。根据我的经验,
除了
之外,它也适用于
警告
。在这种情况下,我更喜欢使用
self.assertwarning(moresspecificwarning)
,因为我不想处理regex。警告不应该是可捕获的异常,除非用
-W error
启动python,或者用
'error'
操作添加警告过滤器。也许您使用的系统在启动脚本中以某种方式打开了“错误”。使用AssertWarning应该在任何地方都有效。