Python自动化之pytest常用插件

目录

1、失败重跑 pytest-rerunfailures

2、多重校验 pytest-assume

3、设定执行顺序 pytest-ordering

4、用例依赖(pytest-dependency)

5.分布式测试(pytest-xdist)

6.生成报告(pytest-html)


1、失败重跑 pytest-rerunfailures

  安装:pip install pytest-rerunfailures

  使用:pytest test_class.py --reruns 5 --reruns-delay 1 -vs (失败后重新运行5次,每次间隔1秒)

     @pytest.mark.flaky(reruns = 5 ,reruns-delay = 1 ) 指定某个用例

#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:chenshifeng
@file:test_calc2.py
@time:2020/09/16
"""import pytest@pytest.mark.parametrize('a,b,result', [(1, 1, 3),(2, 2, 4),(100, 100, 200),(0.1, 0.1, 0.2),(-1, -1, -2)
], ids=['int', 'int', 'bignum', 'float', 'fushu'])  # 参数化
def test_add(a, b, result):# cal = Calculator()assert result == a + b

命令行执行:

pytest test_calc2.py --reruns 5 --reruns-delay 1 -vs

结果如下:

============================================================================= test session starts =============================================================================
platform darwin -- Python 3.6.4, pytest-6.0.2, py-1.9.0, pluggy-0.13.1 -- /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6
cachedir: .pytest_cache
rootdir: /Users/chenshifeng/MyCode/PythonCode/SFDSZL/test_pytest, configfile: pytest.ini
plugins: rerunfailures-9.1, dependency-0.5.1, ordering-0.6, assume-2.3.2
collected 5 items                                                                                                                                                             test_calc2.py::test_add[int0] RERUN
test_calc2.py::test_add[int0] RERUN
test_calc2.py::test_add[int0] RERUN
test_calc2.py::test_add[int0] RERUN
test_calc2.py::test_add[int0] RERUN
test_calc2.py::test_add[int0] FAILED
test_calc2.py::test_add[int1] PASSED
test_calc2.py::test_add[bignum] PASSED
test_calc2.py::test_add[float] PASSED
test_calc2.py::test_add[fushu] PASSED================================================================================== FAILURES ===================================================================================
_______________________________________________________________________________ test_add[int0] ________________________________________________________________________________a = 1, b = 1, result = 3@pytest.mark.parametrize('a,b,result', [(1, 1, 3),(2, 2, 4),(100, 100, 200),(0.1, 0.1, 0.2),(-1, -1, -2)], ids=['int', 'int', 'bignum', 'float', 'fushu'])  # 参数化def test_add(a, b, result):cal = Calculator()
>       assert result == cal.add(a, b)
E       assert 3 == 2
E         +3
E         -2test_calc2.py:26: AssertionError
=========================================================================== short test summary info ===========================================================================
FAILED test_calc2.py::test_add[int0] - assert 3 == 2
==================================================================== 1 failed, 4 passed, 5 rerun in 5.11s =====================================================================

通过装饰器设置重跑次数与延时时间

#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:chenshifeng
@file:test_calc2.py
@time:2020/09/16
"""import pytest@pytest.mark.parametrize('a,b,result', [(1, 1, 3),(2, 2, 4),(100, 100, 200),(0.1, 0.1, 0.2),(-1, -1, -2)
], ids=['int', 'int', 'bignum', 'float', 'fushu'])  # 参数化
# 通过装饰器设置重跑次数
@pytest.mark.flaky(reruns=6, reruns_delay=2)
def test_add(a, b, result):# cal = Calculator()assert result == a + b

结果:

