pytest + requests + allure 接口自动化测试框架指南

pytest + requests + allure 接口自动化测试框架指南

这是一个基于 Python 的经典接口测试组合:pytest 作为测试执行框架,requests 负责发送 HTTP 请求,allure 生成美观的测试报告。下面从零开始介绍如何搭建和使用该框架。


1. 框架核心组件

组件 作用
pytest 测试发现、执行、断言、插件扩展(如参数化、fixture)
requests 发送 HTTP/HTTPS 请求,处理响应、Cookie、Session 等
allure 生成结构化测试报告,支持步骤、附件、标签、严重等级等丰富展示

2. 环境准备

2.1 安装依赖
bash 复制代码
pip install pytest requests allure-pytest
  • allure-pytest 是 pytest 与 allure 的适配插件。
2.2 安装 Allure 命令行工具
  • macOS : brew install allure
  • Windows : 下载 zip 包并添加 bin 目录到 PATH
  • Linux: 使用 apt 或下载解压

验证:allure --version


3. 项目结构建议

复制代码
project/
├── api/                    # 封装请求层
│   ├── __init__.py
│   └── client.py           # 公共请求方法
├── test_cases/             # 测试用例目录
│   ├── __init__.py
│   ├── test_user.py        # 用户模块测试
│   └── test_order.py
├── conftest.py             # pytest 全局配置(fixture、钩子)
├── pytest.ini              # pytest 配置文件
├── requirements.txt
└── reports/                # 存放 allure 原始数据及报告
    ├── raw/                # allure 结果目录
    └── html/               # 生成的报告

4. 基础示例

4.1 简单测试用例
python 复制代码
# test_cases/test_user.py
import requests
import allure

@allure.feature("用户模块")
class TestUser:

    @allure.story("获取用户信息")
    @allure.title("通过用户ID查询用户信息")
    def test_get_user_by_id(self):
        url = "https://jsonplaceholder.typicode.com/users/1"
        response = requests.get(url)
        assert response.status_code == 200
        assert response.json()["id"] == 1
4.2 使用 pytest 运行并生成 allure 数据
bash 复制代码
pytest test_cases/ --alluredir=./reports/raw
  • --alluredir 指定原始数据存放目录。
4.3 生成 allure 报告
bash 复制代码
allure generate ./reports/raw -o ./reports/html --clean
allure open ./reports/html

5. 进阶用法

5.1 封装 requests 客户端(使用 fixture)

conftest.py 中定义全局 session 对象,避免重复创建连接。

python 复制代码
# conftest.py
import pytest
import requests

@pytest.fixture(scope="session")
def api_client():
    """全局 requests session,可添加公共 headers 等"""
    session = requests.Session()
    session.headers.update({"Content-Type": "application/json"})
    # 可设置 base_url
    session.base_url = "https://jsonplaceholder.typicode.com"
    yield session
    session.close()

测试用例中使用:

python 复制代码
def test_get_user(api_client):
    response = api_client.get(f"{api_client.base_url}/users/1")
    assert response.status_code == 200
5.2 数据驱动(参数化)
python 复制代码
import pytest

@allure.feature("用户模块")
class TestUser:

    @allure.story("获取用户信息")
    @pytest.mark.parametrize("user_id, expected_name", [
        (1, "Leanne Graham"),
        (2, "Ervin Howell"),
    ])
    def test_get_user_name(self, api_client, user_id, expected_name):
        response = api_client.get(f"{api_client.base_url}/users/{user_id}")
        assert response.json()["name"] == expected_name
5.3 添加 allure 增强功能
  • 步骤(steps):将请求过程拆分为多个步骤
  • 附件(attachments):记录请求/响应详细信息
  • 严重等级(severity):标记测试重要性
python 复制代码
import allure
from allure_commons.types import AttachmentType

@allure.feature("用户模块")
class TestUser:

    @allure.story("登录")
    @allure.severity(allure.severity_level.CRITICAL)
    def test_login(self, api_client):
        with allure.step("构造登录请求"):
            payload = {"username": "admin", "password": "123456"}
            allure.attach(str(payload), "请求体", AttachmentType.JSON)

        with allure.step("发送请求"):
            response = api_client.post("/login", json=payload)
            allure.attach(response.text, "响应体", AttachmentType.TEXT)

        with allure.step("验证响应"):
            assert response.status_code == 200
            assert response.json()["token"] is not None
5.4 请求与响应日志自动附加

可以使用 pytest 钩子或装饰器自动将请求和响应附加到 allure 报告。例如在 conftest.py 中:

python 复制代码
import allure
from allure_commons.types import AttachmentType
import requests

def pytest_runtest_makereport(item, call):
    """自动为每个测试附加 requests 请求/响应信息(需要提前在 fixture 中存储)"""
    # 这是一种思路,实际需要将 requests 对象注入到测试上下文中
    pass

更简单的方式:在自定义的 api_client 中包装请求方法,每次请求后自动附加日志。


6. 其他最佳实践

  • 分离数据与逻辑 :将 URL、期望结果等存放在 YAML/JSON 文件中,使用 pytest 参数化读取。
  • 环境切换 :通过 pytest --env=test 等命令行参数动态切换 base_url。
  • 日志记录 :结合 logging 模块记录请求和响应,便于排查。
  • 断言增强 :使用 pytest-assumejsonschema 对响应结构进行校验。
  • 重试机制 :使用 pytest-rerunfailures 插件实现失败重试。
  • 并发执行pytest-xdist 加速测试。

7. 完整运行流程

  1. 编写测试用例,按模块组织。

  2. 执行测试 并生成 Allure 原始数据:

    bash 复制代码
    pytest test_cases/ --alluredir=./reports/raw -v
  3. 生成 HTML 报告

    bash 复制代码
    allure generate ./reports/raw -o ./reports/html --clean
  4. 打开报告

    bash 复制代码
    allure open ./reports/html

8. 总结

pytest + requests + allure 是目前非常成熟的接口测试解决方案,具有以下优点:

  • 简洁易用:pytest 低门槛,requests 语法直观。
  • 报告美观:allure 提供层次化展示,适合团队分享。
  • 扩展性强:可轻松集成 CI/CD(Jenkins、GitLab CI 等),通过插件支持数据驱动、并发、重试等。

通过合理设计目录结构、封装请求层、利用 fixture 管理资源,可以构建出稳定、可维护的接口自动化测试体系。

相关推荐
忘忧记4 小时前
pytest进阶参数化用法
前端·python·pytest
bug_rabbit5 小时前
pytest-html 中文乱码问题终极解决方案(Windows版)
windows·html·pytest
庄小法5 小时前
pytest
开发语言·python·pytest
工具人55551 天前
pytest练习
pytest
好家伙VCC1 天前
# Pytest发散创新:从基础测试到智能断言的实战进阶指南在现代软
java·python·pytest
小罗和阿泽2 天前
GUI 自动化测试 pywinauto测试框架
开发语言·python·功能测试·测试工具·pytest
文人sec2 天前
抛弃 Postman!用 Pytest+Requests+Allure+Playwright+Minium 搭建高逼格接口+UI自动化测试平台
自动化测试·python·测试工具·ui·pytest·playwright
曲幽3 天前
FastAPI单元测试实战:别等上线被喷才后悔,TestClient用对了真香!
python·单元测试·pytest·api·fastapi·web·httpx·testclient·依赖项覆盖
小罗和阿泽3 天前
接口测试系列 接口自动化测试 pytest框架(四)
pytest