Python自动化——pytest常用插件详解
haoteby 2025-05-09 18:43 8 浏览
前言
Pytest是Python的一种单元测试框架,与unittest相比,使用起来更简洁、效率更高,也是目前大部分使用python编写测试用例的小伙伴们的第一选择了。
除了框架本身提供的功能外,Pytest还支持上百种第三方插件,良好的扩展性可以更好的满足大家在用例设计时的不同需求。本文将为大家详细介绍下面6项常用的插件。废话就不多说了我们直接开始吧。
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 -2
test_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 items
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] RERUN [ 20%]
test_calc2.py::test_add[int0] FAILED [ 20%]
testcode/test_calc2.py:11 (test_add[int0])
3 != 2
Expected :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 == 2
test_calc2.py:23: AssertionError
PASSED [ 40%]PASSED [ 60%]PASSED [ 80%]PASSED [100%]
Assertion failed
Assertion failed
Assertion failed
Assertion failed
test_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 == 2
test_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 1
Assertion failed
Assertion failed
Assertion failed
Assertion 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 pytest
def 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 item
test_calc2.py::test_assume FAILED [100%]登录操作
搜索操作
加购操作
testcode/test_calc2.py:11 (test_assume)
tp = <class 'pytest_assume.plugin.FailedAssumption'>, value = None, tb = None
def 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
Assertion failed
Assertion failed
=================================== FAILURES ===================================
_________________________________ test_assume __________________________________
tp = <class 'pytest_assume.plugin.FailedAssumption'>, value = None, tb = None
def 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 1
Assertion failed
Assertion failed
Assertion failed
Assertion 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 items
test_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
- nauto:可以自动检测到系统的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
7、总结
本文为大家介绍了一些常用的pytest框架的插件,可以帮助我们解决一些实际使用过程中遇到的问题。目前,pytest支持的插件有很多个,除了本文介绍的6个常用插件外,还有很多支持其它需求的插件,大家可以根据自己的需要尝试查找使用相关的插件,以便能够更好的设计出符合业务场景的测试用例。
喜欢本文可以点赞加关注哟。小编每天都会分享不同的东西哟,关注小编和小编一起学习。
相关推荐
- 网站seo该怎么优化
-
一、网站定位在建设一个网站之前,我们首先要做的就是一个网站清晰的定位,会带来转化率相对较高的客户群体,我们建站的目的就是为了营销,只有集中来做某一件事,才会更好的展现我们的网站。在做SEO优化的同时...
- 3个小技巧教你如何做好SEO优化
-
想半路出家做SEO?可是,怎么才做的好呢?关于SEO专业技术弄懂搜索引擎原理,咱们做搜索引擎排名的首先就是要了解搜索引擎的工作原理,对SEO优化有更深入了解之后再来做SEO,你就能从搜索引擎的视点...
- SEO指令分享:filetype指令
-
filetype用于搜索特定的文件格式。百度和谷歌都支持filetype指令。比如搜索filetype:pdf今日头条返回的就是包含今日头条这个关键词的所有pdf文件,如下图:百度只支持:pdf...
- 网站seo优化技巧大全
-
SEO在搜索引擎中对检索结果进行排序,看谁最初是在用户的第一眼中看到的。实际上,这些排名都是通过引擎的内部算法来实现的。例如,百度算法很有名。那么,对百度SEO的优化有哪些小技巧?下面小编就会说下针对...
- 小技巧#10 某些高级的搜索技巧
-
由于某些原因,我的实验场所仅限百度。1.关键词+空格严格说来这个不能算高级,但关键词之间打空格的办法确实好用。我习惯用右手大拇指外侧敲击空格键,这个习惯在打英文报告时尤其频繁。2.site:(请不要忽...
- MYSQL数据库权限与安全
-
权限与安全数据库的权限和数据库的安全是息息相关的,不当的权限设置可能会导致各种各样的安全隐患,操作系统的某些设置也会对MySQL的安全造成影响。1、权限系统的工作原理...
- WPF样式
-
UniformGrid容器<UniformGridColumns="3"Rows="3"><Button/>...
- MySQL学到什么程度?才有可以在简历上写精通
-
前言如今互联网行业用的最多就是MySQL,然而对于高级Web面试者,尤其对于寻找30k下工作的求职者,很多MySQL相关知识点基本都会涉及,如果面试中,你的相关知识答的模糊和不切要点,基...
- jquery的事件名称和命名空间的方法
-
我们先看一些代码:当然,我们也可以用bind进行事件绑定。我们看到上面的代码,我们可以在事件后面,以点号,加我们的名字,就是事件命名空间。所谓事件命名空间,就是事件类型后面以点语法附加一个别名,以便引...
- c#,委托与事件,发布订阅模型,观察者模式
-
什么是事件?事件(Event)基本上说是一个用户操作,如按键、点击、鼠标移动等等,或者是一些提示信息,如系统生成的通知。应用程序需要在事件发生时响应事件。通过委托使用事件事件在类中声明且生成,且通过...
- 前端分享-原生Popover已经支持
-
传统网页弹窗开发需要自己处理z-index层级冲突、编写点击外部关闭的逻辑、管理多个弹窗的堆叠顺序。核心优势对比:...
- Axure 8.0 综合帖——新增细节内容
-
一、钢笔工具与PS或者AI中的钢笔工具一样的用法。同样有手柄和锚点,如果终点和起点没有接合在一起,只要双击鼠标左键即可完成绘画。画出来的是矢量图,可以理解为新的元件。不建议通过这个工具来画ICON图等...
- PostgreSQL技术内幕28:触发器实现原理
-
0.简介在PostgreSQL(简称PG)数据库中,触发器(Trigger)能够在特定的数据库数据变化事件(如插入、更新、删除等)或数据库事件(DDL)发生时自动执行预定义的操作。触发器的实现原理涉及...
- UWP开发入门(十七)--判断设备类型及响应VirtualKey
-
蜀黍我做的工作跟IM软件有关,UWP同时会跑在电脑和手机上。电脑和手机的使用习惯不尽一致,通常我倾向于根据窗口尺寸来进行布局的变化,但是特定的操作习惯是依赖于设备类型,而不是屏幕尺寸的,比如聊天窗口的...