Postgres Helpers

class test_helpers.postgres.TemporaryDatabase(**kwargs)

Creates a temporary database that is destroyed automatically.

Parameters:
  • user (str) – the database user to connect with. This defaults to PGUSER or postgres if unset.
  • password (str) – the database password to connect with. This defaults to None.
  • host (str) – the database server to connect to. This defaults to PGHOST or localhost if omitted.
  • port (str) – port number that the database server is listening on. This defaults to PGPORT or 5432 if omitted.
  • kwargs – additional psycopg2 connection parameters

Instances of this class will create an isolated database from a template and ensure that it is destroyed when the test process exits. Under the hood it issues DDL commands over a psycopg2 connection to manage the database and registers a single cleanup function with atexit.register().

Usage Example

from test_helpers import postgres

_testing_db = postgres.TemporaryDatabase()

def setup_module():
    _testing_db.create()
    _testing_db.set_environment()

    # from this point on, the standard Postgres environment
    # variables PGDATABASE, PGHOST, PGPORT, and PGUSER are
    # set to connect to the temporary database

By default, this will connect to postgres using the postgres database and clone the template0 database. The starting database is controlled by the STARTING_DATABASE class attribute and the template database can be changed by passing it to the create() method.

Once a temporary database has been created, you can either call the set_environment() method to export the standard set of Postgres environment variables (e.g., PGHOST) or get a copy of the connection parameters from the connection_parameters property.

STARTING_DATABASE = 'postgres'

Database to connect to when cloning the template.

connection_parameters

Keyword parameters for psycopg2.connect().

create(template='template0', **options)

Create the temporary database if it does not exist.

Parameters:
  • template (str) – the name of the database to use as a template for the new database. This defaults to template0 if omitted.
  • options – additional parameters to use in the CREATE DATABASE command.
drop()

Drop the temporary database if it was created.

set_environment()

Export Postgres environment variables for the database.

This exports the PGUSER, PGHOST, PGPORT, and PGDATABASE environment variables set to match connection_parameters.