pytest
Pytest Testing Guide
Write Python tests efficiently with pytest.
Quick Start
pip install pytest
# test_example.py
def test_addition():
assert 1 + 1 == 2
Run: pytest or pytest -v
Core Concepts
| Concept | Example |
|---|---|
| Test function | def test_something(): |
| Assertion | assert result == expected |
| Fixture | @pytest.fixture - dependency injection |
| Marker | @pytest.mark.skip - test metadata |
| Parametrize | @pytest.mark.parametrize - multiple inputs |
Essential Patterns
Basic Test
def test_function():
result = my_function(1, 2)
assert result == 3
Exception Testing
import pytest
def test_raises():
with pytest.raises(ValueError, match="invalid"):
raise ValueError("invalid input")
Fixture (Setup/Teardown)
@pytest.fixture
def database():
db = create_db()
yield db # provide to test
db.cleanup() # teardown
def test_query(database):
assert database.query("SELECT 1")
Parametrize
@pytest.mark.parametrize("input,expected", [
(1, 2),
(2, 4),
(3, 6),
])
def test_double(input, expected):
assert input * 2 == expected
Mocking
def test_mock(monkeypatch):
monkeypatch.setattr("module.func", lambda: "mocked")
monkeypatch.setenv("API_KEY", "test-key")
Reference Files
| Topic | File | When to Use |
|---|---|---|
| Basics | basics.md | Test discovery, assertions, running tests, config |
| Fixtures | fixtures.md | Setup/teardown, scopes, factories, conftest.py |
| Markers | markers.md | skip, xfail, parametrize, custom markers |
| Mocking | mocking.md | monkeypatch, pytest-mock, spies, async mocks |
| Plugins | plugins.md | Coverage, parallel, async, Django, Flask, FastAPI |
Common Commands
pytest # Run all tests
pytest -v # Verbose
pytest -s # Show prints
pytest -x # Stop on first failure
pytest -k "pattern" # Run matching tests
pytest -m slow # Run by marker
pytest --cov=mypackage # With coverage
pytest -n auto # Parallel (xdist)
pytest --lf # Run last failed
pytest --pdb # Debug on failure
Project Structure
project/
├── src/
│ └── mypackage/
│ └── module.py
├── tests/
│ ├── conftest.py # Shared fixtures
│ ├── test_unit.py
│ └── test_integration.py
├── pytest.ini # Or pyproject.toml
└── requirements-test.txt
Configuration (pyproject.toml)
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-v --tb=short"
markers = [
"slow: slow tests",
"integration: integration tests",
]
Built-in Fixtures
| Fixture | Purpose |
|---|---|
tmp_path |
Temp directory (pathlib.Path) |
tmpdir |
Temp directory (legacy) |
capsys |
Capture stdout/stderr |
caplog |
Capture logging |
monkeypatch |
Patch attributes/env vars |
request |
Test/fixture metadata |
Fixture Scopes
@pytest.fixture(scope="function") # Default - per test
@pytest.fixture(scope="class") # Per test class
@pytest.fixture(scope="module") # Per file
@pytest.fixture(scope="session") # Per test run
Best Practices
- Name tests descriptively:
test_user_login_with_invalid_password_fails - One assertion concept per test
- Use fixtures for reusable setup
- Use
conftest.pyfor shared fixtures - Use markers to categorize tests (unit, integration, slow)
- Run with coverage:
pytest --cov --cov-report=html - Use parametrize to reduce duplicate tests
More from salmanferozkhan/cloud-and-fast-api
chainlit
Expert guidance for building conversational AI applications with Chainlit framework in Python. Use when (1) creating chat interfaces for LLM applications, (2) building apps with OpenAI, LangChain, LlamaIndex, or Mistral AI, (3) implementing streaming responses, (4) adding UI elements like images, files, charts, (5) handling user file uploads, (6) implementing authentication (OAuth, password), (7) creating multi-step workflows with visible steps, (8) building RAG applications with document upload, or (9) deploying chat apps to web, Slack, Discord, or Teams.
87microsoft-agent-framework
Expert guidance for building AI agents and multi-agent workflows using Microsoft Agent Framework for .NET. Use when (1) creating AI agents with OpenAI or Azure OpenAI, (2) implementing function tools and structured outputs, (3) building multi-turn conversations, (4) designing graph-based workflows with streaming/checkpointing, (5) implementing middleware pipelines, (6) orchestrating multi-agent systems with fan-out/fan-in patterns, (7) adding human-in-the-loop interactions, (8) integrating OpenTelemetry observability, or (9) exposing agents as MCP tools.
3ship-hero
Expert guidance for integrating with ShipHero's GraphQL API for fulfillment, inventory, orders, and returns management. Use when (1) authenticating with ShipHero API, (2) managing orders (create, update, cancel, query), (3) managing products and inventory levels, (4) creating and tracking shipments, (5) processing returns, (6) working with purchase orders, (7) setting up webhooks for real-time events, (8) implementing 3PL multi-tenant operations, or (9) optimizing GraphQL query costs and pagination.
3doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks.
3context7-efficient
Token-efficient library documentation fetcher using Context7 MCP with 86.8% token savings through intelligent shell pipeline filtering. Fetches code examples, API references, and best practices for JavaScript, Python, Go, Rust, and other libraries. Use when users ask about library documentation, need code examples, want API usage patterns, are learning a new framework, need syntax reference, or troubleshooting with library-specific information. Triggers include questions like "Show me React hooks", "How do I use Prisma", "What's the Next.js routing syntax", or any request for library/framework documentation.
3fetch-library-docs
Fetches official documentation for external libraries and frameworks (React, Next.js, Prisma, FastAPI, Express, Tailwind, MongoDB, etc.) with 60-90% token savings via content-type filtering. Use this skill when implementing features using library APIs, debugging library-specific errors, troubleshooting configuration issues, installing or setting up frameworks, integrating third-party packages, upgrading between library versions, or looking up correct API patterns and best practices. Triggers automatically during coding work - fetch docs before writing library code to get correct patterns, not after guessing wrong.
3