pytest-docker-tools
pytest-docker-tools is a pytest plugin that simplifies writing integration tests with Docker containers. It provides fixtures for managing Docker images and containers, allowing tests to easily spin up and tear down isolated environments. As of its latest version 3.1.9, it's actively maintained with a regular release cadence, primarily driven by new features, bug fixes, and compatibility updates.
Warnings
- breaking The `container_factory` fixture now returns a tuple `(container, logs)` instead of just the container object. Code expecting only the container object will break.
- breaking The parameters `host_ports` and `container_ports` have been removed from `container` and `image` factories. Use the unified `ports` parameter instead.
- breaking The `container_logs` fixture has been renamed to `get_container_logs` for clarity.
- breaking Python 3.7 support has been dropped. The library now requires Python 3.9 or higher.
- gotcha Tests will fail if the Docker daemon is not running or if there are permission issues accessing the Docker socket.
- gotcha Containers may not be immediately 'ready' to serve requests even if they are running. Relying solely on container startup can lead to flaky tests.
Install
-
pip install pytest-docker-tools
Imports
- container
from pytest_docker_tools.factories import container
- image
from pytest_docker_tools.factories import image
Quickstart
# conftest.py
import pytest
from pytest_docker_tools import container
# Define a container using a public Nginx image
# This fixture will be available to all tests.
nginx_container = container(
image="nginx:alpine",
ports={"80/tcp": None}, # Map internal port 80 to a random host port
# Add a readiness check for more robust tests (e.g., via wait_for_response)
# healthcheck_cmd="curl -f http://localhost/ || exit 1",
# healthcheck_interval=1.0,
# healthcheck_timeout=5.0
)
# test_example.py
import requests
def test_nginx_is_reachable(nginx_container):
# The nginx_container fixture provides access to the running container instance
host, port = nginx_container.get_host_port("80/tcp").split(':')
# The host might be '127.0.0.1' or 'localhost' depending on your Docker setup
url = f"http://{host}:{port}"
try:
response = requests.get(url, timeout=5)
assert response.status_code == 200
assert "Welcome to nginx!" in response.text
except requests.exceptions.ConnectionError as e:
pytest.fail(f"Could not connect to Nginx container at {url}: {e}")