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
PGUSERorpostgresif unset. - password (str) – the database password to connect with. This
defaults to
None. - host (str) – the database server to connect to. This defaults
to
PGHOSTorlocalhostif omitted. - port (str) – port number that the database server is listening
on. This defaults to
PGPORTor5432if 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_DATABASEclass attribute and the template database can be changed by passing it to thecreate()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 theconnection_parametersproperty.-
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
template0if omitted. - options – additional parameters to use in the
CREATE DATABASEcommand.
- template (str) – the name of the database to use as a
template for the new database. This defaults to
-
drop()¶ Drop the temporary database if it was created.
-
set_environment()¶ Export Postgres environment variables for the database.
This exports the
PGUSER,PGHOST,PGPORT, andPGDATABASEenvironment variables set to matchconnection_parameters.
- user (str) – the database user to connect with. This defaults
to