pytest -- 进阶使用详解

这篇具有很好参考价值的文章主要介绍了pytest -- 进阶使用详解。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

pytest-html⽣成报告

Pytest-HTML 是⼀个插件,它可以⽣成漂亮且易于阅读的 HTML 测试报告。

pytest-html ⽣成报告的步骤

① 安装 pytest-html 插件:

pip install pytest-html

② 运⾏测试并⽣成报告:

file name:main.py

import pytest

"""
等号的前后不能有空格,不然执行会报错
report/report.html:执行后,在当前文件目录下生成一个report文件夹,
里面包含report.html文件和一个assert文件夹
"""
pytest.main(["--html=report/report.html"])

# 不加report/,直接在当前文件目录下生成一个report.html文件
# pytest.main(["--html=report.html"])

执行测试代码:

# file name:test_001.py

def test_004():
    print("用例test_001被运行")


def test_005():
    print("用例test_002被运行")


def test_006():
    print("这是一条异常用例")
    a = 1
    b = 2
    assert a + b == 4  # assert即断言,触发异常

main文件执行:终端输入如下

pytest -- 进阶使用详解,python进阶,python

使⽤ --html 选项指定报告⽂件的名称和路径。在上述示例中,报告将⽣成为 report.html ⽂件。

pytest -- 进阶使用详解,python进阶,python

③ 查看⽣成的报告:

打开⽣成的 HTML 报告⽂件,你将看到测试结果的摘要、详细的测试⽤例执⾏ 信息、失败⽤例的堆栈跟踪等。报告通常包括以下内容:

●  概述信息:显示运⾏的测试数量、通过的测试数量、失败的测试数量等概览 信息。

●  测试⽤例列表:列出每个测试⽤例的名称、状态(通过、失败、跳过等)、执⾏ 时间等信息。

●  错误和失败详情:提供失败⽤例的详细信息、堆栈跟踪等,帮助你快速定位和解 决问题。

●  图表和图形化统计信息:可视化展示测试结果、⽤例通过率、执⾏时间等数据。

pytest -- 进阶使用详解,python进阶,python

pytest -- 进阶使用详解,python进阶,python

pytest -- 进阶使用详解,python进阶,python

④ ⾃定义报告的样式和配置

hmtl样式合并(没什么实际意义,做个了解)

上面的代码示例,执行后,在当前m8项目文件目录下生成了一个report文件夹 -> assets文件夹 -> style.css文件,这个文件是对html报告的样式做控制的,默认是样式与html文件是分离的

pytest -- 进阶使用详解,python进阶,python

style.css文件删除后,再打开html报告,就没有样式了,只显示数据:

pytest -- 进阶使用详解,python进阶,python

可以在main文件中,修改代码如下:

import pytest

pytest.main(["--html=report/report.html","--self-contained-html"])

pytest -- 进阶使用详解,python进阶,python

再次打开html文件,样式又恢复了:

pytest-html在报告中添加图⽚

fiel name:test_add_img.py 

from pytest_html import extras
import base64


def test_add_img(extra):

    # 将图片转化为base64数据
    def image_to_base64(image_path):
        with open(image_path,"rb") as image_file:
            encoded_string = base64.b64encode(image_file.read())
            return encoded_string.decode("utf-8")

    # 添加图片文件
    image_path = "D:\pycharm\HC\pytest_demo\m8_1\列图1.jpg"
    extra.append(extras.jpg(image_path))

    #添加base64格式的图片
    base64_data = image_to_base64(image_path)
    extra.append(extras.image(base64_data))
flie name:main.py

import pytest

pytest.main(["--html=report/report.html", "--self-contained-html"])

main文件执行后,生成的测试报告:

pytest -- 进阶使用详解,python进阶,python

Pytest获取⽤例结果流程

以下是两个模块的测试用例代码:

# file name:test_001.py

def test_001():
    print("用例test_001被运行")


def test_002():
    print("用例test_002被运行")


def test_003():
    print("用例test_003被运行")
# file name:test_002.py

def test_004():
    print("用例test_004被运行")


def test_005():
    print("用例test_005被运行")


