Pytest自动化测试 - 必知必会的一些插件

2023-09-20 17:23:09

【软件测试行业现状】2023年了你还敢学软件测试?未来已寄..测试人该何去何从?【自动化测试、测试开发、性能测试】

Pytest拥有丰富的插件架构,超过800个以上的外部插件和活跃的社区,在PyPI项目中以“ pytest- *”为标识。

本篇将列举github标星超过两百的一些插件进行实战演示。

插件库地址:http://plugincompat.herokuapp.com/
1、pytest-html:用于生成HTML报告
一次完整的测试,测试报告是必不可少的,但是pytest自身的测试结果过于简单,而pytest-html正好可以给你提供一份清晰报告。

安装:
pip install -U pytest-html
用例:

 
# test_sample.py
import pytest
# import time
 
# 被测功能
def add(x, y):
    # time.sleep(1)
    return x + y
 
# 测试类
class TestLearning:
    data = [
        [3, 4, 7],
        [-3, 4, 1],
        [3, -4, -1],
        [-3, -4, 7],
    ]
    @pytest.mark.parametrize("data", data)
    def test_add(self, data):
        assert add(data[0], data[1]) == data[2]
运行:
E:\workspace-py\Pytest>pytest test_sample.py --html=report/index.html
========================================================================== test session starts ==========================================================================
platform win32 -- Python 3.7.3, pytest-6.0.2, py-1.9.0, pluggy-0.13.0
rootdir: E:\workspace-py\Pytest
plugins: allure-pytest-2.8.18, cov-2.10.1, html-3.0.0, rerunfailures-9.1.1, xdist-2.1.0
collected 4 items                                                                                                                                                        
 
test_sample.py ...F                                                                                                                                                [100%]
 
=============================================================================== FAILURES ================================================================================
_____________________________________________________________________ TestLearning.test_add[data3] ______________________________________________________________________
 
self = <test_sample.TestLearning object at 0x00000000036B6AC8>, data = [-3, -4, 7]
 
    @pytest.mark.parametrize("data", data)
    def test_add(self, data):
>       assert add(data[0], data[1]) == data[2]
E       assert -7 == 7
E        +  where -7 = add(-3, -4)
 
test_sample.py:20: AssertionError
------------------------------------------------- generated html file: file://E:\workspace-py\Pytest\report\index.html --------------------------------------------------
======================================================================== short test summary info ========================================================================
FAILED test_sample.py::TestLearning::test_add[data3] - assert -7 == 7
====================================================================== 1 failed, 3 passed in 0.14s ======================================================================

运行完,会生产一个html文件 和 css样式文件夹assets,用浏览器打开html即可查看清晰的测试结果。

后面我将会更新更加清晰美观的测试报告插件: allure-python
2、pytest-cov:用于生成覆盖率报告
在做单元测试时,代码覆盖率常常被拿来作为衡量测试好坏的指标,甚至,用代码覆盖率来考核测试任务完成情况。

安装:
pip install -U pytest-cov
 运行:

 
E:\workspace-py\Pytest>pytest --cov=.
========================================================================== test session starts ==========================================================================
platform win32 -- Python 3.7.3, pytest-6.0.2, py-1.9.0, pluggy-0.13.0
rootdir: E:\workspace-py\Pytest
plugins: allure-pytest-2.8.18, cov-2.10.1, html-3.0.0, rerunfailures-9.1.1, xdist-2.1.0
collected 4 items                                                                                                                                                        
 
test_sample.py ....                                                                                                                                                [100%]
 
----------- coverage: platform win32, python 3.7.3-final-0 -----------
Name             Stmts   Miss  Cover
------------------------------------
conftest.py          5      3    40%
test_sample.py       7      0   100%
------------------------------------
TOTAL               12      3    75%
 
 
=========================================================================== 4 passed in 0.06s ===========================================================================

3、pytest-xdist:实现多线程、多平台执行
通过将测试发送到多个CPU来加速运行,可以使用-n NUMCPUS指定具体CPU数量,或者使用-n auto自动识别CPU数量并全部使用。

安装:
pip install -U pytest-xdist
用例:
# test_sample.py
import pytest
import time

# 被测功能
def add(x, y):
    time.sleep(3)
    return x + y

# 测试类
class TestAdd:
    def test_first(self):
        assert add(3, 4) == 7

    def test_second(self):
        assert add(-3, 4) == 1

    def test_three(self):
        assert add(3, -4) == -1

    def test_four(self):
        assert add(-3, -4) == 7

 运行:

