pytest-docker

3.2.5 · active · verified Sat Apr 11

pytest-docker provides simple pytest fixtures for testing applications that rely on Docker or Docker Compose services. It simplifies the setup and teardown of Docker containers or multi-container applications (defined via `docker-compose.yml`) for integration tests, automatically managing their lifecycle. The current version is 3.2.5, and it maintains an active release cadence with frequent updates.

Warnings

Install

Imports

Quickstart

To use `pytest-docker`, define your Docker Compose services in a `docker-compose.yml` file and then use the `docker_compose` fixture in your tests. You must define a `docker_compose_file` fixture to point to your compose file. This example uses a Redis service: 1. **Create `docker-compose.yml`** (e.g., in the same directory as your test file): ```yaml services: redis: image: redis:latest ports: - "6379:6379" healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 1s timeout: 3s retries: 5 ``` 2. **Create `test_redis.py`** with the code above. 3. **Run tests** from your terminal: `pytest`

import pytest
import redis
import time
from pathlib import Path

# This fixture tells pytest-docker where to find docker-compose.yml.
# Place this in your conftest.py or directly in your test file.
@pytest.fixture(scope="session")
def docker_compose_file():
    # Assumes docker-compose.yml is in the same directory as this test file.
    return str(Path(__file__).parent / "docker-compose.yml")

def test_redis_connection(docker_compose):
    # The 'docker_compose' fixture automatically starts services from docker-compose.yml
    # Get the host and exposed port for the 'redis' service
    host, port = docker_compose.get_service_host_port("redis", 6379)

    # Poll until the Redis service is ready to accept connections
    _redis_client = None
    for _ in range(30): # Try for up to 30 seconds
        try:
            _redis_client = redis.Redis(host=host, port=port, decode_responses=True)
            _redis_client.ping() # Check connection
            break
        except redis.exceptions.ConnectionError:
            time.sleep(1)
    else:
        pytest.fail("Redis service not ready after 30 seconds")

    assert _redis_client is not None
    _redis_client.set("mykey", "myvalue")
    assert _redis_client.get("mykey") == "myvalue"
    _redis_client.close()

view raw JSON →