def test_006():
    print("这是一条异常用例")
    a = 1
    b = 2
    assert a + b == 4  # assert即断言,触发异常

想要获取执行测试用例的结果流,需要在conftest中进行代码配置:

file name:conftest.py
import pytest

@pytest.hookimpl(hookwrapper=True)          #固定写法、写死的
def pytest_runtest_makereport(item,call):   #固定写法、写死的
    outcome = yield
    report = outcome.get_result()
    if report.when == "call":              #过滤 前置、后置,只保留运行中的状态
        print("用例执行结果:",report.outcome)

执行用例:

从目前来看conftest的配置作用不大,接着往下看,其它作用

pytest -- 进阶使用详解,python进阶,python

pytest-html的异常时添加图⽚实现

还是沿用上面“获取用例结果流程’”的两份用例代码

conftest.py代码:

file name:conftest.py

import base64
import pytest
from pytest_html import extras


@pytest.hookimpl(hookwrapper=True)          #固定写法、写死的
def pytest_runtest_makereport(item, call):   #固定写法、写死的
    # 将图片转化为base64数据
    def image_to_base64(image_path):
        with open(image_path,"rb") as image_file:
            encoded_string = base64.b64encode(image_file.read())
            return encoded_string.decode("utf-8")

    outcome = yield
    report = outcome.get_result()
    extra = getattr(report,"extra",[])
    if report.when == "call":  # 过滤 前置、后置,只保留运行中的状态
        print("用例执行结果:", report.outcome)
        if report.outcome != "passed":
            #失败截图数据
            image_path = "D:\pycharm\HC\pytest_demo\m8_1\列图1.jpg"
            base64_data = image_to_base64(image_path)
            extra.append(extras.image(base64_data))
    report.extra = extra

main.py代码: 

file name:main.py

import pytest

pytest.main(["--html=report/report.html","--self-contained-html"])

运行后,生成的测试报告:已经显示了截图

pytest -- 进阶使用详解,python进阶,python

allure-pytest⽣成测试报告

allure环境部署

① allure-pytest安装

 pip install allure-pytest

② 安装JDK

安装 Java Development Kit (JDK):Allure 需要 Java 运行环境来执行。
确保你的系统已安装适当版本的 JDK(下载安装自行百度)

③ 安装 Allure 命令行工具

allure ⽣成测试报告⾸先需要先下载allure命令⾏⼯具,下载地址为:

Central Repository: io/qameta/allure/allure-commandline (apache.org)

下载allure:下载任意版本都可以

pytest -- 进阶使用详解,python进阶,python

点进去会有很多,如果是windows系统,选择zip后缀的即可

pytest -- 进阶使用详解,python进阶,python

下载了之后需要解压出来,然后可以为它设置⼀个环境变量,这样便于使⽤,环境变量的值为它的bin⽂件夹的绝对路径。

效验是否安装成功,在cmd输入:

allure --version

pytest -- 进阶使用详解,python进阶,python

如上,cmd中能看到版本号,说明安装成功。

至此、环境问题就搞定了!~

allure-pytest生成测试报告步骤

第一步:运行测试用例

准备测试用例代码两份,还是沿用上面“获取用例结果流程’”的两份用例代码 

pytest -- 进阶使用详解,python进阶,python

main文件代码:

import pytest

#将结果记录下来,保存到allure_result这个文件中
pytest.main(["--alluredir","allure_result"])

第二步:获取测试用例的测试结果 

pytest -- 进阶使用详解,python进阶,python

第三步:基于测试结果生成测试报告

修改添加main文件的代码:

import pytest
import os

# 获得测试结果,并以allure的数据格式保留下来
pytest.main(["--alluredir","allure_result"])

# 通过allure的数据,进行报告的生成
os.system("allure generate --clean ./allure_result -o ./allure_report")

再次运行main文件,这两部可以合并执行,这里只是为了展示效果,原理是分为两步

就出现一个allure_report的文件夹,index.html是生成的测试报告

pytest -- 进阶使用详解,python进阶,python

第四步:查看测试报告

测试报告长这样, allure的样式还是比较酷炫的: 

