在进行自动化测试的过程中,我们一定会有这样的需求:希望失败的用例可以自动重跑
在pytest中,提供了pytest-rerunfailures插件可以实现自动重跑的效果
pip3 install pytest-rerunfailures -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
命令行参数:--reruns n
(重新运行次数),--reruns-delay m
(等待运行秒数)
装饰器参数:reruns=n
(重新运行次数),reruns_delay=m
(等待运行秒数)
如果需要把所有失败的用例都重新运行,使用 --reruns 命令,并且制定要运行的最大次数,举个:
# FileName: test_03.py
class TestDemo:
def setup(self):
print("执行setup method方法")
def teardown(self):
print("执行teardown方法")
def test_case1(self):
print("执行测试用例1")
assert 1 + 1 == 3
def test_case2(self):
print("执行测试用例2")
assert 1 + 3 == 6
def test_case3(self):
print("执行测试用例3")
assert 1 + 3 == 4
执行pytest test_03.py --reruns 2 -vs
结果如下:
可以看到,运行失败的 fixture 或 setup_class 也将重新执行
可以使用 --reruns-delay 命令行选项,指定下次测试重新开始之前等待的秒数,举个:
还是上面的case,执行pytest test_03.py --reruns 2 --reruns_delay 10 -vs
结果如下:
可以看到,重跑被挂起(在执行setup之前被挂起),且执行总时间增加了近40s
如果在测试时,只希望在某一条测试用例失败后重新执行,可以使用flaky装饰器 @pytest.mark.flaky(reruns=, reruns_delay=)
reruns 指定重跑的次数
reruns_delay 指定重跑的延迟时间
举个:
# FileName: test_03.py
import pytest
class TestDemo:
def setup(self):
print("执行setup method方法")
def teardown(self):
print("执行teardown方法")
@pytest.mark.flaky(reruns=2, reruns_delay=10)
def test_case1(self):
print("执行测试用例1")
assert 1 + 1 == 3
def test_case2(self):
print("执行测试用例2")
assert 1 + 3 == 6
def test_case3(self):
print("执行测试用例3")
assert 1 + 3 == 4
如果指定了用例的重新运行次数,在命令行添加的 --reruns 对这些用例是不会生效的,即:
使用了flaky装饰器的用例,不会再受命令行参数的
--reruns
的影响
@pytest.fixture()
一起使用--looponfail #在子进程中重复运行测试。每次运行后,pytest 都会等待项目中的文件发生更改,然后重新运行之前失败的测试。重复此过程,直到所有测试都通过,然后再次执行完整运行
pytest --pdb # 每次遇到失败都跳转到 PDB
# pdb 是 Python 标准库的调试模块。在 pytest 中,可以直接使用 --pdb 参数在测试失败时开启调试