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應該無處不在。 –