E:\workspace-py\Pytest>pytest test_sample.py
========================================================================== test session starts ==========================================================================
platform win32 -- Python 3.7.3, pytest-6.0.2, py-1.9.0, pluggy-0.13.0
rootdir: E:\workspace-py\Pytest
plugins: allure-pytest-2.8.18, cov-2.10.1, html-3.0.0, rerunfailures-9.1.1, xdist-2.1.0
collected 4 items                                                                                                                                                        

test_sample.py ....                                                                                                                                                [100%]

========================================================================== 4 passed in 12.05s ===========================================================================

E:\workspace-py\Pytest>pytest test_sample.py -n auto
========================================================================== test session starts ==========================================================================
platform win32 -- Python 3.7.3, pytest-6.0.2, py-1.9.0, pluggy-0.13.0
rootdir: E:\workspace-py\Pytest
plugins: allure-pytest-2.8.18, assume-2.3.3, cov-2.10.1, forked-1.3.0, html-3.0.0, rerunfailures-9.1.1, xdist-2.1.0
gw0 [4] / gw1 [4] / gw2 [4] / gw3 [4]
....                                                                                                                                                               [100%]
=========================================================================== 4 passed in 5.35s ===========================================================================

E:\workspace-py\Pytest>pytest test_sample.py -n 2
========================================================================== test session starts ==========================================================================
platform win32 -- Python 3.7.3, pytest-6.0.2, py-1.9.0, pluggy-0.13.0
rootdir: E:\workspace-py\Pytest
plugins: allure-pytest-2.8.18, assume-2.3.3, cov-2.10.1, forked-1.3.0, html-3.0.0, rerunfailures-9.1.1, xdist-2.1.0
gw0 [4] / gw1 [4]
....                                                                                                                                                               [100%]
=========================================================================== 4 passed in 7.65s ===========================================================================

上述分别进行了未开多并发、开启4个cpu、开启2个cpu,从运行耗时结果来看,很明显多并发可以大大缩减你的测试用例运行耗时。

4、pytest-rerunfailures:实现重新运行失败用例
 我们在测试时可能会出现一些间接性故障,比如接口测试遇到网络波动,web测试遇到个别插件刷新不及时等,这时重新运行则可以帮忙我们消除这些故障。

 安装:
pip install -U pytest-rerunfailures
运行:

E:\workspace-py\Pytest>pytest test_sample.py --reruns 3
========================================================================== test session starts ==========================================================================
platform win32 -- Python 3.7.3, pytest-6.0.2, py-1.9.0, pluggy-0.13.0
rootdir: E:\workspace-py\Pytest
plugins: allure-pytest-2.8.18, cov-2.10.1, html-3.0.0, rerunfailures-9.1.1, xdist-2.1.0
collected 4 items                                                                                                                                                        

test_sample.py ...R                                                                                                                                                [100%]R
 [100%]R [100%]F [100%]

=============================================================================== FAILURES ================================================================================
___________________________________________________________________________ TestAdd.test_four ___________________________________________________________________________

self = <test_sample.TestAdd object at 0x00000000045FBF98>

    def test_four(self):
>       assert add(-3, -4) == 7
E       assert -7 == 7
E        +  where -7 = add(-3, -4)

test_sample.py:22: AssertionError
======================================================================== short test summary info ========================================================================
FAILED test_sample.py::TestAdd::test_four - assert -7 == 7
================================================================= 1 failed, 3 passed, 3 rerun in 0.20s ==================================================================

如果你想设定重试间隔,可以使用 --rerun-delay 参数指定延迟时长(单位秒); 

如果你想重新运行指定错误,可以使用 --only-rerun 参数指定正则表达式匹配,并且可以使用多次来匹配多个。

pytest --reruns 5 --reruns-delay 1 --only-rerun AssertionError --only-rerun ValueError
如果你只想标记单个测试失败时自动重新运行,可以添加 pytest.mark.flaky() 并指定重试次数以及延迟间隔。

@pytest.mark.flaky(reruns=5, reruns_delay=2)
def test_example():
    import random
    assert random.choice([True, False])
5、pytest-randomly:实现随机排序测试
测试中的随机性非常越大越容易发现测试本身中隐藏的缺陷,并为你的系统提供更多的覆盖范围。

安装:
pip install -U pytest-randomly
运行:

E:\workspace-py\Pytest>pytest test_sample.py
========================================================================== test session starts ==========================================================================
platform win32 -- Python 3.7.3, pytest-6.0.2, py-1.9.0, pluggy-0.13.0
Using --randomly-seed=3687888105
rootdir: E:\workspace-py\Pytest
plugins: allure-pytest-2.8.18, cov-2.10.1, html-3.0.0, randomly-3.5.0, rerunfailures-9.1.1, xdist-2.1.0
collected 4 items                                                                                                                                                        

test_sample.py F...                                                                                                                                                [100%]

=============================================================================== FAILURES ================================================================================
___________________________________________________________________________ TestAdd.test_four ___________________________________________________________________________

self = <test_sample.TestAdd object at 0x000000000567AD68>

    def test_four(self):
>       assert add(-3, -4) == 7
E       assert -7 == 7
E        +  where -7 = add(-3, -4)

test_sample.py:22: AssertionError
======================================================================== short test summary info ========================================================================
FAILED test_sample.py::TestAdd::test_four - assert -7 == 7
====================================================================== 1 failed, 3 passed in 0.13s ======================================================================

E:\workspace-py\Pytest>pytest test_sample.py
========================================================================== test session starts ==========================================================================
platform win32 -- Python 3.7.3, pytest-6.0.2, py-1.9.0, pluggy-0.13.0
Using --randomly-seed=3064422675
rootdir: E:\workspace-py\Pytest
plugins: allure-pytest-2.8.18, assume-2.3.3, cov-2.10.1, forked-1.3.0, html-3.0.0, randomly-3.5.0, rerunfailures-9.1.1, xdist-2.1.0
collected 4 items                                                                                                                                                        

test_sample.py ...F                                                                                                                                                [100%]

=============================================================================== FAILURES ================================================================================
___________________________________________________________________________ TestAdd.test_four ___________________________________________________________________________

self = <test_sample.TestAdd object at 0x00000000145EA940>

    def test_four(self):
>       assert add(-3, -4) == 7
E       assert -7 == 7
E        +  where -7 = add(-3, -4)

test_sample.py:22: AssertionError
======================================================================== short test summary info ========================================================================
FAILED test_sample.py::TestAdd::test_four - assert -7 == 7
====================================================================== 1 failed, 3 passed in 0.12s ======================================================================

这功能默认情况下处于启用状态,但可以通过标志禁用(假如你并不需要这个模块,建议就不要安装)。

pytest -p no:randomly
如果你想指定随机顺序,可以通过 --randomly-send 参数来指定,也可以使用 last 值来指定沿用上次的运行顺序。

pytest --randomly-seed=4321
pytest --randomly-seed=last
6、其他活跃的插件
还有一些其他功能性比较活跃的、一些专门为个别框架所定制的、以及为了兼容其他测试框架,这里暂不做演示,我就简单的做个列举:

pytest-django:用于测试Django应用程序(Python Web框架)。
pytest-flask:用于测试Flask应用程序(Python Web框架)。
pytest-splinter:兼容Splinter Web自动化测试工具。
pytest-selenium:兼容Selenium Web自动化测试工具。
pytest-testinfra:测试由Salt,Ansible,Puppet, Chef等管理工具配置的服务器的实际状态。
pytest-mock:提供一个mock固件,创建虚拟的对象来实现测试中个别依赖点。
pytest-factoryboy:结合factoryboy工具用于生成各式各样的数据。
pytest-qt:提供为PyQt5和PySide2应用程序编写测试。
pytest-asyncio:用于使用pytest测试异步代码。
pytest-bdd:实现了Gherkin语言的子集,以实现自动化项目需求测试并促进行为驱动的开发。
pytest-watch:为pytest提供一套快捷CLI工具。
pytest-testmon:可以自动选择并重新执行仅受最近更改影响的测试。
pytest-assume:用于每个测试允许多次失败。
pytest-ordering:用于测试用例的排序功能。
pytest-sugar:可立即显示失败和错误并显示进度条。
pytest-dev/pytest-repeat:可以重复(可指定次数)执行单个或多个测试。

 最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:

文档获取方式:

这份文档,对于想从事【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴我走过了最艰难的路程,希望也能帮助到你!

以上均可以分享,只需要你搜索vx公众号:程序员雨果,即可免费领取

更多推荐

机器学习实战(01)-人工智能概要

1发展历程20世纪50年代:人工智能概念诞生1956年,“人工智能”这个术语由麦卡锡在达特茅斯会议上首次提出主要研究逻辑和推理,以及如何在机器上模拟人类智能20世纪60年代:知识表达期开始研究知识表达,使用谓词逻辑来表达知识开发可以解题的专家系统,例如Dendral专家系统20世纪70年代:知识库期研究汇集知识到知识库

