帮助你设计并实现 Python 自动化测试策略,覆盖 pytest、TDD、mock 与覆盖率要求。
复制安装指令,让 AI 自动完成配置 · 推荐新手
请帮我安装 askskill 上的 "python-testing" 技能: 1. 下载 https://raw.githubusercontent.com/affaan-m/ECC/main/docs/tr/skills/python-testing/SKILL.md 2. 保存为 ~/.claude/skills/python-testing/SKILL.md 3. 装好后重载技能,告诉我可以用了
请为这个 Python 模块编写 pytest 测试,包含正常路径、异常路径和边界条件,并使用 fixture 复用测试数据。
一套结构清晰的 pytest 测试代码,包含 fixture、断言和多场景用例。
我想用 TDD 开发一个用户注册函数,请先列出测试用例,再按红灯-绿灯-重构步骤给出实现建议。
按 TDD 方法组织的测试清单、迭代步骤和对应实现思路。
请为调用第三方 API 的 Python 服务编写测试,使用 mocking 隔离外部请求,并说明如何配置 coverage 阈值。
包含 mock 示例、测试策略以及 coverage 配置说明的完整方案。
pytest, TDD metodolojisi ve en iyi uygulamalar kullanarak Python uygulamaları için kapsamlı test stratejileri.
Her zaman TDD döngüsünü takip edin:
# Adım 1: Başarısız test yaz (RED)
def test_add_numbers():
result = add(2, 3)
assert result == 5
# Adım 2: Minimal implementasyon yaz (GREEN)
def add(a, b):
return a + b
# Adım 3: Gerekirse refactor et (REFACTOR)
pytest --cov kullanınpytest --cov=mypackage --cov-report=term-missing --cov-report=html
import pytest
def test_addition():
"""Temel toplama testi."""
assert 2 + 2 == 4
def test_string_uppercase():
"""String büyük harf yapma testi."""
text = "hello"
assert text.upper() == "HELLO"
def test_list_append():
"""Liste append testi."""
items = [1, 2, 3]
items.append(4)
assert 4 in items
assert len(items) == 4
# Eşitlik
assert result == expected
# Eşitsizlik
assert result != unexpected
# Doğruluk değeri
assert result # Truthy
assert not result # Falsy
assert result is True # Tam olarak True
assert result is False # Tam olarak False
assert result is None # Tam olarak None
# Üyelik
assert item in collection
assert item not in collection
# Karşılaştırmalar
assert result > 0
assert 0 <= result <= 100
# Tip kontrolü
assert isinstance(result, str)
# Exception testi (tercih edilen yaklaşım)
with pytest.raises(ValueError):
raise ValueError("error message")
# Exception mesajını kontrol et
with pytest.raises(ValueError, match="invalid input"):
raise ValueError("invalid input provided")
# Exception niteliklerini kontrol et
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():
"""Örnek veri sağlayan fixture."""
return {"name": "Alice", "age": 30}
def test_sample_data(sample_data):
"""Fixture kullanan test."""
assert sample_data["name"] == "Alice"
assert sample_data["age"] == 30
@pytest.fixture
def database():
"""Setup ve teardown ile fixture."""
# Setup
db = Database(":memory:")
db.create_tables()
db.insert_test_data()
yield db # Teste sağla
# Teardown
db.close()
def test_database_query(database):
"""Veritabanı operasyonlarını test et."""
result = database.query("SELECT * FROM users")
assert len(result) > 0
# Function scope (varsayılan) - her test için çalışır
@pytest.fixture
def temp_file():
with open("temp.txt", "w") as f:
yield f
os.remove("temp.txt")
# Module scope - modül başına bir kez çalışır
@pytest.fixture(scope="module")
def module_db():
db = Database(":memory:")
db.create_tables()
yield db
db.close()
# Session scope - test oturumu başına bir kez çalışır
@pytest.fixture(scope="session")
def shared_resource():
resource = ExpensiveResource()
yield resource
resource.cleanup()
@pytest.fixture(params=[1, 2, 3])
def number(request):
"""Parametreli fixture."""
return request.param
def test_numbers(number):
"""Test her parametre için 3 kez çalışır."""
assert number > 0
…
通过双评审智能体对结果进行对抗式校验,提升输出发布前的可靠性
帮助开发者用 pytest-django 与 TDD 构建高质量 Django 测试体系。