如何创建多个TestCases并以编程方式运行它们?我正在尝试在一个常见的TestCase上测试集合的多个实现。

我宁愿坚持简单的unittest并避免依赖。

我看过的一些资源与我想要的不完全相同:


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

最佳答案

如何使用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

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()

10-04 18:08