vector类(顺序表)

文章目录1.定义:接口成员函数构造成员函数析构函数赋值2.迭代器2.1begin()和end()重点2.1.1应用2.1.1.1函数调用2.1.1.2用变量接受迭代器2.2rbegin()和rend()2.2.1应用3.顺序表的访问(增删查检)3.1operator[]和at3.2front()3.3back()4.v

突破视觉边界:深入探索AI图像识别的现状与挑战

图像识别作为人工智能领域的一个重要研究方向,取得了许多令人瞩目的成就。深入探索当前AI图像识别技术的现状以及所面临的挑战,讨论各种方法的优势和局限性。目录引言1.1AI图像识别的背景和概述1.2人工智能在图像识别中的应用和重要性图像识别基础知识2.1数字图像和像素2.2特征提取和表示2.3图像分类和目标检测传统图像识别

安装Ubuntu系统并搭建C语言环境(超详细教程)

一、新建虚拟机1、打开VMwareWorkstation,点击"创建新的虚拟机"。(或者选择左上角的"文件->新建虚拟机")2、进入向导窗口,选择"自定义"选项,进入下一步。3、选择硬件兼容性,这里选择默认的"Workstation16.x"就行,进入下一步。4、选择"稍后安装操作系统",进入下一步。5、客户机的操作系

Opencv-python去图标与水印方案实践

RGB色彩模式是工业界的一种颜色标准,是通过对红(R)、绿(G)、蓝(B)三个颜色通道的变化以及它们相互之间的叠加来得到各式各样的颜色的,RGB即是代表红、绿、蓝三个通道的颜色,这个标准几乎包括了人类视力所能感知的所有颜色,是运用最广的颜色系统之一。RGB模式的彩色图像在读入OpenCV内进行处理时,会按照行方向依次读

[Docker精进篇] Docker部署和实践 (二)

前言:Docker部署是通过使用Docker容器技术,将应用程序及其所有相关依赖项打包为一个可移植、自包含的镜像,然后在任何支持Docker的环境中快速部署和运行应用程序的过程。文章目录Docker部署1️⃣为什么需要?2️⃣有什么作用?3️⃣docker部署(以mysql和redis为例)部署mysql和映射部署re

【Docker】企业中 Docker 的 Dockerfile 用法及作用详解

企业中Docker的Dockerfile用法及作用详解本文将详细介绍企业中Docker的Dockerfile用法及其在企业中的作用。通过使用Java代码示例,我们将阐述Dockerfile的基本语法、常用指令以及构建和部署容器镜像的流程。Docker的Dockerfile功能可帮助企业实现可重复和可自动化的容器环境构建

《算法图解》阅读笔记

前言问题解决技巧:分而治之/动态规划;贪婪算法书目:Grokkingalgorithms:anillustratedguideforprogrammersandothercuriouspeople中文名称:《算法图解——像小说一样有趣的算法入门书》1算法简介二分查找:输入是一个有序的元素列表运行时间:线性时间;对数时间

腾讯云 Cloud Studio 实战训练:快速构建React完成H5页面还原

0️⃣前言腾讯云CloudStudio是一款在线开发工具(云IDE),它能帮助用户减少安装IDE的成本,提供一站式的在线代码开发、编译、运行和存储服务。1️⃣介绍1.项目介绍我们经常会遇到远程办公的场景,下面我们打算用云IDECloudStudio快速搭建,并开发还原一个移动端ReactH5的简版点餐系统页面,从0到1

【腾讯云Cloud Studio实战训练营】构建基于React的实时聊天应用

关于腾讯云CloudStudio构建基于CloudStudio的聊天应用(项目实战)1.注册并登录CloudStudio2.配置Git环境2.1复制SSH公钥2.2添加SSH公钥至GIt平台3.创建项目4.项目开发4.1安装依赖4.2集成tailwindcss4.3编写代码4.4项目运行示例项目完整代码及CloudSt

将 Pandas 换为交互式表格的 Python 库

Pandas是我们日常处理表格数据最常用的包,但是对于数据分析来说,Pandas的DataFrame还不够直观,所以今天我们将介绍4个Python包,可以将Pandas的DataFrame转换交互式表格,让我们可以直接在上面进行数据分析的操作。PivottablejsPivottablejs是一个通过IPythonwi

热文推荐