Python 测试模式
使用 pytest、TDD 方法论和最佳实践的 Python 应用程序全面测试策略。
何时激活
- 编写新的 Python 代码(遵循 TDD:红、绿、重构)
- 为 Python 项目设计测试套件
- 审查 Python 测试覆盖率
- 设置测试基础设施
核心测试理念
测试驱动开发 (TDD)
始终遵循 TDD 循环:
- 红:为期望的行为编写一个失败的测试
- 绿:编写最少的代码使测试通过
- 重构:在保持测试通过的同时改进代码
# Step 1: Write failing test (RED)
def test_add_numbers():
result = add(2, 3)
assert result == 5
# Step 2: Write minimal implementation (GREEN)
def add(a, b):
return a + b
# Step 3: Refactor if needed (REFACTOR)
覆盖率要求
- 目标:80%+ 代码覆盖率
- 关键路径:需要 100% 覆盖率
- 使用
pytest --cov来测量覆盖率
pytest --cov=mypackage --cov-report=term-missing --cov-report=html
pytest 基础
基本测试结构
import pytest
def test_addition():
"""Test basic addition."""
assert 2 + 2 == 4
def test_string_uppercase():
"""Test string uppercasing."""
text = "hello"
assert text.upper() == "HELLO"
def test_list_append():
"""Test list append."""
items = [1, 2, 3]
items.append(4)
assert 4 in items
assert len(items) == 4
断言
# Equality
assert result == expected
# Inequality
assert result != unexpected
# Truthiness
assert result # Truthy
ass…