2015-12-23 67 views
1

如何創建多個TestCases並以編程方式運行它們?我試圖在一個普通的TestCase上測試一個集合的多個實現。通過繼承Python的參數化unittest 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

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

如果這不是一個選項,你可以做一個混入含有測試功能和子類提供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() 
+0

不錯,mixin的想法是關於完美的。這有點重複,但很清楚。 – Joe

+0

CPython測試套件使用mixin方法來測試例如C和Python實現,或者例如對於多個類通用的測試,例如unicode和字節或元組和列表(甚至範圍)或集合和frozense 。 –

+1

@JoeS,感謝您的編輯。 :) – falsetru