pytest -- 进阶使用详解,python进阶,python

pytest -- 进阶使用详解,python进阶,python

pytest -- 进阶使用详解,python进阶,python

allure-pytest的乱码解决⽅案

pytest -- 进阶使用详解,python进阶,python

在使⽤allure-pytest的过程中,最容易出现的乱码情况是pycharm的终端出现乱码

截图如上面生成测试报告

解决步骤如下:

第一步:将pycharm配置到环境变量中,重启pycharm

pytest -- 进阶使用详解,python进阶,python

第二步:修改pycharm的编码

pytest -- 进阶使用详解,python进阶,python

如果还是出现乱码,按照上面提到的allure环境部署,检查一下有没有漏掉的环节

另外:路径命名的时候避免出现中文

allure-pytest的⾏为驱动标记

在Allure 报告中,feature 和 story 被称为⾏为驱动标记,⽤于描述测试⽤例所属的功能和故事。

● feature 标记⽤于标识测试⽤例所属的功能或模块。它表示被测试的系统中的 ⼀个主要功能。可以将 feature 视为⼀个⼤的分类或主题,⽤于组织和描述相 关的测试⽤例。

简单来说就是一个层级划分

--------->>>

● story 标记⽤于进⼀步细分 feature ,描述测试⽤例所属的具体故事或场景。 它表示在功能中的⼀个具体情境或使⽤案例。可以将 story 视为 feature 的 ⼦分类,⽤于更详细地描述测试⽤例。

--------->>>

这些⾏为驱动标记可以通过在测试⽤例的装饰器中添加相应的注解来指定。

在使⽤ pytest 运⾏测试⽤例时,可以在测试函数上使⽤装饰器来添加 feature 和 story 标记,如下所示:

allure-pytest的⾏为驱动标

在Allure 报告中,feature 和 story 被称为⾏为驱动标记,⽤于描述测试⽤例所属的功能和故事。

● feature 标记⽤于标识测试⽤例所属的功能或模块。它表示被测试的系统中的 ⼀个主要功能。可以将 feature 视为⼀个⼤的分类或主题,⽤于组织和描述相 关的测试⽤例。

--------->>>

● story 标记⽤于进⼀步细分 feature ,描述测试⽤例所属的具体故事或场景。 它表示在功能中的⼀个具体情境或使⽤案例。可以将 story 视为 feature 的 ⼦分类,⽤于更详细地描述测试⽤例。

--------->>>

这些⾏为驱动标记可以通过在测试⽤例的装饰器中添加相应的注解来指定。

在使⽤ pytest 运⾏测试⽤例时,可以在测试函数上使⽤装饰器来添加 feature 和 story 标记,如下所示:

测试用例代码:

flie name:test_01.py

import allure


@allure.feature("⽤户管理")  #主分类
@allure.story("创建用户")
def test_01():
    print("用例test_01被运行")


@allure.feature("⽤户管理")
@allure.story("创建用户1")
def test_02():
    print("用例test_02被运行")


def test_03():
    print("用例test_03被运行")
# file name:test_002.py
import allure

@allure.feature("用户管理22")
class Test:
    def test_004(self):
        print("用例test_004被运行")

    def test_005(self):
        print("用例test_005被运行")

    def test_006(self):
        print("这是一条异常用例")
        a = 1
        b = 2
        assert a + b == 4

main.py代码:

化重点,main函数里千万记得加"--clean-alluredir",不然多次运行代码,测试报告中会显示重复的用例

import pytest
import os

# 获得测试结果,并以allure的数据格式保留下来
pytest.main(["--alluredir","allure_results","--clean-alluredir"])

# 通过allure的数据,进行报告的生成
os.system(r"allure generate --clean ./allure_results -o ./allure_report")

运行后,查看测试报告:就可以看到层级的效果

pytest -- 进阶使用详解,python进阶,python

pytest -- 进阶使用详解,python进阶,python

allure-pytest的步骤管理

Allure-pytest 提供了步骤管理功能,可以帮助在测试⽤例中记录和展示测试步骤的执⾏情况。步骤管理可以提供更详细的测试过程描述,帮助定位问题和跟踪测试执⾏。

