Python通过继承TestCase参数化unittest

时间:2015-12-23 05:00:45

标签: python unit-testing python-3.x inheritance python-unittest

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

我更愿意坚持使用普通的单元测试并避免依赖。

在这里,我看到的一些资源并不能满足我的需求:

这是一个最小(非)工作的例子。

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

1 个答案:

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