最好的解決方案是在python 3.4中使用unittest的子測試功能。文檔發現here和使用,如:
class NumbersTest(unittest.TestCase):
def test_even(self):
"""
Test that numbers between 0 and 5 are all even.
"""
for i in range(0, 6):
with self.subTest(i=i):
self.assertEqual(i % 2, 0)
對於那些誰不能使用Python 3.4,下面是一個窮人的替代品。
class sub_test_data(object):
def __init__(self, *test_data):
self.test_data = test_data
def __call__(self, func):
func.sub_test_data = self.test_data
func.has_sub_tests = True
return func
def create_test_driver(func, *args):
def test_driver(self):
try:
func(self, *args)
except AssertionError as e:
e.args += ({"test_args": args},)
raise
return test_driver
def create_sub_tests(cls):
for attr_name, func in list(vars(cls).items()):
if getattr(func, "has_sub_tests", False):
for i, value in enumerate(func.sub_test_data):
test_name = 'test_{}_subtest{}'.format(attr_name, i)
setattr(cls, test_name, create_test_driver(func, value))
return cls
@create_sub_tests
class NumbersTest(unittest.TestCase):
tickets = [0, 1, 2, 3, 4, 5]
@sub_test_data(*tickets)
def even(self, t):
self.assertEqual(t % 2, 0)
你有python 3.4嗎?最好的方式來實現你想要的是子測試 - https://docs.python.org/3/library/unittest.html#distinguishing-test-iterations-using-subtests – Dunes 2014-11-06 16:07:20
我是!沒有想法的子測試甚至是一件事情。如果您發佈,我會接受您的答案。謝謝。 – 2014-11-06 16:34:40