[英]Python unittest: Can we repeat Unit test case execution for a configurable number of times?
Can we repeat Unit test case execution for a configurable number of times?我们可以重复执行单元测试用例可配置的次数吗?
For example, I have a Unit test script named Test_MyHardware
that contains couple of test cases test_customHardware1
and test_customHardware2
.例如,我有一个名为Test_MyHardware
的单元测试脚本,其中包含几个测试用例test_customHardware1
和test_customHardware2
。
Is there a way to repeat the execution of test_customHardware1
200 times and test_customHardware2
500 times with Python's unittest module?有没有办法使用 Python 的 unittest 模块重复执行test_customHardware1
200 次和test_customHardware2
500 次?
Note : The above case presented is simplified.注意:上述案例是简化的。 In practise, we would have 1000s of test cases.实际上,我们将有 1000 个测试用例。
While the unittest module has no options for that, there are several ways to achieve this: 虽然unittest模块没有选项,但有几种方法可以实现此目的:
You can use decorators to achieve this: 您可以使用装饰器来实现此目的:
#!/usr/bin/env python import unittest def repeat(times): def repeatHelper(f): def callHelper(*args): for i in range(0, times): f(*args) return callHelper return repeatHelper class SomeTests(unittest.TestCase): @repeat(10) def test_me(self): print "You will see me 10 times" if __name__ == '__main__': unittest.main()
A better option is to call unittest.main()
multiple times with exit=False
. 更好的选择是使用exit=False
多次调用unittest.main()
。 This example takes the number of times to repeat as an argument and calls unittest.main
that number of times: 此示例将重复次数作为参数并调用unittest.main
该次数:
parser = argparse.ArgumentParser()
parser.add_argument("-r", "--repeat", dest="repeat", help="repeat tests")
(args, unitargs) = parser.parse_known_args()
unitargs.insert(0, "placeholder") # unittest ignores first arg
# add more arguments to unitargs here
repeat = vars(args)["repeat"]
if repeat == None:
repeat = 1
else:
repeat = int(repeat)
for iteration in range(repeat):
wasSuccessful = unittest.main(exit=False, argv=unitargs).result.wasSuccessful()
if not wasSuccessful:
sys.exit(1)
This allows much greater flexibility since it will run all tests the user requested the number of times specified. 这允许更大的灵活性,因为它将运行用户请求指定次数的所有测试。
You'll need to import: 你需要导入:
import unittest
import argparse
Adding these 2 lines of code helped me.添加这两行代码对我有帮助。 Multiple tests can be added in addition to 'test_customHardware1' in below array.除了下面数组中的“test_customHardware1”之外,还可以添加多个测试。
repeat_nos = 10
unittest.TextTestRunner().run(unittest.TestSuite (map (Test_MyHardware, ['test_customHardware1' ]*repeat_nos)))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.