在 pytest 接口自动化测试中,常用的测试库和工具汇总:
1. 核心测试框架
- pytest
- 基础测试框架,支持参数化、夹具(fixture)、断言重写等特性。
- 插件生态丰富,是接口自动化的核心工具。
2. HTTP 请求库
-
requests
- 发送 HTTP 请求(GET/POST/PUT/DELETE),处理响应数据。
- 简单易用,适合大多数接口测试场景。
import requests response = requests.get("https://api.example.com")
-
httpx
- 支持同步/异步 HTTP 请求,兼容 requests 的 API,适合需要异步的场景。
3. 断言与数据验证
-
pytest 内置断言
- 直接使用 Python 的
assert
语句,pytest 会提供详细的失败信息。
assert response.status_code == 200
- 直接使用 Python 的
-
jsonschema
- 验证 JSON 响应是否符合指定的 Schema 结构。
from jsonschema import validate schema = {"type": "object", "properties": {"name": {"type": "string"}}} validate(instance=response.json(), schema=schema)
-
pydantic
- 通过类型注解验证数据模型,适合强类型校验。
from pydantic import BaseModel class User(BaseModel): id: int name: str User(**response.json()) # 自动校验字段类型
4. 测试数据管理
-
Faker
- 生成假数据(如用户名、邮箱、地址等),用于测试输入。
from faker import Faker fake = Faker() fake.name() # 生成随机姓名
-
pytest-cases
- 分离测试逻辑和测试数据,支持动态参数化。
5. 环境与配置管理
-
python-dotenv
- 从
.env
文件加载环境变量(如测试环境的 URL、密钥等)。
from dotenv import load_dotenv load_dotenv()
- 从
-
pytest-base-url
- 通过命令行或配置文件管理测试的基础 URL。
6. 夹具(Fixtures)扩展
-
pytest-mock
- 集成
unittest.mock
,用于模拟接口依赖(如第三方服务)。
def test_api(mocker): mocker.patch("requests.get", return_value=Mock(status_code=200))
- 集成
-
responses
- 直接模拟
requests
库的返回,避免真实网络请求。
import responses @responses.activate def test_mock_api(): responses.add(responses.GET, "https://api.example.com", json={"key": "value"}) response = requests.get("https://api.example.com")
- 直接模拟
7. 报告与可视化
-
pytest-html
- 生成 HTML 格式的测试报告。
pytest --html=report.html
-
allure-pytest
- 生成 Allure 报告,支持丰富的图表和附件。
pytest --alluredir=./allure-results
8. 性能与安全
- locust
- 结合 pytest 实现接口性能测试(非 pytest 原生支持,但可集成)。
- bandit
- 检查代码中的安全漏洞(如硬编码密码)。
9. 其他实用插件
-
pytest-xdist
- 分布式运行测试,加速大规模用例执行。
pytest -n 4 # 使用 4 个进程并行
-
pytest-ordering
- 控制测试用例的执行顺序(谨慎使用,推荐用例独立)。
-
pytest-rerunfailures
- 自动重试失败的测试。
pytest --reruns 3 # 失败时重试 3 次
典型项目结构
project/
├── conftest.py # 全局夹具(如请求客户端、认证)
├── test_apis/
│ ├── __init__.py
│ ├── test_login.py # 测试模块
│ └── test_user.py
├── utils/
│ ├── data_loader.py # 数据读取工具
│ └── assert_helpers.py # 自定义断言
└── requirements.txt # 依赖库列表
总结
- 基础请求:
requests
+pytest
- 断言校验:
jsonschema
/pydantic
- 测试数据:
Faker
+ 参数化 - Mock:
responses
或pytest-mock
- 报告:
allure-pytest
或pytest-html
- 性能:
locust
(独立工具)
根据项目需求选择合适的库组合,保持代码简洁可维护!