如何在python中生成动态(参数化)单元测试?我有一些测试数据,并希望为每个项目创建一个单元测试。我的第一个想法是这样做:import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]class TestSequence(unittest.TestCase):
def testsample(self):
for name, a,b in l:
print "test", name
self.assertEqual(a,b)if __name__ == '__main__':
unittest.main()这样做的缺点是它在一次测试中处理所有数据。我想在飞行中为每个项目生成一个测试。有什么建议吗?
3 回答
德玛西亚99
TA贡献1770条经验 获得超3个赞
import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]class TestSequenceMeta(type): def __new__(mcs, name, bases, dict): def gen_test(a, b): def test(self): self.assertEqual(a, b) return test for tname, a, b in l: test_name = "test_%s" % tname dict[test_name] = gen_test(a,b) return type.__new__(mcs, name, bases, dict)class TestSequence(unittest.TestCase): __metaclass__ = TestSequenceMetaif __name__ == '__main__': unittest.main()
添加回答
举报
0/150
提交
取消