作者:糯米不开花ぴ

pytest进阶 -- 结合Html / Allure生成测试报告

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文件执行:终端输入如下

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

③ 查看⽣成的报告:

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

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

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

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

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

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

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

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

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

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

import pytest

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

再次打开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获取⽤例结果流程

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

# 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-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"])

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

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:下载任意版本都可以

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

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

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

allure --version

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

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

allure-pytest生成测试报告步骤

第一步:运行测试用例

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

main文件代码:

import pytest

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

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

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

修改添加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是生成的测试报告

第四步:查看测试报告

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

allure-pytest的乱码解决⽅案

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

截图如上面生成测试报告

解决步骤如下:

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

第二步:修改pycharm的编码

如果还是出现乱码,按照上面提到的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")

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

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")

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

在 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文件,查看测试报告:

通过 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的数据驱动⽅案

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

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"])

运行结果:

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

执行后输出: