Build robust Python test suites with pytest, TDD, mocking, and coverage.
Copy the install command and let the AI configure it · recommended for beginners
Please install the "python-testing" skill from askskill: 1. Download https://raw.githubusercontent.com/affaan-m/ECC/main/skills/python-testing/SKILL.md 2. Save it as ~/.claude/skills/python-testing/SKILL.md 3. Reload skills and tell me it's ready
Design a pytest test plan for this Python module using TDD. Include happy paths, edge cases, exception handling, fixture design, and coverage targets, then provide example test code: [paste module code]
A structured test strategy with test cases, fixture plan, coverage goals, and runnable sample tests.
The function below calls a database and a third-party API. Write unit tests for it using pytest and mocking, isolate external dependencies, and explain the purpose of each mock: [paste function code]
Unit test code using mocks and patches, plus an explanation of the isolation strategy and key assertions.
Review this existing pytest suite, identify duplicated cases and missing scenarios, refactor it into parametrized tests, and suggest how to raise coverage to 90%: [paste existing test code]
Refactored parametrized tests, plus a coverage gap analysis and a list of improvement recommendations.
Comprehensive testing strategies for Python applications using pytest, TDD methodology, and best practices.
Always follow the TDD cycle:
# 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 to measure coveragepytest --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():
…
Plan demand forecasts, safety stock, and replenishment for multi-location retail inventory.
Automatically format, lint, and fix code issues on every edit.
Apply NestJS architecture patterns to build maintainable production-ready TypeScript backends.
Learn robust error-handling patterns across TypeScript, Python, and Go applications.
Audit Claude skills and commands with quick scans or full stocktakes.
Create iOS liquid glass interfaces with dynamic visuals and interactive morphing.
Build robust Django tests with pytest-django, TDD, mocks, factories, and API coverage.
Write, run, and improve Perl automated tests with coverage analysis.
Learn Rust testing patterns and TDD to improve code quality and reliability.
Build high-quality Kotlin tests with Kotest, MockK, coroutines, and coverage.
Design test strategies and plans with coverage, methods, and quality priorities.
Write idiomatic Go tests, benchmarks, fuzz tests, and improve coverage.