用途
tdd-pytest 是一个 Python/pytest 的 TDD(测试驱动开发)专项技能。当用户需要编写测试、审计已有 pytest 测试文件的质量、运行 pytest、生成测试报告,或在 pyproject.toml 中配置 pytest 时,可激活该技能。
主要能力
- 按 TDD 方法论(Red-Green-Refactor)编写测试。
- 审计现有 pytest 测试文件的质量。
- 带覆盖率运行测试。
- 生成测试报告到 TESTING_REPORT.local.md。
- 在 pyproject.toml 中设置 pytest 配置。
TDD 工作流
Red-Green-Refactor 循环:
- RED:先写一个失败的测试。测试应因正确的原因失败(而非导入错误);测试应最小且聚焦;展示失败测试输出。
- GREEN:编写最小代码使其通过。只实现通过测试所需的内容;不做过早优化;展示通过测试输出。
- REFACTOR:在保持测试通过的前提下改进代码。清理重复、改进命名、必要时抽取函数/类;每次修改后运行测试。
测试组织
文件结构示例:
project/
src/
module.py
tests/
conftest.py # Shared fixtures
test_module.py # Tests for module.py
pyproject.toml # Pytest configuration
命名约定:
- 测试文件:test_*.py 或 *_test.py
- 测试函数:test_*
- 测试类:Test*
- Fixtures:描述性名称(mock_database、sample_user)
Pytest 最佳实践
Fixtures:
import pytest
@pytest.fixture
def sample_config():
return {"key": "value"}
@pytest.fixture
def mock_client(mocker):
return mocker.MagicMock()
参数化:
@pytest.mark.parametrize("input,expected", [
("hello", "HELLO"),
("world", "WORLD"),
("", ""),
])
def test_uppercase(input, expected):
assert input.upper() == expected
异步测试:
import pytest
@pytest.mark.asyncio
async def test_async_function():
result = await async_operation()
assert result == expected
异常测试:
def test_raises_value_error():
with pytest.raises(ValueError, match="invalid input"):
process_input(None)
运行测试
使用 uv:
uv run pytest # Run all tests
uv run pytest tests/test_module.py # Run specific file
uv run pytest -k "test_name" # Run by name pattern
uv run pytest -v --tb=short # Verbose with short traceback
uv run pytest --cov=src --cov-report=term # With coverage
常用标志:
- -v / --verbose:详细输出
- -x / --exitfirst:首次失败即停止
- --tb=short:简短回溯
- --tb=no:不显示回溯
- -k EXPR:运行匹配表达式的测试
- -m MARKER:运行带标记的测试
- --cov=PATH:对路径统计覆盖率
- --cov-report=term-missing:显示未覆盖行
pyproject.toml 配置
最小配置:
[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]
完整配置:
[tool.pytest.ini_options]
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "function"
testpaths = ["tests"]
python_files = ["test_*.py", "*_test.py"]
python_functions = ["test_*"]
python_classes = ["Test*"]
addopts = "-v --tb=short"
markers = [
"slow: marks tests as slow",
"integration: marks integration tests",
]
filterwarnings = [
"ignore::DeprecationWarning",
]
[tool.coverage.run]
source = ["src"]
branch = true
omit = ["tests/*", "*/__init__.py"]
[tool.coverage.report]
exclude_lines = [
"pragma: no cover",
"if TYPE_CHECKING:",
"raise NotImplementedError",
]
fail_under = 80
show_missing = true
报告生成
TESTING_REPORT.local.md 文件应包含:
- 测试执行摘要(通过/失败/跳过)
- 按模块的覆盖率指标
- 按严重程度划分的审计发现
- 带 file:line 引用的建议
- 证据(命令输出)
与对话集成
当用户要求编写测试时:
- 检查对话历史,获取要测试内容的上下文。
- 识别正在讨论的代码/功能。
- 如果不清楚,提出澄清问题:
- “我应该测试什么具体行为?”
- “是否应包含 X 的边界情况?”
- “你想要单元测试、集成测试,还是两者都要?”
- 遵循 TDD:先写失败测试,再实现。
可用命令
- /tdd-pytest:init:初始化 pytest 配置
- /tdd-pytest:test [path]:使用 TDD 编写测试(上下文感知)
- /tdd-pytest:test-all:运行所有测试
- /tdd-pytest:report:生成/更新 TESTING_REPORT.local.md
适用场景与限制
适用场景:Python 项目中使用 pytest 进行测试驱动开发、测试质量审计、覆盖率运行与测试报告生成。
限制:资料未提供该技能的具体安装方式、支持的平台、收费或价格信息,暂未提供。