Testing started at 10:10 下午 ...
/usr/local/bin/python3.6 "/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/pycharm/_jb_pytest_runner.py" --target test_calc2.py::test_add
Launching pytest with arguments test_calc2.py::test_add in /Users/chenshifeng/MyCode/PythonCode/SFDSZL/test_pytest/testcode============================= test session starts ==============================
platform darwin -- Python 3.6.4, pytest-6.0.2, py-1.9.0, pluggy-0.13.1 -- /usr/local/bin/python3.6
cachedir: .pytest_cache
rootdir: /Users/chenshifeng/MyCode/PythonCode/SFDSZL/test_pytest, configfile: pytest.ini
plugins: rerunfailures-9.1, dependency-0.5.1, ordering-0.6, assume-2.3.2
collecting ... collected 5 itemstest_calc2.py::test_add[int0] RERUN                                      [ 20%]
test_calc2.py::test_add[int0] RERUN                                      [ 20%]
test_calc2.py::test_add[int0] RERUN                                      [ 20%]
test_calc2.py::test_add[int0] RERUN                                      [ 20%]
test_calc2.py::test_add[int0] RERUN                                      [ 20%]
test_calc2.py::test_add[int0] RERUN                                      [ 20%]
test_calc2.py::test_add[int0] FAILED                                     [ 20%]
testcode/test_calc2.py:11 (test_add[int0])
3 != 2Expected :2
Actual   :3
<Click to see difference>a = 1, b = 1, result = 3@pytest.mark.parametrize('a,b,result', [(1, 1, 3),(2, 2, 4),(100, 100, 200),(0.1, 0.1, 0.2),(-1, -1, -2)], ids=['int', 'int', 'bignum', 'float', 'fushu'])  # 参数化# 通过装饰器设置重跑次数@pytest.mark.flaky(reruns=6, reruns_delay=2)def test_add(a, b, result):# cal = Calculator()
>       assert result == a + b
E       assert 3 == 2test_calc2.py:23: AssertionError
PASSED                                     [ 40%]PASSED                                   [ 60%]PASSED                                    [ 80%]PASSED                                    [100%]
Assertion failedAssertion failedAssertion failedAssertion failedtest_calc2.py::test_add[int1] 
test_calc2.py::test_add[bignum] 
test_calc2.py::test_add[float] 
test_calc2.py::test_add[fushu] =================================== FAILURES ===================================
________________________________ test_add[int0] ________________________________a = 1, b = 1, result = 3@pytest.mark.parametrize('a,b,result', [(1, 1, 3),(2, 2, 4),(100, 100, 200),(0.1, 0.1, 0.2),(-1, -1, -2)], ids=['int', 'int', 'bignum', 'float', 'fushu'])  # 参数化# 通过装饰器设置重跑次数@pytest.mark.flaky(reruns=6, reruns_delay=2)def test_add(a, b, result):# cal = Calculator()
>       assert result == a + b
E       assert 3 == 2test_calc2.py:23: AssertionError
=========================== short test summary info ============================
FAILED test_calc2.py::test_add[int0] - assert 3 == 2
==================== 1 failed, 4 passed, 6 rerun in 12.13s =====================Process finished with exit code 1Assertion failedAssertion failedAssertion failedAssertion failed

2、多重校验 pytest-assume

  正常情况下一条用例如果有多条断言,一条断言失败了,其他断言就不会执行了,而使用pytest-assume可以继续执行下面的断言

    安装 : pip install pytest-assume

    执行 : pytest.assume(1==3)