下⾯是使⽤ Allure-pytest 进⾏步骤管理的简单步骤:

1. 在测试⽤例中使⽤ @allure.step 装饰器定义步骤:

用例集代码如下:

每个函数对应一个步骤,即创建一个函数,声明步骤

# file name:test001.py
import allure


@allure.step("步骤1:登录系统")  #声明为步骤1
def step_login_system(username, password):
    # 登录系统的代码逻辑
    print("登录", username, password)


@allure.step("步骤2:搜索商品")  #声明为步骤2
def step_search_product(product_name):
    # 搜索商品的代码逻辑
    print("搜索商品", product_name)


@allure.step("步骤3:添加商品到购物车")  #声明为步骤3
def step_add_to_cart(product_id):
    # 添加商品到购物车的代码逻辑
    print("添加商品id:", product_id, "到购物车")


@allure.step("步骤4:结算购物车")   #声明为步骤4
def step_checkout_cart():
    # 结算购物车的代码逻辑
    print("结算购物车")


@allure.step("步骤5:确认订单")   #声明为步骤5
def step_confirm_order():
    # 确认订单的代码逻辑
    print("确认订单")

2. 在测试⽤例中按照顺序调⽤定义的步骤:

可以直接接着上面的代码后面写

"""
定义测试函数:依次调用了之前定义的测试步骤函数
模拟一个简单的购物流程:登录系统、搜索商品、添加商品到购物车、结算购物车、确认订单。
"""
def test_shopping_flow():  
    step_login_system("testuser", "password")
    step_search_product("iPhone")
    step_add_to_cart("12345")
    step_checkout_cart()
    step_confirm_order()
    assert True

或者也可以这样写:

def test_step_show():
    with allure.step("步骤1"):
        print("步骤1的逻辑代码")

    with allure.step("步骤2"):
        print("步骤2的逻辑代码")

        with allure.step("子步骤2.1"):
            print("子步骤2.1的逻辑代码")

        with allure.step("子步骤2.2"):
            print("子步骤2.2的逻辑代码")

    with allure.step("步骤3"):
        print("步骤3的逻辑代码")

    with allure.step("步骤4"):
        print("步骤4的逻辑代码")

执行main文件:

# file name:main.py
import pytest
import os

pytest.main(["--alluredir", "./allure_results", "--clean-alluredir"])
os.system(r"allure generate --clean ./allure_results -o ./allure_report")

总览的详情点开,会显示输出的步骤,以及参数等:

pytest -- 进阶使用详解,python进阶,python

在 Allure 报告中,每个步骤都将被记录和展示,并且可以查看每个步骤的执⾏状 态、⽇志和截图等信息。

这样的步骤管理可以帮助测试⼈员更好地理解测试过 程,快速定位和排查问题。

allure-pytest在报告中添加图⽚

添加图⽚可以提供更直观的信息展示,帮助测试⼈员和利益相关者更好地理解测试结果。 Allure-pytest 测试框架中使⽤ @allure.attach 装饰器将图⽚作为附件添加到报告中。

通过以下步骤实现在 Allure 报告中添加图⽚:

将图⽚准备好,可以是⽂件路径或者已经编码为 base64 的图⽚内容。

使⽤ allure.attach ⽅法将图⽚作为附件添加到报告中

指定附件的名称和类型,通常是 PNG 或 JPEG 格式

# file name:test001.py
import allure


def test():
    image_path = "png.png"
    with open(image_path, 'rb') as image_file:
        #设置图片的名字,-声明要添加的图片格式的类型为png
        allure.attach(image_file.read(), name='图片的名称', attachment_type=allure.attachment_type.PNG)

运行main文件,查看测试报告:

pytest -- 进阶使用详解,python进阶,python

通过 Allure-pytest 的 @allure.attach 装饰器添加图⽚的目的:

可以增强报告的可读性和 信息传达效果,使测试结果更加直观和清晰。

allure-pytest的异常时添加图⽚

和pytest-hmtl一样:

conftest.py文件中写异常的截图
# file name:conftest.py
import pytest
import allure


