Testcontainers PostgreSQL Module
raw JSON → 0.0.1rc1 verified Fri May 01 auth: no python
PostgreSQL component of testcontainers-python. Provides a lightweight, disposable PostgreSQL container for integration testing. Current version: 0.0.1rc1, requires Python >=3.7. Release cadence: follows the main testcontainers-python library (major releases every few months).
pip install testcontainers-postgres Common errors
error ModuleNotFoundError: No module named 'testcontainers' ↓
cause The base package `testcontainers-core` is not installed; testcontainers-postgres only adds the PostgreSQL module.
fix
Install the main package with
pip install testcontainers or ensure testcontainers-core is installed. error ImportError: cannot import name 'PostgresContainer' from 'testcontainers' ↓
cause The submodule is not imported correctly; the import path uses dots, not underscores.
fix
Use
from testcontainers.postgres import PostgresContainer. error AttributeError: 'PostgresContainer' object has no attribute 'get_connection_url' ↓
cause Method name changed in an older version (pre-4.0.0); the correct method is `get_connection_url()`.
fix
Upgrade to latest version and use
get_connection_url() instead of get_container_host_ip() or get_exposed_port(). Warnings
deprecated The `PostgresContainer` constructor argument `db_name` has been renamed to `dbname` in testcontainers-python v4.14.0+. ↓
fix Use keyword argument `dbname` instead of `db_name`.
breaking The `PostgresContainer` no longer supports the `docker_image` parameter; use the first positional argument (image) instead. ↓
fix Pass the image as a string directly: `PostgresContainer('postgres:16')` instead of `PostgresContainer(docker_image='postgres:16')`.
gotcha `PostgresContainer` silently falls back to default postgres:latest if the provided image tag is not available; this can lead to unexpected version mismatches. ↓
fix Always specify a full image tag (e.g., 'postgres:16-alpine') to ensure reproducibility.
Imports
- PostgresContainer wrong
from testcontainers_postgres import PostgresContainercorrectfrom testcontainers.postgres import PostgresContainer
Quickstart
from testcontainers.postgres import PostgresContainer
with PostgresContainer("postgres:16") as postgres:
connection_url = postgres.get_connection_url()
print(f"Connection URL: {connection_url}")
# Use with psycopg2 or SQLAlchemy
import psycopg2
conn = psycopg2.connect(connection_url)
cur = conn.cursor()
cur.execute("SELECT 1;")
print(cur.fetchone())