关于 python-testing-patterns
python-testing-patterns 为构建和维护 Python 测试套件的开发者提供参考指南,涵盖 pytest、夹具、模拟、异步、集成及基于属性的测试,并按主题提供详细资料。
主要功能
- 01pytest 测试结构与发现
- 02夹具设置、作用域与清理
- 03参数化测试与模拟
- 04异步及基于属性的测试
- 05集成测试与覆盖率指南
适用场景
- 01为 Python 项目搭建 pytest 套件
- 02测试 API、数据库和外部服务
- 03检查异步代码与边界情况
- 04衡量覆盖率并组织测试运行
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ nickcrew/ claude-cortex --skill python-testing-patterns安装后在 Claude Code 中输入/python-testing-patterns确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/async-testing.mdbest-practices.mdcoverage.mdfixtures.mdintegration-testing.mdmocking.mdmonkeypatch.mdparametrized-tests.mdproperty-based-testing.mdpytest-fundamentals.mdtest-organization.mdvalidation/rubric.yaml详细介绍
Python 测试模式
全面介绍如何使用 pytest、fixtures、模拟、参数化和基于属性的测试,在 Python 中实施稳健的测试策略。
何时使用此技能
- 为 Python 函数和类编写单元测试
- 搭建全面的测试套件和基础设施
- 实施测试驱动开发(TDD)工作流
- 为 API、数据库和服务创建集成测试
- 模拟外部依赖项和第三方服务
- 测试异步代码和并发操作
- 使用 Hypothesis 实施基于属性的测试
- 搭建 CI/CD 测试自动化
- 调试失败的测试并提升测试覆盖率
核心概念
测试发现:文件名匹配 test_*.py 或 *_test.py,函数名以 test_ 开头
Fixtures:带有设置和清理步骤的可复用测试资源
- 作用域:
function(默认)、class、module、session - 组合:通过简单 fixtures 构建复杂 fixtures
- 在
conftest.py中共享,以便整个项目使用
断言:使用 assert 语句,使用 pytest.raises() 检查异常
组织结构:分设 unit/、integration/、e2e/ 目录
快速参考
按需加载特定主题的详细参考资料:
| 任务 | 参考文件 |
|---|---|
| Pytest 基础、测试结构、AAA 模式 | skills/python-testing-patterns/references/pytest-fundamentals.md |
| Fixtures、作用域、设置/清理、conftest.py | skills/python-testing-patterns/references/fixtures.md |
| 参数化、多种测试用例 | skills/python-testing-patterns/references/parametrized-tests.md |
| 模拟、打补丁、unittest.mock、pytest-mock | skills/python-testing-patterns/references/mocking.md |
| 异步测试、pytest-asyncio、事件循环 | skills/python-testing-patterns/references/async-testing.md |
| 基于属性的测试、Hypothesis、策略 | skills/python-testing-patterns/references/property-based-testing.md |
| Monkeypatch、环境变量、属性 | skills/python-testing-patterns/references/monkeypatch.md |
| 测试结构、标记、conftest.py 模式 | skills/python-testing-patterns/references/test-organization.md |
| 覆盖率测量、报告、阈值 | skills/python-testing-patterns/references/coverage.md |
| 数据库、API、Redis、消息队列测试 | skills/python-testing-patterns/references/integration-testing.md |
| 最佳实践、测试质量、fixture 设计 | skills/python-testing-patterns/references/best-practices.md |
工作流
1. 基本测试设置
# test_example.py
import pytest
def test_something():
"""Descriptive test name."""
# Arrange
expected = 5
# Act
result = 2 + 3
# Assert
assert result == expected
运行测试:
pytest # Run all tests
pytest -v # Verbose output
pytest tests/unit/ # Specific directory
pytest -k "test_user" # Match pattern
pytest -m unit # Run marked tests
2. 使用 Fixtures
@pytest.fixture
def sample_data():
"""Provide test data."""
data = {"key": "value"}
yield data
# Cleanup if needed
def test_with_fixture(sample_data):
assert sample_data["key"] == "value"
3. 参数化测试
@pytest.mark.parametrize("input,expected", [
(2, 4),
(3, 9),
(4, 16),
])
def test_square(input, expected):
assert input ** 2 == expected
4. 模拟外部依赖项
from unittest.mock import patch
@patch("module.external_api_call")
def test_with_mock(mock_api):
mock_api.return_value = {"status": "ok"}
result = my_function()
assert result["status"] == "ok"
mock_api.assert_called_once()
5. 覆盖率测量
pytest --cov=src --cov-report=term-missing
pytest --cov=src --cov-report=html
pytest --cov=src --cov-fail-under=80
6. 测试配置
pytest.ini:
[pytest]
testpaths = tests
python_files = test_*.py
addopts = -v --strict-markers --cov=src
markers =
unit: Unit tests
integration: Integration tests
slow: Slow tests
常见模式
异常测试:
with pytest.raises(ValueError, match="error message"):
function_that_raises()
异步测试:
@pytest.mark.asyncio
async def test_async_function():
result = await async_operation()
assert result is not None
临时文件:
def test_file_operation(tmp_path):
test_file = tmp_path / "test.txt"
test_file.write_text("content")
assert test_file.read_text() == "content"
用于筛选测试的标记:
@pytest.mark.slow
@pytest.mark.integration
def test_database_operation():
pass
常见错误
-
不使用 fixtures:在多个测试中重复设置代码
- 解决方案:在 conftest.py 中创建 fixtures
-
测试依赖执行顺序:全局状态受到污染
- 解决方案:使用适当的 fixtures 确保测试彼此独立
-
过度模拟:模拟内部实现
- 解决方案:仅模拟外部边界(API、数据库)
-
遗漏边界情况:只测试正常路径
- 解决方案:测试边界条件、错误和无效输入
-
测试缓慢:频繁运行完整的集成测试
- 解决方案:分开单元测试和集成测试,使用标记,并优化 fixtures
-
忽视覆盖率缺口:不测量测试覆盖率
- 解决方案:使用 pytest-cov 并跟踪指标
-
测试名称不佳:使用
test_1()之类的通用名称- 解决方案:使用描述性名称:
test_<behavior>_<condition>_<expected>
- 解决方案:使用描述性名称:
-
没有清理:资源未释放
- 解决方案:使用带有适当清理步骤的 fixtures(yield 模式)
资源
- pytest: https://docs.pytest.org/
- unittest.mock: https://docs.python.org/3/library/unittest.mock.html
- pytest-asyncio: 测试异步代码
- pytest-cov: 覆盖率报告
- pytest-mock: pytest 的 mock 封装
- Hypothesis: https://hypothesis.readthedocs.io/
- pytest-xdist: 并行执行测试
- testcontainers: 用于测试的 Docker 容器
评论
支持 Markdown