如何在python中自动将十几个测试用例添加到测试套件中 [英] how to add dozen of test cases to a test suite automatically in python
问题描述
我在不同的文件夹中有十几个测试用例.在根目录中有一个测试运行器.
i have dozen of test cases in different folders. In the root directory there is a test runner.
unittest\
package1\
test1.py
test2.py
package2\
test3.py
test4.py
testrunner.py
目前我手动将四个测试用例添加到测试套件中
Currently I added the four test cases manually into a test suite
import unittest
from package1.test1 import Test1
from package1.test2 import Test2
from package2.test3 import Test3
from package2.test4 import Test4
suite = unittest.TestSuite()
suite.addTests(unittest.makeSuite(Test1))
suite.addTests(unittest.makeSuite(Test2))
suite.addTests(unittest.makeSuite(Test3))
suite.addTests(unittest.makeSuite(Test4))
result = unittest.TextTestRunner(verbosity=2).run(suite)
if not result.wasSuccessful():
sys.exit(1)
如何让测试运行程序自动测试所有测试用例?如:
How to let test runner test all test cases automatically? Such as:
for testCase in findTestCases():
suite.addTests(testCase)
推荐答案
上述模块很好,但当尝试输入参数时,NoseTests 可能很有趣,而且这也更快,并且很好地适合另一个模块.
The above modules are good but NoseTests can be funny when trying to enter in parameters and this is also faster and fit's into another module nicely.
import os, unittest
class Tests():
def suite(self): #Function stores all the modules to be tested
modules_to_test = []
test_dir = os.listdir('.')
for test in test_dir:
if test.startswith('test') and test.endswith('.py'):
modules_to_test.append(test.rstrip('.py'))
alltests = unittest.TestSuite()
for module in map(__import__, modules_to_test):
module.testvars = ["variables you want to pass through"]
alltests.addTest(unittest.findTestCases(module))
return alltests
if __name__ == '__main__':
MyTests = Tests()
unittest.main(defaultTest='MyTests.suite')
如果您想将结果添加到日志文件中,请在末尾添加:
If you want to add results to a log file add this at the end instead:
if __name__ == '__main__':
MyTests = Tests()
log_file = 'log_file.txt'
f = open(log_file, "w")
runner = unittest.TextTestRunner(f)
unittest.main(defaultTest='MyTests.suite', testRunner=runner)
也在你正在测试的模块底部放置这样的代码:
Also at the bottom of the modules you are testing place code like this:
class SomeTestSuite(unittest.TestSuite):
# Tests to be tested by test suite
def makeRemoveAudioSource():
suite = unittest.TestSuite()
suite.AddTest(TestSomething("TestSomeClass"))
return suite
def suite():
return unittest.makeSuite(TestSomething)
if __name__ == '__main__':
unittest.main()
这篇关于如何在python中自动将十几个测试用例添加到测试套件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!