pytest Coverage

pytest-coverage skill for programming & development

A Python testing skill focused on pytest with code coverage analysis, covering test writing, fixture management, parameterized testing, mocking, and coverage configuration for comprehensive Python test suites.

What Is This?

Overview

This skill provides complete pytest and coverage guidance including test structure, fixture patterns, parameterized tests, mocking with unittest.mock, and pytest-cov configuration. It covers coverage reporting, branch coverage analysis, and CI integration for maintaining high-quality Python codebases.

Who Should Use This

Perfect for Python developers writing unit tests, data engineers testing pipelines, Django and FastAPI teams building test suites, and teams enforcing coverage thresholds in CI pipelines.

Why Use It?

Problems It Solves

Python projects without systematic testing accumulate bugs and resist refactoring. Developers struggle with pytest fixture scoping, mock configuration, and coverage gaps. This skill provides patterns for effective testing with measurable coverage targets.

Core Highlights

  • pytest Patterns - Fixtures, parameterization, markers, and plugins
  • Coverage Analysis - Line and branch coverage with gap identification
  • Mocking - unittest.mock patterns for isolating dependencies
  • CI Integration - Coverage thresholds and reporting in pipelines
  • Fixture Management - Scoped fixtures for efficient test setup

How to Use It?

Basic Usage

Ask Claude about Python testing, and this skill guides pytest and coverage setup.

Scenario 1: Writing Tests with Fixtures

Ask Claude: "Write pytest tests for my user service"

Claude will create:

import pytest
from unittest.mock import AsyncMock, patch
from app.services.user_service import UserService
from app.models import User

@pytest.fixture
def mock_db():
    db = AsyncMock()
    db.users.find_one = AsyncMock(return_value={"id": "1", "name": "Alice", "email": "alice@example.com"})
    return db

@pytest.fixture
def user_service(mock_db):
    return UserService(db=mock_db)

class TestUserService:
    async def test_get_user_returns_user(self, user_service, mock_db):
        user = await user_service.get_user("1")
        assert user.name == "Alice"
        mock_db.users.find_one.assert_called_once_with({"id": "1"})

    async def test_get_user_not_found_raises(self, user_service, mock_db):
        mock_db.users.find_one.return_value = None
        with pytest.raises(UserNotFoundError):
            await user_service.get_user("999")

    @pytest.mark.parametrize("email,valid", [
        ("alice@example.com", True),
        ("invalid-email", False),
        ("", False),
    ])
    def test_validate_email(self, user_service, email, valid):
        assert user_service.validate_email(email) == valid

Scenario 2: Coverage Configuration

Tell Claude: "Set up pytest coverage with 80% threshold"

Claude will configure:

[tool.pytest.ini_options]
testpaths = ["tests"]
asyncio_mode = "auto"
addopts = "--cov=app --cov-report=term-missing --cov-branch --cov-fail-under=80"

[tool.coverage.run]
source = ["app"]
branch = true
omit = ["app/migrations/*", "app/config.py"]

[tool.coverage.report]
show_missing = true
fail_under = 80
exclude_lines = [
    "pragma: no cover",
    "if __name__ == .__main__.",
    "if TYPE_CHECKING:",
]

Real-World Examples

API Test Suite

A FastAPI team achieved 92% coverage across 200+ endpoints. Fixtures for database sessions and authenticated clients made test writing fast. Coverage reports in CI caught untested error paths before production.

Data Pipeline Testing

A data engineering team tested ETL pipelines with pytest fixtures providing sample DataFrames. Parameterized tests validated transformations across 50+ edge cases, catching data type issues early.

Advanced Tips

Fixture Scoping

Use scope="session" for expensive fixtures like database connections. Use scope="function" (default) for fixtures that need fresh state per test.

Coverage Gap Analysis

Run pytest --cov-report=html to generate HTML coverage reports. Browse uncovered lines visually to identify critical paths missing tests.

When to Use It?

Use Cases

  • Unit Testing - Test functions and classes in isolation with mocks
  • Integration Testing - Validate component interactions with fixtures
  • API Testing - Test FastAPI or Django endpoints with test clients
  • Coverage Enforcement - Set and enforce minimum coverage thresholds
  • CI Pipeline Testing - Run tests and coverage checks automatically

Related Topics

When you ask Claude these questions, this skill will activate:

  • "Write pytest tests for my Python code"
  • "Set up code coverage with pytest"
  • "How do I mock in pytest?"
  • "Configure pytest-cov in CI"

Important Notes

Requirements

  • Python 3.8+ with pytest 7.0+ installed
  • pytest-cov plugin for coverage reporting
  • pytest-asyncio for async test support (if needed)
  • pytest-mock for enhanced mocking utilities (optional)

Usage Recommendations

Do:

  • Use fixtures for setup - Avoid repeating setup code across tests
  • Enable branch coverage - Line coverage alone misses conditional paths
  • Test error paths - Verify exception handling and edge cases
  • Run coverage in CI - Enforce thresholds on every pull request

Don't:

  • Don't chase 100% coverage - Focus on critical paths over vanity metrics
  • Don't mock everything - Integration tests catch issues mocks hide
  • Don't skip async tests - Use pytest-asyncio for proper async testing

Limitations

  • Coverage percentage does not guarantee test quality or correctness
  • Branch coverage may miss complex logical combinations
  • Mocking can mask integration issues between components
  • Large test suites need parallelization for acceptable CI times