@pytest.hookimpl(hookwrapper=True)  # 写死的
def pytest_runtest_makereport(item, call):  # 写死的
    outcome = yield
    report = outcome.get_result()
    if report.when == "call":  # 过滤 前置,和后置,只保留运行中的状态
        if report.outcome != "passed":
            """失败截图数据"""
            image_path = "png.png"  # 这里你可以换成你的图片路径
            with open(image_path, 'rb') as image_file:
                allure.attach(image_file.read(), name='异常截图', attachment_type=allure.attachment_type.PNG)

用例中写正常的截图:

# file name:test001.py
import allure


def test():
    image_path = "png.png"
    with open(image_path, 'rb') as image_file:
        allure.attach(image_file.read(), name='正常的图片', attachment_type=allure.attachment_type.PNG)

    print("异常用例")
    assert 0

main文件代码:

import pytest
import os

pytest.main(["--alluredir", "./allure_results", "--clean-alluredir"])
os.system(r"allure generate --clean ./allure_results -o ./allure_report")

查看测试报告:会显示两个图片:

pytest -- 进阶使用详解,python进阶,python

Pytest的数据驱动⽅案

数据驱动是⼀种常⻅的测试⽅案,它允许我们使⽤不同的测试数据来执⾏相同的测试⽤例。这种⽅法可以帮助我们提⾼测试覆盖率,减少代码冗余,并更好地组织测试代 码。

pytest的数据驱动的⽅案,有且只有下面两个⽅法:

1.使⽤fixtures和数据⽂件

我们可以结合pytest的fixtures来实现数据驱动。

在这种⽅法中,我们可以使⽤fixture 读取和处理数据⽂件,并将数据作为参数传递给测试函数。

通过@pytest.fixture接受一个参数params

params里接收一个list的数据集合,里面是3个元组

将fixture名字命名为test_data,用data构建一个request,

request接收params的数据返回给测试用例:
# file name:conftest.py
import pytest


@pytest.fixture(params=[
    (1, 2, 3),
    (5, 5, 10),
    (10, -2, 8)
], name="test_data")
def data(request):
    return request.param

测试用例:

测试用例中的test_data接收conftest.py中的fixtures

# file name:test_001.py

def test(test_data):
    print(test_data)

main文件:

# file name:main.py

import pytest

pytest.main(["-vs"])

运行结果:

pytest -- 进阶使用详解,python进阶,python

2.使⽤@pytest.mark标签管理

pytest提供了⼀个装饰器 @pytest.mark.parametrize ,它可以⽤来将测试函数参数化。

通过这个装饰器,我们可以指定多个参数值的组合,pytest会⾃动为每个组合⽣成⼀个独⽴的测试⽤例。

parametrize是固定标签,可以接收参数,这里设置接收三个参数,以逗号分隔

三个参数分别接收三个元组数据,按照顺序,inptut1接收第一个元组,以此类推

函数的内容、或步骤不变,但是数据改变的情况下,就可以做成数据驱动

# file name:test_data_driver.py
import pytest


@pytest.mark.parametrize("input1, input2, expected", [
    (1, 2, 3),
    (5, 5, 10),
    (10, -2, 8)
])
def test_addition(input1, input2, expected):
    print("input1的数据", input1)
    print("input2的数据", input2)
    print("expected的数据", expected)
    assert input1 + input2 == expected

执行后输出:

pytest -- 进阶使用详解,python进阶,python文章来源地址https://www.toymoban.com/news/detail-808803.html

