How to Run an Integration Test with Docker Compose Mock in Python

Run a Python integration test against a docker-compose environment, using mocks to simulate service health and business logic responses.

Medium Python 3.9+ Aug 9, 2026 Testing & modern typing 15 views 0 copies

Python code

43 lines
Python 3.9+
import subprocess
import json
from typing import Dict

def run_integration_test() -> Dict[str, str]:
    """
    Simulates an integration test against a docker-compose environment
    using a mock service that returns canned responses.
    """
    # Mock docker-compose environment check
    env_ready = subprocess.run(
        ["docker", "compose", "config", "--quiet"],
        capture_output=True,
        text=True
    )
    
    if env_ready.returncode != 0:
        return {"status": "failed", "detail": "docker-compose config invalid"}
    
    # Mock service health check (simulates actual HTTP call)
    mock_health = {"status": "healthy", "service": "api", "port": 8080}
    
    # Mock business logic test
    mock_response = {
        "test": "user_creation",
        "input": {"name": "Alice", "email": "alice@example.com"},
        "output": {"id": "12345", "created": True}
    }
    
    # Simulate integration assertions
    assert mock_health["status"] == "healthy", "Service unhealthy"
    assert mock_response["output"]["created"] == True, "Creation failed"
    
    return {
        "status": "passed",
        "environment": "docker-compose:mock",
        "test_count": 3,
        "services_checked": ["api", "db", "cache"]
    }

if __name__ == "__main__":
    result = run_integration_test()
    print(json.dumps(result, indent=2))

Output

stdout
{
  "status": "passed",
  "environment": "docker-compose:mock",
  "test_count": 3,
  "services_checked": ["api", "db", "cache"]
}

How it works

The subprocess.run call validates that the docker-compose file is correct before any test logic runs. The health check and business logic responses are mocked as dictionaries, simulating what a real HTTP call would return. Assertions verify that the service is healthy and the creation operation succeeded, mimicking integration test conditions. The script outputs a JSON summary that is easy to parse in CI pipelines or logs.

Common mistakes

  • Forgetting to check the returncode from docker-compose config
  • Using real service calls instead of mocks, making tests slow and flaky
  • Hardcoding test data instead of parametrizing edge cases
  • Not cleaning up docker-compose resources after tests run

Variations

  1. Use pytest with fixtures to mock HTTP responses
  2. Call `docker compose up -d` before tests and `down` after with finally
  3. Integrate with Testcontainers to spin up real Docker containers

Real-world use cases

  • Running CI integration tests that validate docker-compose services before deploying.
  • Simulating external API responses in a microservice test suite.
  • Automating end-to-end checks for a multi-container application stack.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Testing & modern typing

Related tutorials and quizzes for this topic.