これは、subTestsコンテキスト マネージャーにとって理想的な状況です。ただし、これは python 3 でのみ使用できます。最善の解決策は、独自のバージョンのsubTests. 利点は、 の基本的な模倣をセットアップするのが簡単であり、Python 2 に逆移植されたsubTests場合、subTests簡単に切り替えることができることです。
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)