Pytest教程:简单了解Pytest+Allure生成测试报告的使用

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

环境准备


  • 确保已安装Python环境
  • 安装Pytest:pip install pytest
  • 安装Allure-Pytest:pip install allure-pytest
  • 安装Java开发工具包(JDK)
  • 下载allure工具

步骤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 报告提供原材料。

pytest --alluredir=/tmp/my_allure_results test_example.py

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

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

allure serve /tmp/my_allure_results

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 报告:

 [pytest]
addopts = --alluredir=./allure-results

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

pytest --alluredir=./allure-results

4.最后,生成 Allure 报告:

allure serve ./allure-results

 

相关推荐

  1. (六)Python3 接口自动化测试pytest-html报告使用

    2024-03-15 10:04:02       28 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-15 10:04:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-15 10:04:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-15 10:04:02       82 阅读
  4. Python语言-面向对象

    2024-03-15 10:04:02       91 阅读

热门阅读

  1. PaddleOCR识别框架解读[14] OCR数据集

    2024-03-15 10:04:02       46 阅读
  2. Oracle数据库 shared pool

    2024-03-15 10:04:02       38 阅读
  3. Kotlin 中的数据类

    2024-03-15 10:04:02       37 阅读
  4. CSS中两栏布局的实现

    2024-03-15 10:04:02       46 阅读
  5. Union和union导致的数据不一致

    2024-03-15 10:04:02       41 阅读
  6. pxe安装mini centos系统

    2024-03-15 10:04:02       39 阅读
  7. 【备忘录】kafka常用命令维护

    2024-03-15 10:04:02       36 阅读
  8. postman学习

    2024-03-15 10:04:02       33 阅读