Install & Compatibility
Where this runs
tested against v1.3.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.230s · 20.2MB
glibcpy 3.10–3.95 runs
installs and imports cleanly · install 1.9s · import 0.214s · 21MB
18MB installed
● package 18MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
Postgresql
✓ from testing.postgresql import Postgresql
PostgresqlFactory
✓ from testing.postgresql import PostgresqlFactory
Used for creating cached PostgreSQL instances to speed up tests.
This quickstart demonstrates launching a temporary PostgreSQL instance using `testing.postgresql.Postgresql` within a context manager. It shows how to connect to the instance using both SQLAlchemy and psycopg2, execute basic queries, and ensures the PostgreSQL server is properly terminated and cleaned up. It also includes an example of `PostgresqlFactory` which caches the initialized database to speed up repeated test runs, optionally with a custom initialization handler.
import testing.postgresql
from sqlalchemy import create_engine
import psycopg2
# Basic usage with a context manager
with testing.postgresql.Postgresql() as postgresql:
# Connect using SQLAlchemy
engine = create_engine(postgresql.url())
with engine.connect() as conn:
result = conn.execute(postgresql.text("SELECT 1")).scalar()
print(f"SQLAlchemy: Connected to {postgresql.url()}, result: {result}")
# Connect using psycopg2 (requires psycopg2 to be installed)
try:
conn_psycopg = psycopg2.connect(**postgresql.dsn())
cursor = conn_psycopg.cursor()
cursor.execute("CREATE TABLE my_table (id SERIAL PRIMARY KEY, name VARCHAR(255))")
cursor.execute("INSERT INTO my_table (name) VALUES (%s)", ('test_name',))
cursor.execute("SELECT name FROM my_table WHERE id = 1")
name_result = cursor.fetchone()[0]
print(f"psycopg2: Inserted and retrieved: {name_result}")
cursor.close()
conn_psycopg.close()
except Exception as e:
print(f"psycopg2 connection/query failed: {e}")
# Example of using PostgresqlFactory for faster tests (e.g., in a test suite setup)
def custom_init_handler(pg_instance):
"""An optional handler to run SQL on a newly initialized DB."""
conn = psycopg2.connect(**pg_instance.dsn())
cursor = conn.cursor()
cursor.execute("CREATE TABLE users (id SERIAL PRIMARY KEY, username VARCHAR(255))")
conn.commit()
conn.close()
print("Factory DB initialized with 'users' table.")
PostgresqlFactory = testing.postgresql.PostgresqlFactory(
cache_initialized_db=True,
on_initialized=custom_init_handler
)
with PostgresqlFactory() as postgresql_cached:
conn = psycopg2.connect(**postgresql_cached.dsn())
cursor = conn.cursor()
cursor.execute("INSERT INTO users (username) VALUES (%s)", ('cached_user',))
conn.commit()
cursor.execute("SELECT username FROM users WHERE id = 1")
user_result = cursor.fetchone()[0]
print(f"Factory usage: Inserted and retrieved: {user_result}")
conn.close()
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'testing.postgresql'
The 'testing-postgresql' package is not installed in your Python environment.
fixInstall the package using pip: `pip install testing-postgresql`
RuntimeError: Could not find 'initdb' or 'postgres' executable.
The `testing-postgresql` library cannot locate the necessary PostgreSQL binaries (`initdb` and `postgres`) in your system's PATH.
fixInstall PostgreSQL on your system and ensure its `bin` directory is added to your system's PATH. Alternatively, specify the `initdb` and `postgres` paths explicitly when instantiating `Postgresql`.
psycopg2.OperationalError: could not connect to server: Connection refused
This error from `psycopg2` indicates that the PostgreSQL server failed to start or connect properly, often a symptom of missing PostgreSQL binaries or issues with the temporary directory setup.
fixEnsure PostgreSQL binaries (`initdb`, `postgres`) are installed and accessible in your system's PATH, or provide their explicit paths to `testing.postgresql.Postgresql`.
ModuleNotFoundError: No module named 'testing_postgresql'
You are trying to import the library using an incorrect module name (underscore instead of dot).
fixChange your import statement from `import testing_postgresql` or `from testing_postgresql import ...` to `import testing.postgresql` or `from testing.postgresql import ...`.
Upgrade
Version history
1.3.0latest on PyPI · released Feb 4, 2016
Audit
Dependencies
PostgreSQL serverrequiredRequires the PostgreSQL server binaries (e.g., `initdb`, `postgres`) to be present in the system's PATH. This is an external, non-Python dependency.
pg8000optionalUsed internally for database connection to create the test database (since v1.2.0).
testing.common.databaserequiredA dependency for utility methods (since v1.3.0).