设置
我试图在mutliple数据集上运行相同的unittest.TestCase
。我的设置是关于以下(尽可能简化的(:
from unittest import TestCase, TestSuite
class MyTest(TestCase):
def __init__(self, a, *args, **kwargs):
super().__init__(methodName="runTest", *args, **kwargs)
self.a = a
def setUp(self):
# something stateful that depends on self.a in the real use case
self.count = 0
def tearDown(self):
del self.count
def runTest(self):
self.test_a()
def test_a(self):
self.count += 1
self.assertGreaterEqual(self.a, 0)
test_data = tuple(range(5))
test_cases = tuple(MyTest(a) for a in test_data)
def suite():
test_suite = TestSuite()
test_suite.addTests(test_cases)
return test_suite
这起作用
我可以使用TextTestRunner
from unittest import TextTestRunner
TextTestRunner().run(suite())
正常工作。
失败尝试1
我想使用unittests.main
:
from unittest import main
main(verbosity=3)
首先运行良好的
(数字0, 1, .., 4
通过测试(,但随后将第六个参数传递给Funciton:str
ING 'test_a'
;这里的测试当然会失败。
尝试失败2
,但Ulitmate的目标是使用unittest.TestLoader().discover()
(将从其他Python模块运行(:
from unittest import TestLoader
from pathlib import Path
FILE = Path(__file__)
HERE_DIR = Path(FILE).parent
loader = TestLoader()
discovered_suite = loader.discover(start_dir=str(HERE_DIR), pattern=FILE.name)
TextTestRunner().run(discovered_suite)
如果我这样做,则 loader.discover(...)
再次初始化了 MyTest
六次而不是五个;最后一次使用str
ING 'test_a'
。
问题
如何使用一个TestCase
和多个参数以某种方式设置此测试,我可以使用unittest.TestLoader().discover()
运行它?
我终于找到了可能有帮助的:在模块中添加load_tests
方法:
def load_tests(loader, standard_tests, pattern):
return suite()
小警告:该测试仍在第6次初始化,如上所述...如何避免这种情况?
,因为如果MyTest
采用了多个参数:
class MyTest(TestCase):
def __init__(self, a, b, *args, **kwargs):
....
test_cases = tuple(MyTest(a, a) for a in test_data)
当加载程序试图通过'test_a'
作为参数时,这将导致测试崩溃:
TypeError: __init__() missing 1 required positional argument: 'b'
最后我放弃了,去了一个混合蛋白型方法(这里是2个成员的示例: a
和 b
(:
class MyTest:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def setUp(self):
# something stateful in the real use case
self.count = 0
def tearDown(self):
del self.count
def runTest(self):
self.test_a()
def test_a(self):
self.count += 1
self.assertGreaterEqual(self.a, 0)
class Test0(MyTest, TestCase):
a = 0
b = 0
class Test1(MyTest, TestCase):
a = 1
b = 1
if __name__ == "__main__":
main(verbosity=3)