Pytest入门系列之pytest的常见三方插件

Pytest入门系列之pytest的常见三方插件

pytest 提供了大量插件,可以增强测试能力,比如:

✅ 并行执行
✅ 生成测试报告
✅ 测试覆盖率统计
Mock 数据
✅ 数据库测试
✅ 自动失败重试
API 测试

pytest-xdist:并行执行,提高测试速度

📌 pytest-xdist 可以并行运行多个测试,提升执行效率。适用于:

✅大规模测试套件
API、UI自动化测试
CI/CD 提速

🔹 安装

1
pip install pytest-xdist

🔹 用法

1
2
3
pytest -n 4  # 4 个 CPU 核心并行执行
pytest -n auto # 自动检测 CPU 核心数

🔹 实战案例:加速 API 测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import requests
import time

API_ENDPOINTS = [
"https://jsonplaceholder.typicode.com/posts/1",
"https://jsonplaceholder.typicode.com/posts/2",
"https://jsonplaceholder.typicode.com/posts/3",
]

def fetch_api(url):
response = requests.get(url)
return response.json()

import pytest

@pytest.mark.parametrize("url", API_ENDPOINTS)
def test_api_performance(url):
start_time = time.time()
data = fetch_api(url)
duration = time.time() - start_time
assert "userId" in data
assert duration < 2 # API 响应必须在 2 秒内

📌 并行执行

1
pytest -n 3

📌 单线程:3s,4 线程并行:1s 🚀

pytest-html:生成可视化 HTML 测试报告

📌 pytest-html 生成详细的 HTML 报告,适用于:

✅CI/CD 持续集成
✅测试数据可视化
✅团队测试报告共享

🔹 安装

1
pip install pytest-html

🔹 生成 HTML 报告

1
pytest --html=report.html --self-contained-html

🔹 实战案例

1
2
3
4
5
6
def test_addition():
assert 1 + 1 == 2

def test_string():
assert "pytest" in "pytest is awesome"

📌 打开 report.html,查看可视化报告

pytest-cov:代码覆盖率分析

📌 pytest-cov 用于 统计测试覆盖率,找出未测试的代码。适用于:

✅单元测试
✅重构代码,找出未覆盖部分
✅CI/CD 质量检查

🔹 安装

1
pip install pytest-cov

🔹 运行测试 + 生成覆盖率报告

1
pytest --cov=my_project

🔹 代码示例

1
2
3
4
5
6
7
# my_project/calculator.py
def add(x, y):
return x + y

def multiply(x, y):
return x * y

1
2
3
4
5
6
# test_calculator.py
from my_project.calculator import add

def test_add():
assert add(2, 3) == 5

📌 运行 pytest --cov=my_project

1
2
----------- coverage: 50% -----------
calculator.py | 2 | 1 | 50%

📌 发现 multiply() 没有测试!

pytest-mock:模拟 HTTP 请求,数据库,函数

📌 pytest-mock 用于 Mock 依赖的函数/对象,避免真实请求,适用于:

✅模拟 API 返回数据
✅模拟数据库连接
Mock 类方法

🔹 安装

1
pip install pytest-mock

🔹 实战案例:Mock HTTP 请求

1
2
3
4
5
6
7
8
9
10
11
12
13
import requests

def fetch_data():
response = requests.get("https://api.example.com/data")
return response.json()

def test_mock_api(mocker):
mock_response = mocker.Mock()
mock_response.json.return_value = {"key": "mock_value"}
mocker.patch("requests.get", return_value=mock_response)

result = fetch_data()
assert result == {"key": "mock_value"}

📌 requests.get 不会真的请求 API,而是返回 Mock 数据

pytest-django:Django 项目专用

📌 pytest-django 优化 Django 测试,提供数据库回滚、ORM 测试支持。

🔹 安装

1
2
pip install pytest-django

🔹 配置

pytest.ini 里添加:

1
2
[pytest]
DJANGO_SETTINGS_MODULE = myproject.settings

🔹 实战案例:测试 Django ORM

1
2
3
4
5
6
7
8
import pytest
from myapp.models import User

@pytest.mark.django_db
def test_create_user():
user = User.objects.create(username="testuser")
assert user.username == "testuser"

📌 数据库测试自动回滚,不影响数据。

pytest-rerunfailures:失败自动重试

📌 pytest-rerunfailures 让失败的测试自动重试,适用于:

✅不稳定的 API / UI 测试
CI/CD 避免因偶然失败导致构建失败

🔹 安装

1
pip install pytest-rerunfailures

🔹 用法

1
2
pytest --reruns 3  # 失败时最多重试 3 次
pytest --reruns 3 --reruns-delay 2 # 每次重试间隔 2 秒

🔹 代码示例

1
2
3
4
import random

def test_unstable():
assert random.choice([True, False])

📌 如果失败,会自动重试 3 次

pytest-faker:生成随机数据

📌 pytest-faker 自动生成测试数据(如姓名、邮箱、地址),适用于:

✅用户注册测试
✅模拟表单提交
✅随机化数据

🔹 安装

1
pip install pytest-faker

🔹 代码示例

1
2
3
4
5
6
def test_faker(faker):
name = faker.name()
email = faker.email()
print(f"🧑 生成用户: {name}, 📧 邮箱: {email}")
assert "@" in email

📌 运行后,每次生成不同的名字和邮箱

pytest-timeout:防止死循环

📌 pytest-timeout 限制测试运行时间,避免死循环,适用于:

✅API / UI 超时检测
✅避免慢测试阻塞 CI/CD

🔹 安装

1
pip install pytest-timeout

🔹 代码示例

1
2
3
4
import time

def test_slow():
time.sleep(10) # 超时

📌 运行

1
pytest --timeout=5  # 超过 5 秒自动失败

总结

插件 适用场景 命令示例
pytest-xdist 并行执行测试 pytest -n 4
pytest-html 生成 HTML 报告 pytest --html=report.html
pytest-cov 测试覆盖率 pytest --cov=my_project
pytest-mock Mock 测试 mocker.patch()
pytest-django Django ORM 测试 @pytest.mark.django_db
pytest-rerunfailures 测试失败重试 pytest --reruns 3
pytest-faker 生成假数据 faker.email()
pytest-timeout 测试超时 pytest --timeout=5

以上只是常见的插件,pytest拥有非常丰富的插件,大家可以在评论区说一下你经常用那个呢?


Pytest入门系列之pytest的常见三方插件
https://dreamshao.github.io/2025/03/25/pytest入门系列8/
作者
Yun Shao
发布于
2025年3月25日
许可协议