PyTest 教程:安装、编写与运行 Python 测试的完整指南
什么是 PyTest?
PyTest 是一款强大的开源测试框架,让开发者能为 Python 项目编写简洁、可扩展的测试用例——无论是单元测试、集成测试还是端到端 API 测试。支持并行执行、固件注入、参数化、开箱即用的丰富报告。
为什么选择 PyTest?
- 简洁易读的语法,减少样板代码
- 自动测试发现与执行
- 通过
-k和标记运行特定测试或分组 - 内置
pytest-xdist支持并行运行 - 通过固件、钩子、插件高度可扩展
- 免费且社区活跃维护
安装 PyTest
使用 pip 安装最新稳定版:
pip install pytest
验证安装:
pytest --version
如需指定版本,可固定版本号,如 pip install pytest==7.4.0。
入门:基础测试
创建项目目录,添加测试文件 test_sample1.py:
import pytest
def test_file1_method1():
x = 5
y = 6
assert x + 1 == y, "Addition failed"
assert x == y, "Values should match"
def test_file1_method2():
x = 5
y = 6
assert x + 1 == y, "Addition failed"
运行测试套件:
pytest
输出示例:
==================== test session starts ====================
collected 2 items
test_sample1.py F. [100%]
=================================== FAILURES ===================================
...
理解断言
PyTest 断言表现如标准 Python assert 语句。失败时测试停止,PyTest 报告确切位置和信息:
assert "hello" == "Hai", "Mismatched greeting"
测试发现规则
- 文件名必须以
test_开头或以_test.py结尾。 - 测试函数必须以
test_开头。 - 其他文件或函数除非显式指定否则被忽略。
运行特定测试
执行目录下所有测试:
pytest
运行单个文件:
pytest test_sample1.py
按子串过滤:
pytest -k method1 -v
按标记运行:
pytest -m set1
并行执行
安装 xdist 插件并启动 4 进程并行:
pip install pytest-xdist pytest -n 4
使用固件
定义一次可复用的设置逻辑并注入测试:
import pytest
@pytest.fixture
def supply_data():
return [25, 35, 45]
def test_compare_with_first(supply_data):
assert supply_data[0] == 25
将固件代码放入 conftest.py 可跨多测试模块共享。
参数化测试
单测试运行多组输入:
import pytest
@pytest.mark.parametrize("a, b, expected", [(5, 5, 10), (3, 5, 8)])
def test_add(a, b, expected):
assert a + b == expected
跳过与预期失败
使用标记跳过或标记预期失败,不污染结果:
import pytest
@pytest.mark.skip(reason="Feature not yet available")
def test_future_feature():
pass
@pytest.mark.xfail(reason="Known bug")
def test_known_issue():
assert 1 == 2
生成 XML 报告
生成兼容 JUnit 的 XML 文件供 CI 流水线使用:
pytest -v --junitxml=result.xml
实战示例:测试公开 API
下面最小框架演练 https://reqres.in/:
# conftest.py
import pytest
@pytest.fixture
def base_url():
return "https://reqres.in/api"
# test_list_user.py
import requests, json
import pytest
@pytest.mark.parametrize("user_id, first_name", [(1, "George"), (2, "Janet")])
def test_valid_user(base_url, user_id, first_name):
resp = requests.get(f"{base_url}/users/{user_id}")
data = json.loads(resp.text)
assert resp.status_code == 200
assert data["data"]["id"] == user_id
assert data["data"]["first_name"] == first_name
def test_invalid_user(base_url):
resp = requests.get(f"{base_url}/users/50")
assert resp.status_code == 404
# test_login_user.py
import requests, json
import pytest
def test_login_success(base_url):
payload = {"email": "test@test.com", "password": "something"}
resp = requests.post(f"{base_url}/login/", data=payload)
data = json.loads(resp.text)
assert resp.status_code == 200
assert data["token"] == "QpwL5tke4Pnpja7X"
def test_login_missing_password(base_url):
payload = {"email": "test@test.com"}
resp = requests.post(f"{base_url}/login/", data=payload)
data = json.loads(resp.text)
assert resp.status_code == 400
assert data["error"] == "Missing password"
结语
本教程涵盖 PyTest 安装、编写清晰测试、使用固件与标记、并行运行、生成 XML 报告、构建简单 API 测试套件。掌握这些基础,你能自信地扩展 Python 测试实践。
Python