微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

『德不孤』Pytest框架 — 5、Pytest失败重试

Pytest失败重试就是,在执行一次测试脚本时,如果一个测试用例执行结果失败了,则重新执行该测试用例。

前提:

Pytest测试框架失败重试需要下载pytest-rerunfailures插件

安装方式:pip install pytest-rerunfailures

Pytest实现失败重试的方式:

方式一:在命令行或者main()函数中使用。

pytest.main(['-vs','test_a.py','--reruns=2'])(这种方式没有实现成功,可能自己环境的问题)

或者:

pytest -vs ./test_a.py --reruns 2 --reruns-delay 2(可以)

表示:失败重试2次,在每次重试前会等到2秒。

说明: reruns为重跑次数reruns_delay为间隔时间,单位s

方式二:在pytest.ini配置文件中使用。(推荐)

pytest.ini配置文件addopts添加reruns重试参数

[pytest]
addopts = -s --reruns 2 --reruns-delay 2
testpaths = scripts
python_files = test_01.py
python_classes = Test*
python_functions = test*

示例:使用第二种方式:

"""
1.学习目标
    掌握pytest中用例失败重试方法
2.操作步骤
    2.1 安装 pytest-rerunfailures
        pip install pytest-rerunfailures
    2.2 使用 在pytest.ini文件中,添加一个命令行参数  
        --reruns n # n表示重试次数
3.需求
"""
# 1.导入pytest
import pytest


# 2.编写测试用例
@pytest.mark.run(order=2)
def test_login():
    """登录用例"""
    print("登录步骤")
    assert "abcd" in "abcdefg"


@pytest.mark.run(order=1)
def test_register():
    """注册用例"""
    print("注册步骤")
    assert False


@pytest.mark.run(order=4)
def test_shopping():
    """购物下单"""
    print("购物流程")
    assert True


@pytest.mark.run(order=3)
def test_cart():
    """购物车用例"""
    print("购物车流程")
    assert True


if __name__ == '__main__':
    pytest.main(['-vs', 'test_01.py', '--reruns=2'])

# pytest ./pytest_demo/test_01.py --reruns 10 --reruns-delay 1
#
"""
执行结果:注意有两个:2 rerun
==================== 1 Failed, 3 passed, 2 rerun in 0.09s =====================

test_01.py::test_register 注册步骤
RERUN
test_01.py::test_register 注册步骤
RERUN
test_01.py::test_register 注册步骤
Failed
pytest_demo\test_01.py:20 (test_register)
@pytest.mark.run(order=1)
    def test_register():
        ""注册用例""
        print("注册步骤")
>       assert False
E       assert False

test_01.py:25: AssertionError
登录步骤
PASSED购物车流程
PASSED购物流程
PASSED
"""

注意:如果设置失败重试5次,在重试的过程中成功了,就不用全部跑完5次重试,这里需要注意一下。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