Testcontainers Python

4.14.2 · active · verified Sun Apr 05

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

Install

Imports

Quickstart

This quickstart demonstrates how to spin up a PostgreSQL container using `PostgresContainer` as a context manager. It connects to the database using `psycopg` and executes a simple query to verify connectivity. The container is automatically started before the `with` block and torn down afterward, ensuring a clean and isolated environment.

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()

view raw JSON →