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.
Python code
43 linesimport 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
{
"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
- Use pytest with fixtures to mock HTTP responses
- Call `docker compose up -d` before tests and `down` after with finally
- 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
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.