Use pytest-docker for integration tests
masterTo use pytest-docker, define your services in a docker-compose.yml file. The plugin will automatically spin up these containers for the duration of your tests.
Example workflow:
- Define services in
docker-compose.yml. - Use
docker_ipanddocker_servicesfixtures in your tests to interact with containers. - Use
docker_services.port_for(service_name, container_port)to resolve the host port for a specific service. - Use
docker_services.wait_until_responsive(...)if you need to ensure a service is ready beyond the default--waitbehavior.
import pytest
import requests
@pytest.fixture(scope="session")
def http_service(docker_ip, docker_services):
# Resolve the host port for the 'httpbin' service on port 80
port = docker_services.port_for("httpbin", 80)
url = f"http://{docker_ip}:{port}"
# Wait for the service to be responsive
docker_services.wait_until_responsive(
timeout=30.0,
pause=0.1,
check=lambda: requests.get(url).status_code == 200
)
return url
def test_status_code(http_service):
response = requests.get(f"{http_service}/status/418")
assert response.status_code == 418