pytest-docker-tools

3.1.9 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart defines an `nginx_container` fixture in `conftest.py` that uses the `nginx:alpine` Docker image, mapping port 80. A test then uses this fixture to assert that the Nginx server is reachable and responds with the expected content. This demonstrates defining a container and using it in a test.

# 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}")

view raw JSON →