for example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:chenshifeng
@file:test_calc2.py
@time:2020/09/16
"""import pytestdef test_assume():print('登录操作')pytest.assume(1 == 2)print('搜索操作')pytest.assume(2 == 2)print('加购操作')pytest.assume(3 == 2)

运行结果:

Testing started at 10:23 下午 ...
/usr/local/bin/python3.6 "/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/pycharm/_jb_pytest_runner.py" --target test_calc2.py::test_assume
Launching pytest with arguments test_calc2.py::test_assume in /Users/chenshifeng/MyCode/PythonCode/SFDSZL/test_pytest/testcode============================= test session starts ==============================
platform darwin -- Python 3.6.4, pytest-6.0.2, py-1.9.0, pluggy-0.13.1 -- /usr/local/bin/python3.6
cachedir: .pytest_cache
rootdir: /Users/chenshifeng/MyCode/PythonCode/SFDSZL/test_pytest, configfile: pytest.ini
plugins: rerunfailures-9.1, dependency-0.5.1, ordering-0.6, assume-2.3.2
collecting ... collected 1 itemtest_calc2.py::test_assume FAILED                                        [100%]登录操作
搜索操作
加购操作testcode/test_calc2.py:11 (test_assume)
tp = <class 'pytest_assume.plugin.FailedAssumption'>, value = None, tb = Nonedef reraise(tp, value, tb=None):try:if value is None:value = tp()if value.__traceback__ is not tb:
>               raise value.with_traceback(tb)
E               pytest_assume.plugin.FailedAssumption: 
E               2 Failed Assumptions:
E               
E               test_calc2.py:14: AssumptionFailure
E               >>    pytest.assume(1 == 2)
E               AssertionError: assert False
E               
E               test_calc2.py:18: AssumptionFailure
E               >>    pytest.assume(3 == 2)
E               AssertionError: assert False/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/six.py:702: FailedAssumptionAssertion failedAssertion failed=================================== FAILURES ===================================
_________________________________ test_assume __________________________________tp = <class 'pytest_assume.plugin.FailedAssumption'>, value = None, tb = Nonedef reraise(tp, value, tb=None):try:if value is None:value = tp()if value.__traceback__ is not tb:
>               raise value.with_traceback(tb)
E               pytest_assume.plugin.FailedAssumption: 
E               2 Failed Assumptions:
E               
E               test_calc2.py:14: AssumptionFailure
E               >>    pytest.assume(1 == 2)
E               AssertionError: assert False
E               
E               test_calc2.py:18: AssumptionFailure
E               >>    pytest.assume(3 == 2)
E               AssertionError: assert False/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/six.py:702: FailedAssumption
----------------------------- Captured stdout call -----------------------------
登录操作
搜索操作
加购操作
=========================== short test summary info ============================
FAILED test_calc2.py::test_assume - pytest_assume.plugin.FailedAssumption: 
============================== 1 failed in 0.09s ===============================Process finished with exit code 1Assertion failedAssertion failedAssertion failedAssertion failed

3、设定执行顺序 pytest-ordering

  正常情况下,用例默认执行顺序是自上而下的,对于一些有上下文依赖关系的用例,可是通过 pytest-ordering 来设置执行顺序,当然,通过setup、teardown和fixture来解决也是可以的

  安装插件 : pip install pytest-ordering

  使用方法 : @pytest.mark.run(order=2)

  需要注意的是,当有多个装饰器的时候,可能会发生冲突(比如参数化)

For example, this:

import pytest@pytest.mark.run(order=2)
def test_foo():assert True@pytest.mark.run(order=1)
def test_bar():assert True

Yields this output:

============================= test session starts ==============================
platform darwin -- Python 3.6.4, pytest-6.0.2, py-1.9.0, pluggy-0.13.1 -- /usr/local/bin/python3.6
cachedir: .pytest_cache
rootdir: /Users/chenshifeng/MyCode/PythonCode/SFDSZL/test_pytest, configfile: pytest.ini
plugins: rerunfailures-9.1, dependency-0.5.1, ordering-0.6, assume-2.3.2
collecting ... collected 2 itemstest_ordering.py::test_bar 
test_ordering.py::test_foo ============================== 2 passed in 0.02s ===============================

4、用例依赖(pytest-dependency)

使用该插件可以标记一个testcase作为其他testcase的依赖,当依赖项执行失败时,那些依赖它的test将会被跳过。

安装 : pip install pytest-dependency

使用方法: 用 @pytest.mark.dependency()对所依赖的方法进行标记,使用@pytest.mark.dependency(depends=["test_name"])引用依赖,test_name可以是多个。

上用例:

import pytest@pytest.mark.dependency()
def test_01():assert False@pytest.mark.dependency(depends=["test_01"])
def test_02():print("执行测试2")

output:

=========================== short test summary info ============================
FAILED test_ordering.py::test_01 - assert False
========================= 1 failed, 1 skipped in 0.06s =========================Process finished with exit code 1

5.分布式测试(pytest-xdist)

  • 平常我们功能测试用例非常多时,比如有1千条用例,假设每个用例执行需要1分钟,如果单个测试人员执行需要1000分钟才能跑完
  • 当项目非常紧急时,会需要协调多个测试资源来把任务分成两部分,于是执行时间缩短一半,如果有10个小伙伴,那么执行时间就会变成十分之一,大大节省了测试时间
  • 为了节省项目测试时间,10个测试同时并行测试,这就是一种分布式场景

 分布式执行用例的原则:

  • 用例之间是独立的,没有依赖关系,完全可以独立运行用例执行没有顺序要求,随机顺序都能正常执行每个用例都能重复运行,运行结果不会影响其他用例

  插件安装:
      pip3 install pytest-xdist -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

  使用方法:

      pytest -n 2 (2代表2个CPU)

      pytest -n auto

  •   n auto:可以自动检测到系统的CPU核数;从测试结果来看,检测到的是逻辑处理器的数量,即假12核  使用auto等于利用了所有CPU来跑用例,此时CPU占用率会特别高

6.生成报告(pytest-html)

pytest-html是一个插件,pytest用于生成测试结果的HTML报告。兼容Python 2.7,3.6

安装插件: pip install pytest-html

使用方法: pytest --html=report.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/22842.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Unity游戏源码分享-Unity5.4.1打砖块游戏Breakout_Game_Starter_Kit

Unity5.4.1打砖块游戏Breakout_Game_Starter_Kit 童年的回忆 项目地址&#xff1a;https://download.csdn.net/download/Highning0007/88042779Unity游戏源码分享-

SpringCloud——消息总线Bus

SpringCloud Bus将分布式系统的节点与轻量级消息系统链接起来的框架&#xff0c;是对SpringCloud Config的加强&#xff0c;广播自动版的配置。 支持两种消息代理&#xff1a;RabbitMQ和Kafka 一、创建工程&#xff0c;添加依赖 spring-cloud-starter-config spring-cloud-st…

(转载)从0开始学matlab(第1天)—变量和数组

MATLAB 程序的基本数据单元是数组。一个数组是以行和列组织起来的数据集合&#xff0c;并且拥有一个数组名。数组中的单个数据是可以被访问的&#xff0c;访问的方法是数组名后带一个括号&#xff0c;括号内是这个数据所对应行标和列标。标量在 MATLAB 中也被当作数组来处理——…

centos 配置好网络后无法ping 通百度

问题&#xff1a; ping 自己配置的ip地址能够ping通&#xff0c;ping 连接的WiFi &#xff08;可以上外网&#xff09;地址也能ping通&#xff0c;但是ping www.baidu.com 却ping不同&#xff1b; 配置 处理方法&#xff1a; 我的虚拟机开通了三张网卡&#xff0c;150段…

GB35114双向身份认证(A级)学习笔记

GB35114双向身份验证学习笔记 温故而知新 SSL单向认证 摘录自&#xff1a;https://blog.csdn.net/qq_45759354/article/details/128672828 SSL协议用到了对称加密和非对称加密&#xff0c;在建立连接时&#xff0c;SSL首先对对称加密密钥使用非对称加密。连接建立好后&…

【量化课程】02_1.宏观经济学基础概念

2.1_宏观经济学基础概念 文章目录 2.1_宏观经济学基础概念1. 宏观经济简单背景1.1 微观经济学时期1.2 宏观经济学开端1.3 宏观经济学研究的问题1.4 宏观经济与理财的联系 2. 宏观经济分析及关键指标2.1 教材中的宏观经济分析框架和指标2.1.1 国内生产总值GDP2.1.2 边际消费倾向…

Docker:overlay2浅析以及解决overlay2 文件过大的问题

最近在学习docker的实现时看到这么一个概念&#xff1a;Union File System&#xff0c;先让我们来介绍介绍它。 Union File System 定义&#xff1a;联合文件系统&#xff08;UnionFS&#xff09;是一种分层、轻量级并且高性能的文件系统&#xff0c;它支持对文件系统的修改作…

微信小程序音频播放失败:TypeError: Cannot read property ‘duration‘ of undefined

报错截图 最下面这个this.setData()报错可不用理会&#xff0c;是this取值的问题 解决 需要播放和暂停功能时&#xff0c;需要把audio以及他的src放在Page外面。不能缺少 audioCtx.onPlay() 和 audioCtx.onError()两个方法&#xff0c;且需要放在play()方法之前如果在wx.crea…

Bash 有效电话号码

193 有效电话号码 给定一个包含电话号码列表&#xff08;一行一个电话号码&#xff09;的文本文件 file.txt&#xff0c;写一个单行 bash 脚本输出所有有效的电话号码。 你可以假设一个有效的电话号码必须满足以下两种格式&#xff1a; (xxx) xxx-xxxx 或 xxx-xxx-xxxx。&…

apple pencil一代的平替有哪些品牌?苹果平板的触控笔

随着苹果Pencil系列的推出&#xff0c;平替电容笔在国内市场得到了较好的发展&#xff0c;随之的销量&#xff0c;也开始暴涨&#xff0c;苹果pencil因为价格太高&#xff0c;导致很多人买不起。目前市场上&#xff0c;有不少的平替电容笔&#xff0c;可以替代苹果的Pencil&…

StringBuffer类 StringBuilder 类

StringBuffer类 介绍 StringBuffer是一个容器&#xff0c;代表可变的字符序列&#xff0c;可以对字符串内容进行增删。 StringBuffer是可变长度的。 实现了序列化接口&#xff0c;可实现串行化&#xff08;可以将内容保存至文件或者网络传输&#xff09;&#xff1a; Serial…

webpack项目和vue项目发布,浏览器存在缓存

项目是webpack搭建的每次发步到线上&#xff0c;经常需要手动清楚浏览器缓存才能有效果。vue项目设置在最下面 项目打包的js&#xff08;css也是一致&#xff09;名称都采用哈希值 问题&#xff1a;哈希值在有些情况下打包会不变&#xff0c;导致浏览器使用自己缓存的资源 解…