使用 pytest、TDD 方法论、fixtures、mocking、参数化和代码覆盖率要求的 Python 测试策略。
View on GitHubxu-xiang/everything-claude-code-zh
everything-claude-code
February 5, 2026
Select agents to install to:
npx add-skill https://github.com/xu-xiang/everything-claude-code-zh/blob/main/skills/python-testing/SKILL.md -a claude-code --skill python-testingInstallation paths:
.claude/skills/python-testing/# Python 测试模式(Python Testing Patterns)
使用 pytest、测试驱动开发(TDD)方法论及最佳实践的 Python 应用程序全面测试策略。
## 何时激活
- 编写新的 Python 代码时(遵循 TDD:红、绿、重构)
- 为 Python 项目设计测试套件时
- 审查 Python 测试覆盖率时
- 搭建测试基础设施时
## 核心测试理念
### 测试驱动开发(TDD)
始终遵循 TDD 循环:
1. **红(RED)**:为期望的行为编写一个失败的测试
2. **绿(GREEN)**:编写最少量的代码使测试通过
3. **重构(REFACTOR)**:在保持测试通过的前提下优化代码
```python
# 步骤 1:编写失败的测试 (RED)
def test_add_numbers():
result = add(2, 3)
assert result == 5
# 步骤 2:编写最小实现 (GREEN)
def add(a, b):
return a + b
# 步骤 3:根据需要进行重构 (REFACTOR)
```
### 覆盖率要求
- **目标**:80% 以上的代码覆盖率
- **关键路径**:必须达到 100% 覆盖率
- 使用 `pytest --cov` 来衡量覆盖率
```bash
pytest --cov=mypackage --cov-report=term-missing --cov-report=html
```
## pytest 基础
### 基本测试结构
```python
import pytest
def test_addition():
"""测试基础加法。"""
assert 2 + 2 == 4
def test_string_uppercase():
"""测试字符串大写转换。"""
text = "hello"
assert text.upper() == "HELLO"
def test_list_append():
"""测试列表追加。"""
items = [1, 2, 3]
items.append(4)
assert 4 in items
assert len(items) == 4
```
### 断言(Assertions)
```python
# 相等性
assert result == expected
# 不等性
assert result != unexpected
# 真值
assert result # Truthy
assert not result # Falsy
assert result is True # 精确为 True
assert result is False # 精确为 False
assert result is None # 精确为 None
# 成员资格
assert item in collection
assert item not in collection
# 比较
assert result > 0
assert 0 <= result <= 100
# 类型检查
assert isinstance(result, str)
# 异常测试(推荐做法)
with pytest.raises(ValueError):
raise ValueError("error message")
# 检查异常消息
with pytest.raises(ValueError, match="invalid input"):
raise ValueError("invalid input provided")
# 检查异常属性
with pytest.raises(ValueError) as exc_info:
raise ValueError("error message")
assert str(exc_info.value) == "error message"
```
## Fixtures
### 基础 Fixture 用法
```python
import pytest
@pytest.fixture
def sample_data():
"""提供示例数据的 Fixture。"""
return {"name": "Alice", "age": 30}
def test_sample_data(sample_data):
"""使用 fixture 的