如何创建多个TestCase并以编程方式运行它们?我试图在常见的TestCase上测试集合的多个实现。
我更愿意坚持使用普通的单元测试并避免依赖。
在这里,我看到的一些资源并不能满足我的需求:
Writing a re-usable parametrized unittest.TestCase method - 接受的答案提出了四种不同的外部库。
http://eli.thegreenplace.net/2011/08/02/python-unit-testing-parametrized-test-cases -
此方法使用静态方法paramerize
。我不明白为什么你不能直接将参数传递给
TestSubClass.__init__
。
How to generate dynamic (parametrized) unit tests in python? - 有点太黑魔法了。
这是一个最小(非)工作的例子。
import unittest
MyCollection = set
AnotherCollection = set
# ... many more collections
def maximise(collection, array):
return 2
class TestSubClass(unittest.TestCase):
def __init__(self, collection_class):
unittest.TestCase.__init__(self)
self.collection_class = collection_class
self.maximise_fn = lambda array: maximise(collection_class, array)
def test_single(self):
self.assertEqual(self.maximise_fn([1]), 1)
def test_overflow(self):
self.assertEqual(self.maximise_fn([3]), 1)
# ... many more tests
def run_suite():
suite = unittest.defaultTestLoader
for collection in [MyCollection, AnotherCollection]:
suite.loadTestsFromTestCase(TestSubClass(collection))
unittest.TextTestRunner().run(suite)
def main():
run_suite()
if __name__ == '__main__':
main()
loadTestsFromTestCase
中的上述方法错误:
TypeError: issubclass() arg 1 must be a class
答案 0 :(得分:1)
如何使用pytest
with to parametrize fixture:
import pytest
MyCollection = set
AnotherCollection = set
def maximise(collection, array):
return 1
@pytest.fixture(scope='module', params=[MyCollection, AnotherCollection])
def maximise_fn(request):
return lambda array: maximise(request.param, array)
def test_single(maximise_fn):
assert maximise_fn([1]) == 1
def test_overflow(maximise_fn):
assert maximise_fn([3]) == 1
如果这不是一个选项,你可以让mixin包含测试函数,并使用子类来提供maximise_fn
s:
import unittest
MyCollection = set
AnotherCollection = set
def maximise(collection, array):
return 1
class TestCollectionMixin:
def test_single(self):
self.assertEqual(self.maximise_fn([1]), 1)
def test_overflow(self):
self.assertEqual(self.maximise_fn([3]), 1)
class TestMyCollection(TestCollectionMixin, unittest.TestCase):
maximise_fn = lambda self, array: maximise(MyCollection, array)
class TestAnotherCollection(TestCollectionMixin, unittest.TestCase):
maximise_fn = lambda self, array: maximise(AnotherCollection, array)
if __name__ == '__main__':
unittest.main()