testing-strategy-python
Python/FastAPI/Django testing conventions. pytest, fixtures, httpx, TestClient, factory_boy. Use when writing or reviewing Python tests.
Best use case
testing-strategy-python is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Python/FastAPI/Django testing conventions. pytest, fixtures, httpx, TestClient, factory_boy. Use when writing or reviewing Python tests.
Teams using testing-strategy-python should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/testing-strategy-python/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How testing-strategy-python Compares
| Feature / Agent | testing-strategy-python | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Python/FastAPI/Django testing conventions. pytest, fixtures, httpx, TestClient, factory_boy. Use when writing or reviewing Python tests.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
SKILL.md Source
Python testing conventions for FastAPI, Django, and Flask.
## Frameworks
- **Unit/Integration tests**: pytest (always — never unittest style)
- **API tests**: `httpx.AsyncClient` (FastAPI) or `TestClient`
- **Mocking**: `pytest-mock` (wrapper around `unittest.mock`)
- **Fixtures**: pytest fixtures (not setUp/tearDown)
- **Test data**: `factory_boy` or plain fixture functions
## Unit Tests
```python
import pytest
from unittest.mock import AsyncMock
from app.services.order_service import OrderService
@pytest.fixture
def mock_repo():
repo = AsyncMock()
repo.find_by_id.return_value = {"id": 1, "status": "PENDING"}
repo.save.return_value = {"id": 1, "status": "PENDING"}
return repo
@pytest.fixture
def service(mock_repo):
return OrderService(repository=mock_repo)
async def test_create_order_sets_pending_status(service, mock_repo):
result = await service.create_order(product_id=1, quantity=2)
assert result["status"] == "PENDING"
mock_repo.save.assert_called_once()
async def test_find_order_raises_when_not_found(service, mock_repo):
mock_repo.find_by_id.return_value = None
with pytest.raises(OrderNotFoundError):
await service.find_by_id(999)
```
### Rules
- Use `pytest.fixture` for all setup — never class-based `setUp`/`tearDown`
- Use `AsyncMock` for async functions, `MagicMock` for sync
- Fixtures compose: small fixtures combine into larger ones
- Use `conftest.py` for shared fixtures across test modules
## FastAPI API Tests
```python
import pytest
from httpx import AsyncClient, ASGITransport
from app.main import app
@pytest.fixture
async def client():
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
yield client
async def test_get_orders_returns_list(client):
response = await client.get("/api/orders", headers={"Authorization": "Bearer test-token"})
assert response.status_code == 200
assert isinstance(response.json(), list)
async def test_create_order_validates_input(client):
response = await client.post("/api/orders", json={"quantity": -1})
assert response.status_code == 422
assert "quantity" in response.json()["detail"][0]["loc"]
async def test_get_order_returns_404_when_not_found(client):
response = await client.get("/api/orders/999")
assert response.status_code == 404
```
### Rules
- Use `httpx.AsyncClient` with `ASGITransport` for async FastAPI
- Use `TestClient` from Starlette for sync tests (simpler)
- Override dependencies with `app.dependency_overrides[get_db] = mock_db`
- Test status codes, response body, validation errors
## Django Tests
```python
import pytest
from django.test import Client
from app.models import Order
@pytest.fixture
def api_client():
return Client()
@pytest.mark.django_db
def test_list_orders(api_client):
Order.objects.create(status="PENDING")
response = api_client.get("/api/orders/")
assert response.status_code == 200
assert len(response.json()) == 1
@pytest.mark.django_db
def test_create_order(api_client):
response = api_client.post("/api/orders/", data={"product_id": 1}, content_type="application/json")
assert response.status_code == 201
assert Order.objects.count() == 1
```
### Rules
- Mark DB tests with `@pytest.mark.django_db`
- Use `pytest-django` plugin
- Use `baker.make(Order)` from `model_bakery` for test data
- Transaction rollback is automatic per test
## Fixtures Pattern (conftest.py)
```python
# tests/conftest.py
import pytest
from app.database import get_test_db
@pytest.fixture(scope="session")
def db_engine():
"""Create test database once per session."""
engine = create_engine("sqlite:///test.db")
Base.metadata.create_all(engine)
yield engine
Base.metadata.drop_all(engine)
@pytest.fixture
def db_session(db_engine):
"""Fresh DB session per test with rollback."""
connection = db_engine.connect()
transaction = connection.begin()
session = Session(bind=connection)
yield session
session.close()
transaction.rollback()
connection.close()
@pytest.fixture
def sample_order(db_session):
order = Order(status="PENDING", product_id=1)
db_session.add(order)
db_session.commit()
return order
```
## File Structure
```
tests/
├── conftest.py Shared fixtures
├── unit/
│ ├── test_order_service.py
│ └── test_payment_service.py
├── api/
│ ├── test_orders_api.py
│ └── test_auth_api.py
└── integration/
└── test_order_workflow.py
```
## Naming
- File: `test_module_name.py` (pytest auto-discovers `test_` prefix)
- Function: `test_should_behavior_when_condition` or `test_behavior_description`
- No classes needed — plain functions with fixturesRelated Skills
typescript-testing
Comprehensive testing guidance for TypeScript projects including unit testing patterns, mocking strategies, and test organization best practices
testing-tauri-apps
Guides developers through testing Tauri applications including unit testing with mock runtime, mocking Tauri APIs, WebDriver end-to-end testing with Selenium and WebdriverIO, and CI integration with GitHub Actions.
testing-strategy-builder
Use this skill when creating comprehensive testing strategies for applications. Provides test planning templates, coverage targets, test case structures, and guidance for unit, integration, E2E, and performance testing. Ensures robust quality assurance across the development lifecycle.
testing-skills-activation
Use when creating or refining Claude Code skills to validate that skill descriptions trigger correctly - provides systematic testing methodology for skill activation patterns using test cases and automated evaluation
Testing Skill
Automatiza pruebas y diagnósticos del sistema SmartK et sin perder tiempo
testing-qa
Comprehensive testing and QA workflow covering unit testing, integration testing, E2E testing, browser automation, and quality assurance.
testing-principles
Language-agnostic testing principles including TDD, test quality, coverage standards, and test design patterns. Use when writing tests, designing test strategies, or reviewing test quality.
testing-patterns
TDD and unit testing guidance for Crispy CRM. Use when writing tests, implementing TDD, debugging test failures, or setting up test infrastructure. Covers Vitest patterns, React Admin component testing, Zod schema validation testing, Supabase mocking, E2E with Playwright, and manual E2E testing with Claude Chrome. Integrates with verification-before-completion for test verification.
testing-builder
Automatically generates comprehensive test suites (unit, integration, E2E) based on code and past testing patterns. Use when user says "write tests", "test this", "add coverage", or after fixing bugs to create regression tests. Eliminates testing friction for ADHD users.
Testing Anti-Patterns
This skill should be used when encountering "flaky tests", "test maintenance issues", "slow test suites", "brittle tests", "test code smells", "test debugging problems", or when tests are hard to understand, maintain, or debug.
temporal-python-pro
Master Temporal workflow orchestration with Python SDK. Implements durable workflows, saga patterns, and distributed transactions. Covers async/await, testing strategies, and production deployment.
standards-python
This skill provides Python coding standards and is automatically loaded for Python projects. It includes naming conventions, best practices, and recommended tooling.