到了这里,关于pytest -- 进阶使用详解的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 分布式测试插件 pytest-xdist 使用详解

    目录 使用背景: 使用前提: 使用快速入门: 使用小结: 大型测试套件:当你的测试套件非常庞大,包含了大量的测试用例时,pytest-xdist可以通过并行执行来加速整体的测试过程。它利用多个进程或计算机的计算资源,可以显著减少测试执行的时间。 高计算资源需求:某些

    2024年02月13日
    浏览(29)
  • Python测试框架 Pytest —— mock使用(pytest-mock)

    安装:pip install pytest-mock 这里的mock和unittest的mock基本上都是一样的,唯一的区别在于pytest.mock需要导入mock对象的详细路径。 先将需要模拟的天气接口,以及需要模拟的场景的代码写好,然后在进行遵循pytest的用例规范进行书写关于mock的测试用例 通过上述代码,提供pytest中

    2024年02月09日
    浏览(33)
  • pytest框架快速进阶篇-pytest前置和pytest后置,skipif跳过用例

     一、 Pytest的前置和后置方法 1.Pytest可以集成unittest实现前置和后置 注意:setUpClass和tearDownClass需要用@classmethod装饰器装饰。 2.Pytest前置和后置 注意:setup、teardown、setup_class、teardown_class都是小写! 二、跳过用例 使用方法:   @pytest.mark.skipif(21,reason=\\\'当条件不True时跳过\\\') 使用

    2024年02月13日
    浏览(37)
  • pytest 参数化进阶

    目录 前言: 语法 参数化误区 实践 简要回顾 pytest是一个功能强大的Python测试框架,它提供了参数化功能,可以帮助简化测试用例的编写和管理。 本文就赶紧聊一聊 pytest 的参数化是怎么玩的。 @pytest.mark.parametrize 可以自定义变量,test_input 对应的值是\\\"3+5\\\" \\\"2+4\\\" \\\"6*9\\\",expected 对

    2024年02月16日
    浏览(23)
  • Python基础介绍 —— 使用pytest进行测试!

    Pytest 是 Python 的一种单元测试框架,与 Python 自带的 unittest 测试框架类似,但是比 unittest 框架使用起来更简洁,效率更高。 Pytest 是 Python 的一种单元测试框架,与 Python 自带的 unittest 测试框架类似,但是比 unittest 框架使用起来更简洁,效率更高。 适合从简单的单元到复杂的

    2024年02月05日
    浏览(36)
  • Python-pytest使用unittest

    介绍: unittest 是 Python 标准库中的测试框架,用于编写和运行单元测试。它提供了一组用于组织测试、断言和报告测试结果的类和方法。 编写测试类和方法 运行测试 命令行方式: 测试运行器方式: 断言 使用各种断言方法来验证测试条件: 测试装置 使用 setUp 和 tearDown 进行

    2024年01月17日
    浏览(36)
  • Python-pytest使用allure工具

    Allure 是一种用于生成、展示和分析测试报告的开源测试报告框架。它支持多种测试框架,包括 Java、C#, Python 等,可以与各种测试工具集成。Allure 的目标是提供美观、易于理解的测试报告,同时提供详细的测试结果和历史数据。 1. 安装与配置 安装Python依赖 2. 流程 要使 Allu

    2024年01月17日
    浏览(28)
  • Python 面试:单元测试unit testing & 使用pytest

    calc.py test_calc.py employee.py test_employee.py 输出为: setupClass setUp test_apply_raise tearDown .setUp test_email tearDown .setUp test_fullname tearDown .teardownClass Ran 3 tests in 0.001s OK employee.py test_employee.py 输出为: setupClass setUp test_apply_raise tearDown .setUp test_email tearDown .setUp test_fullname tearDown .setUp tearDown

    2024年02月10日
    浏览(35)
  • python+pytest接口自动化(12)-自动化用例编写思路 (使用pytest编写一个测试脚本)

    经过之前的学习铺垫,我们尝试着利用pytest框架编写一条接口自动化测试用例,来厘清接口自动化用例编写的思路。 我们在百度搜索 天气查询 ,会出现如下图所示结果: 接下来,我们以该天气查询接口为例,编写接口测试用例脚本。 针对某个功能做接口测试,首先我们需

    2024年02月04日
    浏览(45)
  • python+request+pytest+allure接口自动化使用说明书

    接口自动化使用与流程设计: 一、设计思路 1、一个好的框架,必须要可读性强,所以目录规划尤为重要; 2、公共的方法提取出来,提高复用性; 3、可变的环境等参数,提取出来放到配置文件中,这样,每次只需要更改配置文件中的值; 4、为了追踪错误,需要必要的日志

    2024年02月09日
    浏览(45)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包