Python Testing
This skill provides comprehensive Python testing patterns using pytest as the primary testing framework.
Testing Framework
Use pytest as the testing framework for its powerful features and clean syntax.
Basic Test Structure
Test Discovery
pytest automatically discovers tests following these conventions:
- Files:
test_*.pyor*_test.py - Functions:
test_* - Classes:
Test*(without__init__) - Methods:
test_*
Fixtures
Fixtures provide reusable test setup and teardown:
Fixture Scopes
Fixture Dependencies
Parametrization
Test multiple inputs with @pytest.mark.parametrize:
Multiple Parameters
Parametrize with IDs
Test Markers
Use markers for test categorization and selective execution:
Run specific markers:
Mocking
Using unittest.mock
pytest-mock Plugin
Coverage Analysis
Basic Coverage
HTML Coverage Report
Coverage Configuration
Branch Coverage
Async Testing
Testing Async Functions
Test Organization
Directory Structure
conftest.py
Assertions
Basic Assertions
pytest Assertions with Better Error Messages
Custom Assertion Messages
Approximate Comparisons
Exception Testing
Test Helpers
Property-Based Testing
Using hypothesis for property-based testing:
Best Practices
- One assertion per test (when possible)
- Use descriptive test names - describe what's being tested
- Arrange-Act-Assert pattern - clear test structure
- Use fixtures for setup - avoid duplication
- Mock external dependencies - keep tests fast and isolated
- Test edge cases - empty inputs, None, boundaries
- Use parametrize - test multiple scenarios efficiently
- Keep tests independent - no shared state between tests
Running Tests
When to Use This Skill
- Writing new Python tests
- Improving test coverage
- Setting up pytest infrastructure
- Debugging flaky tests
- Implementing integration tests
- Testing async Python code


