[英]Custom exceptions in unittests
我已經在errors.py
創建了自定義異常
mapper = {
'E101':
'There is no data at all for these constraints',
'E102':
'There is no data for these constraints in this market, try changing market',
'E103':
'There is no data for these constraints during these dates, try changing dates',
}
class DataException(Exception):
def __init__(self, code):
super().__init__()
self.msg = mapper[code]
def __str__(self):
return self.msg
如果pandas
數據框中的數據不足,則代碼中其他地方的另一個函數將引發DataException
不同實例。 我想使用unittest
來確保它返回適當的異常及其相應的消息。
用一個簡單的例子,為什么這不起作用:
from .. import DataException
def foobar():
raise DataException('E101')
import unittest
with unittest.TestCase.assertRaises(DataException):
foobar()
如此處所示: Python assertRaises在用戶定義的異常上
我收到此錯誤:
TypeError: assertRaises() missing 1 required positional argument: 'expected_exception'
或者:
def foobar():
raise DataException('E101')
import unittest
unittest.TestCase.assertRaises(DataException, foobar)
結果是:
TypeError: assertRaises() arg 1 must be an exception type or tuple of exception types
為什么不將DataException
識別為Exception
? 為什么在沒有為assertRaises
提供第二個參數的情況下鏈接的stackoverflow問題答案有效?
您正在嘗試使用TestCase
類的方法而不創建實例。 這些方法並非旨在以這種方式使用。
unittest.TestCase.assertRaises
是一個未綁定的方法 。 您將在定義的TestCase
類的測試方法中使用它:
class DemoTestCase(unittest.TestCase):
def test_foobar(self):
with self.assertRaises(DataException):
foobar()
引發此錯誤的原因未綁定的方法沒有得到self
傳遞。因為unittest.TestCase.assertRaises
預計雙方self
,並命名為第二個參數expected_exception
,你會得到一個異常DataException
傳遞中作為價值self
。
現在,您必須使用測試運行器來管理您的測試用例。 加
if __name__ == '__main__':
unittest.main()
在底部,並以腳本形式運行文件。 然后,您的測試用例將被自動發現並執行。
從技術上講,可以在這樣的環境之外使用斷言,請參閱是否可以在TestCase之外使用Python單元測試斷言? ,但是我建議您堅持創建測試用例。
為了進一步驗證所引發異常的代碼和消息,將進入上下文時返回的值分配給一個新名稱,並with ... as <target>:
:; 上下文管理器對象捕獲引發的異常,因此您可以對其進行斷言:
with self.assertRaises(DataException) as context:
foobar()
self.assertEqual(context.exception.code, 'E101')
self.assertEqual(
context.exception.msg,
'There is no data at all for these constraints')
請參閱TestCase.assertRaises()
文檔 。
最后但並非最不重要的一點是,請考慮使用DataException
子類 ,而不要使用單獨的錯誤代碼。 這樣,您的API用戶就可以捕獲這些子類中的一個來處理特定的錯誤代碼,而不必對代碼進行額外的測試,並在不應該處理特定代碼的情況下重新引發。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.