1、前言
- 平常在做功能测试的时候,经常会遇到某个模块不稳定,偶尔会出现一些bug,对于这种问题我们可以针对此用例反复执行多次,最终复现出问题来
- 自动化运行用例的时候,也会出现偶然的bug,可以针对单个用例,或者针对某个模块的用例重复执行多次
2、环境要求
- Python2.7、3.4+或PyPy
- pytest2.8 或者更高版本
3、安装插件
pip install pytest-repeat -i https://pypi.tuna.tsinghua.edu.cn/simple
4、使用场景
场景一:重复执行
重复执行用例2次,使用命令:pytest test_01.py -s --count 2 或者 pytest test_01.py -s --count=2
场景二:重复执行直到失败
- 如果需要验证偶现问题,可以将pytest的
-x与pytest-repeat结合,以强制运行程序在第一次失败时停止pytest --count 1000 -x test_01.py - 代码
def test_01(): import random flag = random.choice([False, True, True, True]) print(flag) assert flag - 执行命令:
pytest --count 100 -x test_01.py -s - 结果
=========================================================================== test session starts ============================================================================ collected 100 items test_01.py True .True .True .True .True .False F ================================================================================= FAILURES ================================================================================= _____________________________________________________________________________ test_01[6-1000] ______________________________________________________________________________ def test_01(): import random flag = random.choice([False, True, True, True]) print(flag) > assert flag E assert False test_01.py:15: AssertionError ====================================================

本文介绍了如何使用pytest-repeat插件在Python测试中重复执行测试用例,以帮助定位偶发性bug。通过命令行参数`--count`可以指定用例重复次数,结合`-x`选项可验证偶发问题。此外,还展示了如何通过`@pytest.mark.repeat`装饰器以及`--repeat-scope`参数控制重复执行的范围,如函数、类或模块级别。对于不兼容unittest.TestCase的情况也进行了说明。

1333

被折叠的 条评论
为什么被折叠?



