testgres
raw JSON → 1.13.7 verified Fri May 01 auth: no python
testgres is a testing utility for PostgreSQL and its extensions, providing a simple API to manage temporary PostgreSQL instances, create databases, execute queries, and test replication. Current version 1.13.7, PyPI release with monthly cadence.
pip install testgres Common errors
error ImportError: No module named 'testgres' ↓
cause testgres is not installed or the virtual environment does not include it.
fix
Run
pip install testgres and ensure the correct virtual environment is activated. error psycopg2.OperationalError: could not connect to server: Connection refused ↓
cause The PostgreSQL node may not have started fully before attempting a connection.
fix
Ensure you call
node.start() and wait for readiness, e.g., node.wait_for_ready(). error FileNotFoundError: [Errno 2] No such file or directory: 'initdb' ↓
cause PostgreSQL binaries (initdb, pg_ctl) are not in the system PATH.
fix
Install PostgreSQL server and ensure its bin directory is in PATH, or set
pg_bindir parameter to the PostgreSQL bin directory. Warnings
gotcha testgres.get_new_node() requires a node name that is unique per test session. Reusing names across tests may cause conflicts. ↓
fix Use unique names (e.g., with test name or random suffix) for each node.
gotcha The temporary PostgreSQL instance uses a port assigned by the OS. If multiple tests run concurrently, port collisions can occur. Use the 'port' parameter to specify a range or fixed port. ↓
fix Specify port range via `port=50432` or use `testgres.get_new_node('node', port=50432)`.
deprecated The `execute()` method returns a list of tuples by default; in older versions it returned a string. If you rely on string output, update your code. ↓
fix Use `node.execute('query', returns='text')` to get string output, or adapt to list-of-tuples.
gotcha testgres nodes do not automatically clean up the data directory if the context manager exits due to an exception. Use explicit cleanup or catch exceptions. ↓
fix Wrap in try/finally or use `with` context manager which handles cleanup on normal exit, but on exception you may need manual `node.stop()` and `node.cleanup()`.
Imports
- testgres
import testgres
Quickstart
import testgres
def test_postgres():
# Start a temporary PostgreSQL instance
with testgres.get_new_node('test_node') as node:
node.init()
node.start()
# Create a database and execute a query
db = node.execute('CREATE DATABASE testdb')
result = node.execute('SELECT 1')
print(result)
# Node is automatically stopped and cleaned up