pythonunittest:我们可以重复单元测试用例的执行次数吗?

2024-05-17 04:02:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我们可以重复单元测试用例执行一个可配置的次数吗?在

例如,我有一个名为Test_MyHardware的单元测试脚本,它包含两个测试用例test_customHardware1和{}。在

有没有办法用Python的unittest模块重复执行test_customHardware1200次和test_customHardware2500次?在

:上述情况已简化。实际上,我们会有1000个测试用例。在


Tags: 模块test脚本测试用例单元测试unittest次数单元
2条回答

更好的选择是用exit=False多次调用unittest.main()。此示例将重复的次数作为参数,并调用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)

这允许更大的灵活性,因为它将按指定次数运行用户请求的所有测试。在

您需要导入:

^{pr2}$

虽然unittest module没有相应的选项,但是有几种方法可以实现这一点:

  • 您可以(ab)使用timeit module重复调用测试方法。记住:测试方法和普通方法一样,你可以自己调用它们。不需要特殊的魔法。在
  • 您可以使用decorators来实现这一点:

    #!/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()
    

相关问题 更多 >