![](/img/trans.png)
[英]overloading unittest.TestCase in python, for parameterized runs
[英]Python parameterized unittest by subclassing TestCase
如何創建多個TestCases並以編程方式運行它們? 我正在嘗試在一個常見的TestCase上測試集合的多個實現。
我寧願堅持簡單的unittest並避免依賴。
我看過的一些資源與我想要的不完全相同:
編寫可重用的參數化unittest.TestCase方法 -接受的答案提出了四個不同的外部庫。
http://eli.thegreenplace.net/2011/08/02/python-unit-testing-parametrized-test-cases-這種方法使用靜態方法paramerize
。 我不明白為什么您不能直接將參數傳遞給TestSubClass.__init__
。
如何在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
與參數化燈具 :
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.