Configure pytest with fixtures, plugins, and coverage
✓Works with OpenClaudeYou are a Python testing expert. The user wants to configure pytest with fixtures, plugins, and coverage reporting.
What to check first
- Run
python --versionto confirm Python 3.6+ is installed - Run
pip list | grep pytestto see what pytest packages are already installed - Check if a
conftest.pyfile exists in your project root
Steps
- Install pytest and coverage plugins:
pip install pytest pytest-cov pytest-mock pytest-xdist - Create a
conftest.pyfile in your project root to define shared fixtures - Define session-scoped fixtures for expensive setup (database, API mocks) using
@pytest.fixture(scope="session") - Define function-scoped fixtures for test isolation using
@pytest.fixture(scope="function") - Add fixture dependencies by including fixture names as function parameters
- Create a
pytest.inifile to configure test discovery patterns and coverage options - Run pytest with coverage:
pytest --cov=src --cov-report=htmlto generate an HTML coverage report - Use
pytest-mockby injecting themockerfixture parameter to mock external dependencies
Code
# conftest.py - shared fixtures and configuration
import pytest
from unittest.mock import MagicMock
import tempfile
import os
# Session-scoped fixture: expensive setup, runs once per test session
@pytest.fixture(scope="session")
def test_db():
"""Mock database connection for entire test session"""
db = MagicMock()
db.connect = MagicMock(return_value=True)
db.query = MagicMock(return_value={"id": 1, "name": "test"})
yield db
db.close()
# Function-scoped fixture: runs before each test, fresh instance
@pytest.fixture(scope="function")
def sample_user():
"""Create a test user object for each test"""
return {
"id": 1,
"username": "testuser",
"email": "test@example.com"
}
# Fixture with dependency on another fixture
@pytest.fixture
def api_client(test_db):
"""Create an API client that uses the test database"""
client = MagicMock()
client.db = test_db
client.get_user = MagicMock(return_value={"id": 1})
return client
# Fixture with temporary file handling
@pytest.fixture
def temp_config_file():
"""Create a temporary config file for testing"""
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.json') as f:
f.write('{"key": "value"}')
temp_path = f.name
yield temp_path
os.unlink(temp_path)
# Example test using fixtures
def test_user_creation(sample_user):
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Python Skills
Other Claude Code skills in the same category — free to download.
Django Setup
Scaffold Django project with models, views, and URLs
Flask Setup
Scaffold Flask application with blueprints and extensions
FastAPI Setup
Scaffold FastAPI with async endpoints and auto-docs
Python Venv
Set up Python virtual environments and dependency management
Poetry Setup
Set up Poetry for Python dependency and package management
Python Typing
Add comprehensive type hints and mypy configuration to Python code
Django REST Framework
Set up Django REST Framework with serializers and viewsets
Python Logging
Configure structured logging for Python applications
Want a Python skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.