[英]How to make assertRaises() print the passed *args, **kwargs in Python 2.7?
我在這樣的循環中使用assertRaises
:
for i in ['a', 'b', 'c']:
self.assertRaises(ValidationError, my_method, i)
問題是每當測試失敗時,輸出將如下所示:
File "/bla/test.py", line 4, in test_assertion
my_method(i)
AssertionError: ValidationError not raised
測試失敗時如何打印出i
的值? 像這樣:
File "/bla/test.py", line 4, in test_assertion
my_method('b')
AssertionError: ValidationError not raised
這是subTests
上下文管理器的理想情況。 但是,這僅在python 3中可用。我認為最好的解決方案是創建自己的subTests
版本。 好處是可以很容易地設置subTests
的基本模擬,並且如果將subTests
重新移植到python 2,則將很容易切換。
import unittest
import sys
from contextlib import contextmanager
class TestCaseWithSubTests(unittest.TestCase):
@contextmanager
def subTest(self, **kwargs):
try:
yield None
except:
exc_class, exc, tb = sys.exc_info()
kwargs_desc = ", ".join("{}={!r}".format(k, v) for k, v in kwargs.items())
new_exc = exc_class("with {}: {}".format(kwargs_desc, exc))
raise exc_class, new_exc, tb.tb_next
class MyTest(TestCaseWithSubTests):
def test_with_assertion_error(self):
for i in [0, 1]:
with self.subTest(i=i), self.assertRaises(ZeroDivisionError):
1 / i
def test_with_value_error(self):
def f(i):
raise ValueError
for i in [0, 1]:
with self.subTest(i=i), self.assertRaises(ZeroDivisionError):
f(i)
if __name__ == "__main__":
unittest.main()
產生以下輸出:
FE
======================================================================
ERROR: test_with_value_error (__main__.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\dunes\py2sub_tests.py", line 30, in test_with_value_error
f(i)
File "C:\Python27\lib\contextlib.py", line 35, in __exit__
self.gen.throw(type, value, traceback)
File "C:\Users\dunes\py2sub_tests.py", line 30, in test_with_value_error
f(i)
File "C:\Users\dunes\py2sub_tests.py", line 26, in f
raise ValueError
ValueError: with i=0:
======================================================================
FAIL: test_with_assertion_error (__main__.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\dunes\py2sub_tests.py", line 22, in test_with_assertion_error
1 / i
File "C:\Python27\lib\contextlib.py", line 35, in __exit__
self.gen.throw(type, value, traceback)
File "C:\Users\dunes\py2sub_tests.py", line 22, in test_with_assertion_error
1 / i
AssertionError: with i=1: ZeroDivisionError not raised
----------------------------------------------------------------------
Ran 2 tests in 0.006s
FAILED (failures=1, errors=1)
一種解決方案是使用assertRaises()
作為上下文管理器。
with self.assertRaises(ValidationError):
my_method(i)
print("Failed when i was",i)
僅當my_method()
行成功通過時,print語句才會執行,因此當測試失敗時,它將顯示為輸出。 有點my_method()
,但確實有效(除非my_method()
拋出不是ValidationError
錯誤)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.