在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)
isFalse
,因此测试失败
我想要的是在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应该在任何地方都有效。