$ loading_
帮助你设计并实现基于pytest与TDD的高质量Python测试策略。
复制安装指令,让 AI 自动完成配置 · 推荐新手
请帮我安装 askskill 上的 "python-testing" 技能: 1. 下载 https://raw.githubusercontent.com/affaan-m/ECC/main/docs/ja-JP/skills/python-testing/SKILL.md 2. 保存为 ~/.claude/skills/python-testing/SKILL.md 3. 装好后重载技能,告诉我可以用了
请为这个Python工具库设计pytest测试方案,使用fixture、参数化和mock,覆盖正常路径、边界条件和异常场景,并给出可直接运行的测试代码。
一套结构清晰的pytest测试文件,包含夹具、参数化用例、mock示例与覆盖点说明。
请用TDD方式为这个Python函数新增功能:先写失败的pytest测试,再给出最小实现,最后说明如何重构并保持测试通过。
按红灯、绿灯、重构步骤组织的测试与实现代码,展示完整TDD过程。
请为这个Python项目制定测试覆盖率要求,说明如何用pytest和coverage配置最低阈值,并给出CI中失败条件的示例配置。
覆盖率策略说明、pytest/coverage配置示例,以及可用于CI的检查方案。
pytest、TDD方法論、ベストプラクティスを使用したPythonアプリケーションの包括的なテスト戦略。
常に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)
pytest --covを使用してカバレッジを測定pytest --cov=mypackage --cov-report=term-missing --cov-report=html
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
assert not result # Falsy
assert result is True # Exactly True
assert result is False # Exactly False
assert result is None # Exactly None
# Membership
assert item in collection
assert item not in collection
# Comparisons
assert result > 0
assert 0 <= result <= 100
# Type checking
assert isinstance(result, str)
# Exception testing (preferred approach)
with pytest.raises(ValueError):
raise ValueError("error message")
# Check exception message
with pytest.raises(ValueError, match="invalid input"):
raise ValueError("invalid input provided")
# Check exception attributes
with pytest.raises(ValueError) as exc_info:
raise ValueError("error message")
assert str(exc_info.value) == "error message"
import pytest
@pytest.fixture
def sample_data():
"""Fixture providing sample data."""
return {"name": "Alice", "age": 30}
def test_sample_data(sample_data):
"""Test using the fixture."""
assert sample_data["name"] == "Alice"
assert sample_data["age"] == 30
@pytest.fixture
def database():
"""Fixture with setup and teardown."""
# Setup
db = Database(":memory:")
db.create_tables()
db.insert_test_data()
yield db # Provide to test
# Teardown
db.close()
def test_database_query(database):
"""Test database operations."""
result = database.query("SELECT * FROM users")
assert len(result) > 0
# Function scope (default) - runs for each test
@pytest.fixture
def temp_file():
with open("temp.txt", "w") as f:
yield f
os.remove("temp.txt")
# Module scope - runs once per module
@pytest.fixture(scope="module")
def module_db():
db = Database(":memory:")
db.create_tables()
yield db
db.close()
# Session scope - runs once per test session
@pytest.fixture(scope="session")
def shared_resource():
resource = ExpensiveResource()
yield resource
resource.cleanup()
@pytest.fixture(params=[1, 2, 3])
def number(request):
"""Parameterized fixture."""
return request.param
def test_numbers(number):
"""Test runs 3 times, once for each parameter."""
assert number > 0
@pytest.fixture
def user():
return User(id=1, name="Alice")
@pytest.fixture
def admin():
return User(id=2, name="Admin", role="admin")
def test_user_admin_interaction(user, admin):
"""Test using multiple fixtures."""
assert admin.can_manage(user)
@pytest.fixture(autouse=True)
def reset_config():
"""Automatically runs before every test."""
…
通过双评审智能体对结果进行对抗式校验,提升输出发布前的可靠性
帮助开发者用 pytest-django 与 TDD 构建高质量 Django 测试体系。