关于 pytest
pytest 是面向 Python 开发者的测试技能指南,介绍如何编写和运行测试,并通过夹具、参数化和模拟管理测试流程。还涵盖配置、覆盖率报告及并行测试。
主要功能
- 01编写并运行 Python 测试
- 02使用夹具管理测试设置与清理
- 03参数化测试输入
- 04通过模拟隔离依赖
- 05配置 pytest 并生成覆盖率报告
- 06使用 pytest-xdist 并行运行测试
适用场景
- 01为 Python 项目编写单元测试
- 02复用测试所需的设置与依赖注入
- 03用多组输入验证函数行为
- 04在 CI 中运行测试并检查覆盖率
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ partme-ai/ full-stack-skills --skill pytest安装后在 Claude Code 中输入/pytest确认已加载。
附带文件LICENSE.txt
详细介绍
适用场景
当用户希望执行以下操作时,使用此技能:
- 使用 pytest 编写并运行 Python 单元测试
- 使用 fixture 进行测试设置、清理和依赖注入
- 参数化测试,以使用多组输入运行测试
- 使用
pytest-mock或unittest.mock模拟依赖项 - 通过
pytest.ini、pyproject.toml或conftest.py配置 pytest - 使用
pytest-cov生成覆盖率报告 - 使用
pytest-xdist并行运行测试
如何使用此技能
工作流
- 编写测试函数,名称以
test_开头,或编写Test类 - 在
conftest.py中使用 fixture 进行共享设置和依赖注入 - 使用
pytestCLI 运行测试,并根据需要应用标记和筛选条件 - 使用覆盖率和报告插件分析结果
1. 基本测试
def test_addition():
assert 1 + 1 == 2
def test_string_upper():
assert "hello".upper() == "HELLO"
2. Fixture
import pytest
@pytest.fixture
def sample_user():
return {"name": "Alice", "email": "[email protected]"}
def test_user_name(sample_user):
assert sample_user["name"] == "Alice"
@pytest.fixture(autouse=True)
def reset_database(db):
db.clear()
yield
db.clear()
3. 参数化
import pytest
@pytest.mark.parametrize("input,expected", [
("hello", 5),
("", 0),
("pytest", 6),
])
def test_string_length(input, expected):
assert len(input) == expected
4. 模拟
def test_api_call(mocker):
mock_get = mocker.patch("requests.get")
mock_get.return_value.json.return_value = {"status": "ok"}
result = fetch_status()
assert result == "ok"
mock_get.assert_called_once()
5. 运行测试
# Run all tests
pytest
# Verbose with pattern filter
pytest -v -k "test_user"
# With coverage
pytest --cov=mypackage --cov-report=html
# Parallel execution
pytest -n auto
最佳实践
- 保持测试相互独立,不共享可变状态;使用 fixture 进行设置和清理
- 使用清晰、具体的测试名称,说明预期行为
- 避免依赖测试执行顺序;使用
conftest.py定义共享 fixture - 在 CI 中运行完整测试套件;使用
--cov检查覆盖率,并使用--maxfail=1尽早失败 - 使用标记(
@pytest.mark.slow)对测试分类并运行部分测试
资源
- 官方文档:https://docs.pytest.org/
- pytest-cov:https://pytest-cov.readthedocs.io/
- pytest-xdist:https://github.com/pytest-dev/pytest-xdist
关键词
pytest、Python 测试、fixture、参数化、模拟、conftest、覆盖率、pytest-cov、pytest-xdist、单元测试、标记
评论
支持 Markdown