0
点赞
收藏
分享

微信扫一扫

蓝桥杯刷题(八)

在软件测试领域,Pytest 是一个非常流行的 Python 测试框架,它简单、灵活且功能强大。Allure 是一个轻量级且富有表现力的测试报告工具,能够展示丰富的测试信息。将 PytestAllure 结合使用,可以生成详细且美观的测试报告,有助于提高软件质量和测试效率。

环境准备


步骤1:编写测试用例

首先,创建一个测试文件 test_example.py

import pytest

def add(a, b):
    return a + b

@pytest.mark.parametrize("a,b,expected", [(1, 2, 3), (4, 5, 9), (10, 20, 30)])
def test_add(a, b, expected):
    assert add(a, b) == expected

这个例子中,我们定义了一个简单的加法函数 add 和一个参数化的测试函数 test_add

步骤2:运行Pytest并生成Allure报告

运行测试并生成 Allure 报告需要两步:

1.运行 Pytest 生成数据文件:这些数据文件为 Allure 报告提供原材料。

 上述命令会将测试结果数据存放在 /tmp/my_allure_results 目录。

2.使用 Allure 生成 HTML 报告:需要先安装 Allure 命令行工具,安装方法请参考 Allure 官方文档。安装完成后,运行以下命令生成报告:

allure serve 命令会处理 /tmp/my_allure_results 目录下的数据文件,生成并在默认浏览器中打开一个临时的测试报告页面。

结合实际测试场景


在实际测试场景中,我们可能需要对 Web 应用、API 接口或者其他软件模块进行自动化测试。无论是哪种类型的测试,只要能够用 Python 编写测试脚本,就可以利用 Pytest 进行测试管理,并通过 Allure 生成漂亮的测试报告。

例如,假设我们正在对一个 RESTful API 进行测试,我们可以使用 requests 库发起 HTTP 请求,并用 Pytest 断言响应结果。然后,与上述类似,通过 Pytest + Allure 生成测试报告。

1.创建一个测试文件 test_api.py,编写测试代码:

import requests
import pytest
import allure

API_URL = "https://api.example.com"

@pytest.mark.parametrize("resource", ["/users", "/posts"])
def test_api_endpoint(resource):
    response = requests.get(API_URL + resource)
    
    assert response.status_code == 200
    assert response.json() is not None

    with allure.step("Verify response format"):
        allure.attach(f"Response: {response.text}", name="API Response")

2.创建一个 pytest.ini 配置文件,配置 Allure 报告:

3.运行 Pytest 测试并生成 Allure 报告:

4.最后,生成 Allure 报告:

 

举报

相关推荐

0 条评论