0
这是我的代码。在Python`unittest`中,如何在尝试中发生异常/警告后返回值 - 除了?
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
是False
,因此未能通过测试。
我想要的是is_this_True
在self.assertTrue(is_this_True)
是True
。但是,由于返回值在之后function_that_raises_CustomWarning()
中发出警告,因此返回值未被“俘获”。
如何返回function_that_raises_CustomWarning()
中的值,并且还“捕获”了except
中的警告?
谢谢!知道我也可以基于提出的警告来断言。根据我的经验,“except”和“Warning”一起工作。在这种情况下,我宁愿使用'self.assertWarns(MoreSpecificWarning)'来代替,因为我不想处理正则表达式。 – notalentgeek
警告不应该是可捕获的异常,除非用'-W error'启动python https://docs.python.org/3/using/cmdline.html#cmdoption-W或添加一个带有“error”的警告过滤器行动https://docs.python.org/3/library/warnings.html#warnings.filterwarnings。也许您使用的系统在启动脚本中以某种方式打开了“错误”。使用assertWarns应该无处不在。 –