[英]python unittest combine assertions with context manager
要測試 function,當第一個參數不是 integer 類型時,我會引發異常:
def magicWithInteger(integerA):
if not isinstance(integerA, int):
raise TypeError("argument should be integer type")
我使用 unittest assertRaises 和 assertEqual,所以我可以檢查帶有錯誤參數的 function 是否引發 TypeError 以及 TypeError 是否實際吐出“參數應該是 integer 類型”
class test(unittest.TestCase):
def test_magicWithInteger(self):
self.assertRaises(TypeError, MagicWithInteger, "TEST")
try:
MagicWithInteger("TEST")
except TypeError as error:
self.assertEqual(str(error), "argument should be integer type")
調用 function 兩次看起來有點傻,首先檢查它是否引發異常,然后檢查哪個 TypeError 異常?
經過一番研究,我知道應該可以使用上下文管理器在一個 go 中進行這兩個測試,但我似乎無法維持生計......
您可以使用with self.assertRaises(ExceptionType)
上下文管理器來捕獲異常。 根據assertRaises 手冊,您可以查看with
塊之后的異常:如果您使用as <name>
語法為其命名,它似乎仍在 scope 中:
with self.assertRaises(SomeException) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
資料來源: docs.python.org
所以你的代碼會變成:
class test(unittest.TestCase):
def test_magicWithInteger(self):
with self.assertRaises(TypeError) as cm:
MagicWithInteger("TEST")
self.assertEqual(str(cm.exception), "argument should be integer type")
PS:我不知道這一點,但是with
語句並沒有在 Python 中引入新的 scope。 with
內部定義的變量與with
語句本身在同一 scope 中。 請參閱https://stackoverflow.com/a/45100308/3216427到此特定點,對於實際創建范圍的內容, https://stackoverflow.com/a/52992404/321642
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.