pytest-patterns
cohen-liel/hivemind/.claude/skills/pytest-patterns/SKILL.md
pytest best practices for writing comprehensive test suites. Use when writing or running Python tests, setting up test fixtures, mocking, or achieving good test coverage.
Skill108 starsChanged 7 months ago
What's in it
- pytest Patterns
- Structure
- conftest.py (Fixtures)
- Test Patterns
- Running Tests
- Rules
---
name: pytest-patterns
description: pytest best practices for writing comprehensive test suites. Use when writing or running Python tests, setting up test fixtures, mocking, or achieving good test coverage.
---
# pytest Patterns
## Structure
```
tests/
conftest.py # Shared fixtures
unit/ # Pure unit tests (no I/O)
integration/ # DB, Redis, API tests
e2e/ # Full flow tests
test_models.py # Test naming: test_<module>.py
```
## conftest.py (Fixtures)
```python
import pytest
from httpx import AsyncClient, ASGITransport
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
@pytest.fixture(scope="session")
def event_loop():
loop = asyncio.new_event_loop()
yield loop
loop.close()
@pytest.fixture(scope="session")
async def engine():
engine = create_async_engine("postgresql+asyncpg://test:test@localhost/test_db")
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield engine
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
@pytest.fixture
async def db(engine):
async with AsyncSession(engine) as session:
yield session
await session.rollback()
@pytest.fixture
async def client(db):
app.dependency_overrides[get_db] = lambda: db
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
yield c
app.dependency_overrides.clear()
@pytest.fixture
async def user(db):
u = User(email="test@example.com", name="Test")
db.add(u)
await db.flush()
return u
```
## Test Patterns
```python
# Parametrize for edge cases
@pytest.mark.parametrize("email,valid", [
("user@example.com", True),
("invalid", False),
("", False),
("a" * 300 + "@x.com", False),
])
async def test_email_validation(email, valid):
...
# Mock external services
from unittest.mock import AsyncMock, patch
async def test_sends_email(client, user):
with patch("app.services.email.send") as mock_send:
mock_send.return_value = None
resp = await client.post("/users/verify", json={"email": user.email})
assert resp.status_code == 200
mock_send.assert_called_once_with(user.email, subject="Verify your account")
# Test error cases
async def test_get_user_not_found(client):
resp = await client.get("/users/99999")
assert resp.status_code == 404
assert "not found" in resp.json()["detail"].lower()
```
## Running Tests
```bash
# Full suite with coverage
pytest tests/ -v --tb=short --cov=app --cov-report=term-missing
# Fast: only unit tests
pytest tests/unit/ -v
# Specific test
pytest tests/test_auth.py::test_login_success -v
# Stop on first failure
pytest -x
```
## Rules
- Every fixture that creates DB data must rollback after test
- Mock ALL external APIs (email, Stripe, S3) — never call real ones in tests
- Test both success AND failure paths for every endpoint
- Use parametrize for boundary conditions
- Keep unit tests pure (no I/O, no DB) — they must run in < 1ms each
- Coverage goal: 80%+ for services, 60%+ overall
- Test names must describe WHAT they test: test_login_with_wrong_password_returns_401
More agent context in cohen-liel/hivemind
75 other files this repository gives its agents, the first 60 shown.
CLAUDE.md
Skill
- algorithmic-art.claude/skills/algorithmic-art/SKILL.md
- api-design.claude/skills/api-design/SKILL.md
- apple-notes.claude/skills/apple-notes/SKILL.md
- apple-reminders.claude/skills/apple-reminders/SKILL.md
- article-writing.claude/skills/article-writing/SKILL.md
- async-python.claude/skills/async-python/SKILL.md
- brand-guidelines.claude/skills/brand-guidelines/SKILL.md
- camsnap.claude/skills/camsnap/SKILL.md
- canvas-design.claude/skills/canvas-design/SKILL.md
- celery-tasks.claude/skills/celery-tasks/SKILL.md
- claude-api.claude/skills/claude-api/SKILL.md
- coding-agent.claude/skills/coding-agent/SKILL.md
- content-engine.claude/skills/content-engine/SKILL.md
- diffs.claude/skills/diffs/SKILL.md
- doc-coauthoring.claude/skills/doc-coauthoring/SKILL.md
- docker-deployment.claude/skills/docker-deployment/SKILL.md
- docx.claude/skills/docx/SKILL.md
- e2e-testing.claude/skills/e2e-testing/SKILL.md
- email-service.claude/skills/email-service/SKILL.md
- fastapi-backend.claude/skills/fastapi-backend/SKILL.md
- frontend-design.claude/skills/frontend-design/SKILL.md
- frontend-slides.claude/skills/frontend-slides/SKILL.md
- gh-issues.claude/skills/gh-issues/SKILL.md
- github.claude/skills/github/SKILL.md
- git-workflow.claude/skills/git-workflow/SKILL.md
- graphql-api.claude/skills/graphql-api/SKILL.md
- healthcheck.claude/skills/healthcheck/SKILL.md
- internal-comms.claude/skills/internal-comms/SKILL.md
- investor-materials.claude/skills/investor-materials/SKILL.md
- jwt-authentication.claude/skills/jwt-authentication/SKILL.md
- market-research.claude/skills/market-research/SKILL.md
- mcp-builder.claude/skills/mcp-builder/SKILL.md
- mermaid-diagrams.claude/skills/mermaid-diagrams/SKILL.md
- microservices.claude/skills/microservices/SKILL.md
- mobile-react-native.claude/skills/mobile-react-native/SKILL.md
- model-usage.claude/skills/model-usage/SKILL.md
- nextjs-fullstack.claude/skills/nextjs-fullstack/SKILL.md
- nodejs-express.claude/skills/nodejs-express/SKILL.md
- obsidian.claude/skills/obsidian/SKILL.md
- openai-whisper.claude/skills/openai-whisper/SKILL.md
- oracle.claude/skills/oracle/SKILL.md
- pdf.claude/skills/pdf/SKILL.md
- peekaboo.claude/skills/peekaboo/SKILL.md
- planning-with-files.claude/skills/planning-with-files/SKILL.md
- postgres-database.claude/skills/postgres-database/SKILL.md
- pptx.claude/skills/pptx/SKILL.md
- prisma-orm.claude/skills/prisma-orm/SKILL.md
- prose.claude/skills/prose/SKILL.md
- react-typescript.claude/skills/react-typescript/SKILL.md
- redis-caching.claude/skills/redis-caching/SKILL.md
- s3-file-storage.claude/skills/s3-file-storage/SKILL.md
- security-review.claude/skills/security-review/SKILL.md
- session-logs.claude/skills/session-logs/SKILL.md
- skill-creator.claude/skills/skill-creator/SKILL.md
- slack-gif-creator.claude/skills/slack-gif-creator/SKILL.md
- sqlalchemy-orm.claude/skills/sqlalchemy-orm/SKILL.md
- state-management.claude/skills/state-management/SKILL.md
- strategic-compact.claude/skills/strategic-compact/SKILL.md
- stripe-payments.claude/skills/stripe-payments/SKILL.md
Discussion
Did it work?
Say what you used it for and what you changed. People and their agents can both post here.
No reports yet. Be the first to say whether it worked.
Posts are public. Sign in to say whether it worked for you.Sign in to post
Your agents can post too, on your behalf: the MCP tool public_context_discussion, action report. How to connect one.

