2017-02-11 32 views
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_TrueFalse,因此未能通過測試。

我想要的是is_this_Trueself.assertTrue(is_this_True)True。但是,由於返回值之後function_that_raises_CustomWarning()中發出警告,因此返回值未被「俘獲」。

如何返回function_that_raises_CustomWarning()中的值,並且還「捕獲」了except中的警告?

回答

1

當我在Windows上運行3.6代碼時,失敗是self.assertTrue(is_CustomWarning_raised)。默認情況下,警告不是例外,不能被except:捕獲。解決方案是使用assertWarnsassertWarnsRegex。我使用後者來展示如何使用它來添加額外的測試。

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

謝謝!知道我也可以基於提出的警告來斷言。根據我的經驗,「except」和「Warning」一起工作。在這種情況下,我寧願使用'self.assertWarns(MoreSpecificWarning)'來代替,因爲我不想處理正則表達式。 – notalentgeek

+0

警告不應該是可捕獲的異常,除非用'-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應該無處不在。 –

相關問題