接口自动化测试框架 - 5-3 Pytest - 常用插件-测试报告-失败重试

3. Pytest - 常用插件

插件列表网址:https://plugincompat.herokuapp.com 包含很多插件包,大家可依据工作的需求选择使用。

3.1 测试报告

  • 应用场景

    自动化测试脚本最终执行是通过还是不通过,需要通过测试报告进行体现。

  • 安装

    $ pip3 install pytest-html 
    
  • 使用

    在配置文件中的命令行参数中增加 --html=用户路径/report.html

  • 示例

    pytest.ini
    
    addopts = -s --html=report/report.html
    
  • 结果

    在项目目录下会对一个 report 文件夹,里面有个 report.html 即为测试报告

3.2 控制函数执行顺序

  • 应用场景

    现实生活中,如果想下订单,必须先登录,我们可以通过插件的形式来控制函数执行的顺序。

  • 安装

    $ pip3 install pytest-ordering 
    
  • 使用

    1. 标记于被测试函数,@pytest.mark.run(order=x)
    2. 根据order传入的参数来解决运行顺序
    3. order值全为正数或全为负数时,运行顺序:值越小,优先级越高
    4. 正数和负数同时存在:正数优先级高
  • 示例

    import pytest
    
    class TestLogin:
    	def test_hello_001(self):
    		print("test_hello_001")
    	@pytest.mark.run(order=1)
      
    	def test_hello_002(self):
    		print("test_hello_002")
        
    	@pytest.mark.run(order=2)
    	def test_hello_003(self):
    		print("test_hello_003")
    
  • 结果

    scripts/test_login.py test_hello_002 # 先运行2
    
    .test_hello_003 # 再运行3
    
    .test_hello_001
    

3.3 失败重试

  • 应用场景

    自动化测试脚本可能会使用到网络,如果网络不好可能最终会使脚本不通过。像这种情况可能并不是脚本本身的问题,仅仅是因为网络忽快忽慢,那么我们可以使用失败重试的插件,当失败后尝试再次运行。一般情况最终成功可以视为成功,但最好进行进行排查时候是脚本问题。

  • 安装

    pip3 install pytest-rerunfailures 
    
  • 使用

    在配置文件中的命令行参数中增加 --reruns n

  • 示例

    pytest.ini

    addopts = -s --reruns 3
    

    test_login.py

    class TestLogin:
    
    	def test_a(self): # test开头的测试函数
    		print("------->test_a")
    		assert 1 # 断言成功
    	
    	def test_b(self):
    		print("------->test_b")
    		assert 0 # 断言失败
    
  • 结果

    scripts/test_login.py ------->test_a
    .------->test_b
    R------->test_b
    R------->test_b
    R------->test_b
    F
    

R 表示重试

  • 注意点

    重试时,如果脚本通过,那么后续不再重试

    .test_hello_003 # 再运行3
    .test_hello_001
    

如果你期望加上出错重试的等待时间,请使用如下命令(reruns-delay是等待时间):

pytest --reruns 5 --reruns-delay 1

如果你只想对某几个测试用例应用重试策略,你可以使用装饰器:

@pytest.mark.flaky(reruns=5, reruns_delay=2)

例如:

@pytest.mark.flaky(reruns=5, reruns_delay=2)
def test_example():
    import random
    assert random.choice([True, False])

其它参数

pytest --maxfail=10 #失败超过10次则停止运行
pytest -x test_demo.py #出现失败则停止
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值