Generate pytest fixtures for test setup, teardown, and dependency injection with best practices for modular, explicit, and scalable test architecture.
Generate pytest fixtures following best practices for test setup, teardown, and dependency injection. Pytest fixtures provide explicit, modular, and scalable test context management.
This skill helps you create and work with pytest fixtures - functions that provide a defined, reliable, and consistent context for tests. Fixtures handle the "arrange" phase of tests and can manage:
When the user requests pytest fixture creation or guidance:
1. **Understand the Context**
- Identify what needs to be set up (database, API client, test data, etc.)
- Determine the scope needed (function, class, module, session)
- Check if fixtures need to depend on other fixtures
- Identify any teardown/cleanup requirements
2. **Create Fixtures Following Best Practices**
- Use `@pytest.fixture` decorator
- Give fixtures explicit, descriptive names
- Keep fixtures modular - one responsibility per fixture
- Use fixture parameters to inject dependencies
- Implement proper teardown with `yield` when needed
3. **Structure for Scalability**
- Place shared fixtures in `conftest.py` at appropriate levels
- Use fixture composition (fixtures using other fixtures)
- Consider parametrization for fixtures that need multiple configurations
- Set appropriate scope (`function`, `class`, `module`, `session`)
4. **Handle Cleanup Properly**
- Use `yield` for fixtures that need teardown
- Ensure cleanup happens even if tests fail
- Avoid complex error handling in teardown - keep it simple
5. **Document and Explain**
- Add docstrings explaining what each fixture provides
- Document any dependencies between fixtures
- Note any important limitations or caveats
```python
import pytest
@pytest.fixture
def sample_data():
"""Provides sample data for testing."""
return {"key": "value", "count": 42}
def test_data_access(sample_data):
assert sample_data["key"] == "value"
```
```python
@pytest.fixture
def database_connection():
"""Provides a database connection with automatic cleanup."""
conn = create_connection()
yield conn
conn.close()
```
```python
@pytest.fixture
def user():
return User(name="test_user")
@pytest.fixture
def authenticated_client(user):
"""Provides an authenticated API client."""
client = APIClient()
client.authenticate(user)
return client
```
```python
@pytest.fixture(scope="module")
def expensive_resource():
"""Module-scoped fixture - created once per test module."""
resource = create_expensive_resource()
yield resource
resource.cleanup()
```
1. **Explicit over Implicit**: Fixtures are explicitly declared as test parameters
2. **Modular**: Each fixture has a single, clear purpose
3. **Composable**: Fixtures can depend on other fixtures
4. **Minimal Dependencies**: Only depend on what you actually need
5. **Clean Separation**: Keep setup, execution, and teardown clearly separated
Choose the widest scope that's safe for your use case to optimize performance.
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/pytest-fixtures-guide/raw