Collect code coverage from Python applications running inside Docker containers during integration tests. Works alongside pytest-cov to combine container coverage with your local test coverage.
Built for projects using AWS SAM local testing, but works with any Docker-based test workflow.
- Before tests — injects a coverage wrapper,
.coveragerc, andrun.shinto your SAM build directory - During tests — your containerized app runs under
coveragevia the injected wrapper - After tests — extracts
.coverage.*files from containers and runscoverage combineto merge them with local results
pip install pytest-cov-containerRequires Python 3.11+.
Add to your pyproject.toml:
[tool.pytest-cov-container]
image_pattern = "samcli/lambda*"
label = "pytest-cov-container"
[tool.pytest-cov-container.path_mapping]
"src/api" = "/var/task"
[tool.pytest-cov-container.python]
build_dir = ".aws-sam/build/ApiFunction"
entrypoint = "uvicorn app:app --host 0.0.0.0 --port 8080"| Key | Description |
|---|---|
image_pattern |
Glob pattern to match container image tags |
label |
Docker label to filter containers |
path_mapping |
Maps host source paths to container paths (used by coverage combine) |
build_dir |
SAM build output directory where coverage files are injected |
entrypoint |
The command your app runs inside the container |
language |
Language driver to use (default: "python") |
enabled |
Set to false to disable (default: true) |
Run your tests with --cov as usual:
pytest --cov=src/api tests/The plugin activates automatically when:
- pytest-cov is active (
--covflag present) [tool.pytest-cov-container]is configured inpyproject.toml
Disable it for a run with:
pytest --cov=src/api --no-cov-container tests/If you need to collect coverage before containers stop (e.g., in a session-scoped fixture teardown), use the public API:
from pytest_cov_container import collect_container_coverage
@pytest.fixture(scope="session")
def sam_api():
proc = start_sam(...)
yield SAM_URL
collect_container_coverage()
proc.terminate()This sends SIGUSR1 to running containers to flush coverage data, then extracts the files.
Language support is pluggable via entry points. The built-in Python driver handles:
- Writing
.coveragercwithparallel = trueandsigterm = true - Writing
_cov_wrapper.pythat starts coverage, handlesSIGTERM/SIGUSR1, and runs your entrypoint - Writing
run.shto bootstrap the wrapper - Extracting
.coverage.*files from/tmpin containers
To add a driver for another language, register an entry point:
[project.entry-points."pytest_cov_container.drivers"]
node = "my_package.drivers.node:NodeDriver"Drivers must implement the LanguageDriver protocol from pytest_cov_container.models.
# Run tests
hatch test
# Run across all Python versions
hatch test --all
# Format and lint
hatch fmt
# Type check
hatch run types:check
# Security scan
hatch run security:scanpytest-cov-container is distributed under the terms of the MIT license.