Testcontainers Python
Testcontainers Python is an open-source library that provides lightweight, disposable instances of common databases, message brokers, web browsers, or any service that can run in a Docker container, for development and testing. It simplifies integration testing by provisioning on-demand containers. The library is actively maintained, with frequent releases (typically monthly or bi-monthly), and is currently at version 4.14.2.
Warnings
- breaking With version 4.0.0, the `testcontainers-*` individual PyPI packages (e.g., `testcontainers-postgres`) were deprecated. Users must now install the main `testcontainers` package and specify required modules as 'extras' (e.g., `pip install 'testcontainers[postgres]'`).
- gotcha Testcontainers requires a running Docker daemon accessible by the Python process. Common issues include Docker not running, insufficient user permissions, or misconfigured DOCKER_HOST environment variables, especially in CI/CD environments (e.g., Docker-in-Docker setups).
- gotcha Using ':latest' Docker image tags can lead to flaky or unpredictable tests, as the 'latest' image can change without notice and introduce breaking changes. It's a best practice to pin specific image versions (e.g., 'postgres:16').
- deprecated Older wait strategies, particularly those using decorators for `wait_for_container_ready` or custom, less explicit waiting logic, are being superseded. Newer versions of Testcontainers encourage or internally use explicit `WaitStrategy` classes and `ExecWaitStrategy`.
- gotcha While the `core` package adheres to Semantic Versioning, community modules (e.g., `testcontainers[mysql]`) are supported on a 'best-effort' basis. Breaking changes may occur in these modules with minor version updates of the main `testcontainers` package.
- gotcha Though Testcontainers uses Ryuk for automatic container cleanup, it's good practice to ensure containers are explicitly stopped and removed, especially in complex `pytest` fixtures without `yield` or for custom `DockerContainer` instances not using context managers, to prevent resource leakage.
Install
-
pip install testcontainers -
pip install 'testcontainers[postgres]'
Imports
- DockerContainer
from testcontainers.core.container import DockerContainer
- PostgresContainer
from testcontainers.postgres import PostgresContainer
- DockerCompose
from testcontainers.compose import DockerCompose
- KafkaContainer
from testcontainers.kafka import KafkaContainer
Quickstart
import os
from testcontainers.postgres import PostgresContainer
import psycopg
# Example of using PostgresContainer in a test context
def test_postgres_container_starts():
# Use a specific image version for reproducibility
# The database driver (psycopg) is expected to be installed in your environment
with PostgresContainer("postgres:16") as postgres:
connection_url = postgres.get_connection_url()
print(f"PostgreSQL container started, connection URL: {connection_url}")
# Connect to the database
with psycopg.connect(connection_url) as conn:
with conn.cursor() as cur:
cur.execute("SELECT 1")
result = cur.fetchone()
assert result == (1,)
print("Successfully connected and executed a query.")
if __name__ == "__main__":
# Ensure Docker is running before executing
# In a real test suite, this would typically be run by pytest
test_postgres_container_starts()