Registry / testing / testing-postgresql

testing-postgresql

JSON →
library1.3.0pypypi✓ verified 25d ago

testing.postgresql is a Python library that automatically sets up a PostgreSQL instance in a temporary directory for testing purposes and destroys it afterward. The current version is 1.3.0. Its release cadence appears to be slow, with the last major update in 2016.

pip install testing.postgresql
INSTALL
IMPORT
SIG · TESTING-POSTGRESQL
T
testing-postgresql
testingpythonv1.3.0
Install
1.9s avg
Import
222ms
Disk
18MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
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
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.230s · 20.2MB
glibc
py 3.103.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()
Debug
Known issues
breakingThis library requires a pre-installed PostgreSQL server in your system's PATH environment variable. It uses binaries like `initdb` and `postgres` directly. Without these, the library cannot function.
fix
Ensure that your system has PostgreSQL installed and that its binary directory (e.g., `/usr/bin/`, `/usr/local/bin/`) is included in your PATH environment variable.
affects: All versions
gotchaThe `testing-postgresql` project appears to be minimally maintained, with the last PyPI release in 2016 and limited GitHub activity since 2017. Users seeking active development, support for newer PostgreSQL features, or compatibility with recent Python versions might find it lacking.
fix
Evaluate alternatives like `pytest-postgresql` for more actively developed solutions, especially if you require modern features, community support, or encounter compatibility issues with newer Python or PostgreSQL versions.
affects: 1.x
gotchaBy default, `testing.postgresql.Postgresql` invokes `initdb` on every instantiation. This can be a slow operation, especially when creating many test databases for individual test cases, leading to increased test suite execution time.
fix
For faster repeated tests, use `testing.postgresql.PostgresqlFactory` with `cache_initialized_db=True`. This initializes the database only once and copies it for subsequent instances. You can also use the `copy_data_from` option to provide a pre-existing data directory.
affects: All versions
gotchaFailure to explicitly call `.stop()` on a `Postgresql` instance or neglecting to use it within a `with` statement (context manager) can leave lingering PostgreSQL processes and temporary data directories, consuming system resources and potentially causing conflicts.
fix
Always use `testing.postgresql.Postgresql()` within a `with` statement to ensure proper cleanup. If manual management is necessary (e.g., in `setUp`/`tearDown` methods of `unittest.TestCase`), ensure `postgresql_instance.stop()` is called in `tearDown`.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'testing.postgresql'
The 'testing-postgresql' package is not installed in your Python environment.
fix
Install 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.
fix
Install 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.
fix
Ensure 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).
fix
Change 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).
Agent activity
23 hits · last 30 days
node
18
Meta
1
OpenAI (training)
1
Resources
testing-postgresql — pip install testing-postgresql · libregistry