Skip to main content

Postgresql fixtures and fixture factories for Pytest.

Project description


Latest PyPI version Wheel Status Supported Python Versions License

What is this?

This is a pytest plugin, that enables you to test your code that relies on a running PostgreSQL Database. It allows you to specify fixtures for PostgreSQL process and client.

How to use


Tested on PostgreSQL versions >= 10. See tests for more details.

Install with:

pip install pytest-postgresql

You will also need to install psycopg. See its installation instructions. Note that this plugin requires psycopg version 3. It is possible to simultaneously install version 3 and version 2 for libraries that require the latter (see those instructions).

Plugin contains three fixtures:

  • postgresql - it’s a client fixture that has functional scope. After each test it ends all leftover connections, and drops test database from PostgreSQL ensuring repeatability. This fixture returns already connected psycopg connection.
  • postgresql_proc - session scoped fixture, that starts PostgreSQL instance at it’s first use and stops at the end of the tests.
  • postgresql_noproc - a noprocess fixture, that’s connecting to already running postgresql instance. For example on dockerized test environments, or CI providing postgresql services

Simply include one of these fixtures into your tests fixture list.

You can also create additional postgresql client and process fixtures if you’d need to:

from pytest_postgresql import factories

postgresql_my_proc = factories.postgresql_proc(
    port=None, unixsocketdir='/var/run')
postgresql_my = factories.postgresql('postgresql_my_proc')


Each PostgreSQL process fixture can be configured in a different way than the others through the fixture factory arguments.

Sample test

def test_example_postgres(postgresql):
    """Check main postgresql fixture."""
    cur = postgresql.cursor()
    cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")

If you want the database fixture to be automatically populated with your schema there are two ways:

  1. client fixture specific
  2. process fixture specific

Both are accepting same set of possible loaders:

  • sql file path
  • loading function import path (string)
  • actual loading function

That function will receive host, port, user, dbname and password kwargs and will have to perform connection to the database inside. However, you’ll be able to run SQL files or even trigger programmatically database migrations you have.

Client specific loads the database each test

postgresql_my_with_schema = factories.postgresql(
    load=["schemafile.sql", "otherschema.sql", "", "", load_this]


This way, the database will still be dropped each time.

The process fixture performs the load once per test session, and loads the data into the template database. Client fixture then creates test database out of the template database each test, which significantly speeds up the tests.

postgresql_my_proc = factories.postgresql_proc(
    load=["schemafile.sql", "otherschema.sql", "", "", load_this]
pytest --postgresql-populate-template=path/to/file.sql

The loading_function from example will receive , and have to commit that. Connecting to already existing postgresql database ————————————————–

Some projects are using already running postgresql servers (ie on docker instances). In order to connect to them, one would be using the postgresql_noproc fixture.

postgresql_external = factories.postgresql('postgresql_noproc')

By default the postgresql_noproc fixture would connect to postgresql instance using 5432 port. Standard configuration options apply to it.

These are the configuration options that are working on all levels with the postgresql_noproc fixture:


You can define your settings in three ways, it’s fixture factory argument, command line option and pytest.ini configuration option. You can pick which you prefer, but remember that these settings are handled in the following order:

  • Fixture factory argument
  • Command line option
  • Configuration option in your pytest.ini file
Configuration options
PostgreSQL option Fixture factory argument Command line option pytest.ini option Noop process fixture Default
Path to executable executable –postgresql-exec postgresql_exec
host host –postgresql-host postgresql_host yes
port port –postgresql-port postgresql_port yes (5432) random
postgresql user user –postgresql-user postgresql_user yes postgres
password password –postgresql-password postgresql_password yes  
Starting parameters (extra pg_ctl arguments) startparams –postgresql-startparams postgresql_startparams
Postgres exe extra arguments (passed via pg_ctl’s -o argument) postgres_options –postgresql-postgres-options postgresql_postgres_options
Log filename’s prefix logsprefix –postgresql-logsprefix postgresql_logsprefix
Location for unixsockets unixsocket –postgresql-unixsocketdir postgresql_unixsocketdir
Database name dbname –postgresql-dbname postgresql_dbname yes, however with xdist an index is being added to name, resulting in test0, test1 for each worker. test
Default Schema either in sql files or import path to function that will load it (list of values for each) load –postgresql-load postgresql_load yes  
PostgreSQL connection options options –postgresql-options postgresql_options yes  

Example usage:

  • pass it as an argument in your own fixture

    postgresql_proc = factories.postgresql_proc(
  • use --postgresql-port command line option when you run your tests

    py.test tests --postgresql-port=8888
  • specify your port as postgresql_port in your pytest.ini file.

    To do so, put a line like the following under the [pytest] section of your pytest.ini:

    postgresql_port = 8888


Populating database for tests

With SQLAlchemy

This example shows how to populate database and create an SQLAlchemy’s ORM connection:

Sample below is simplified session fixture from pyramid_fullauth tests:

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.pool import NullPool
from zope.sqlalchemy import register

def db_session(postgresql):
    """Session for SQLAlchemy."""
    from pyramid_fullauth.models import Base

    connection = f'postgresql+psycopg2://{}:@{}:{}/{}'

    engine = create_engine(connection, echo=False, poolclass=NullPool)
    pyramid_basemodel.Session = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
        engine, pyramid_basemodel.Session, should_create=True, should_drop=True)

    yield pyramid_basemodel.Session


def user(db_session):
    """Test user fixture."""
    from pyramid_fullauth.models import User
    from import DEFAULT_USER

    new_user = User(**DEFAULT_USER)
    return new_user

def test_remove_last_admin(db_session, user):
    Sample test checks internal login, but shows usage in tests with SQLAlchemy
    user = db_session.merge(user)
    user.is_admin = True
    user = db_session.merge(user)

    with pytest.raises(AttributeError):
        user.is_admin = False


See the original code at pyramid_fullauth’s conftest file. Depending on your needs, that in between code can fire alembic migrations in case of sqlalchemy stack or any other code

Maintaining database state outside of the fixtures

It is possible and appears it’s used in other libraries for tests, to maintain database state with the use of the pytest-postgresql database managing functionality:

For this import DatabaseJanitor and use its init and drop methods:

import pytest
from pytest_postgresql.janitor import DatabaseJanitor

def database(postgresql_proc):
    # variable definition

    janitor = DatabaseJanitor(
    yield psycopg2.connect(

or use it as a context manager:

import pytest
from pytest_postgresql.janitor import DatabaseJanitor

def database(postgresql_proc):
    # variable definition

    with DatabaseJanitor(
        yield psycopg2.connect(


DatabaseJanitor manages the state of the database, but you’ll have to create connection to use in test code yourself.

You can optionally pass in a recognized postgresql ISOLATION_LEVEL for additional control.


See DatabaseJanitor usage in python’s warehouse test code

Connecting to Postgresql (in a docker)

To connect to a docker run postgresql and run test on it, use noproc fixtures.

docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres

This will start postgresql in a docker container, however using a postgresql installed locally is not much different.

In tests, make sure that all your tests are using postgresql_noproc fixture like that:

from pytest_postgresql import factories

postgresql_in_docker = factories.postgresql_noproc()
postgresql = factories.postgresql("postgresql_in_docker", dbname="test")

def test_postgres_docker(postgresql):
    """Run test."""
    cur = postgresql.cursor()
    cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")

And run tests:

pytest --postgresql-host= --postgresql-password=mysecretpassword

Using a common database initialisation between tests

If you’ve got several tests that require common initialisation, you need to define a load and pass it to your custom postgresql process fixture:

import pytest_postgresql.factories
def load_database(**kwargs):
    db_connection: connection = psycopg2.connect(**kwargs)
    with db_connection.cursor() as cur:
        cur.execute("CREATE TABLE stories (id serial PRIMARY KEY, name varchar);")
            "INSERT INTO stories (name) VALUES"
            "('Silmarillion'), ('Star Wars'), ('The Expanse'), ('Battlestar Galactica')"

postgresql_proc = factories.postgresql_proc(

postgresql = factories.postgresql(

You can also define your own database name by passing same dbname value to both factories.

The way this will work is that the process fixture will populate template database, which in turn will be used automatically by client fixture to create a test database from scratch. Fast, clean and no dangling transactions, that could be accidentally rolled back.

Same approach will work with noproces fixture, while connecting to already running postgresql instance whether it’ll be on a docker machine or running remotely or locally.




  • Error message typo fix
  • Docker documentation example typo fixes
  • Have setuptools required as package dependency. pkg_resources.parse_version is used in code but setuptools was only used as build requirements



  • Import FixtureRequest from pytest, not private _pytest. Require at least pytest 6.2
  • Replace tmpdir_factory with tmp_path_factory



  • Upgrade to psycopg 3.
  • Xdist running test connecting to already existing postgresql, will now create separate databases for each worker.

Backward Incompatibilities

  • Use psycopg 3 and return its connections in client fixtures.
  • Drop support for postgresql 9.6
  • client fixture will no longer utilize configuration’s load param
  • client fixture will no longer utilize configuration’s dbanme parameter


  • Add Postgresql 14 to the CI



  • Database can be created by DatabaseJanitor or the client fixture when an isolation level is specified.



  • rely on get_port functionality delivered by port_for



  • Added type annotations and compatibitlity with PEP 561


  • pre-commit configuration



  • Changed UPDATE pg_database SET to ALTER. System tables should not be updated.



  • Fixed DatabaseJanitor port type hint to int from str
  • Changed retry definition to not fail if psycopg2 is not installed. Now the default is Exception.


  • Support python 3.7 and up



  • Ability to create template database once for the process fixture and re-recreate a clean database out of it every test. Not only it does provide some common db initialisation between tests but also can speed up tests significantly, especially if the initialisation has lots of operations to perform.
  • DatabaseJanitor can now define a connection_timeout parameter. How long will it try to connect to database before raising a TimeoutError
  • Updated supported python versions
  • Unified temporary directory handling in fixture. Settled on tmpdir_factory.
  • Fully moved to the Github Actions as CI/CD pipeline


  • Deprecated support for logs_prefix process fixture factory argument, –postgresql-logsprefix pytest command line option and postgresql_logsprefix ini configuration option. tmpdir_factory now builds pretty unique temporary directory structure.

Backward Incompatibilities

  • Dropped support for postgresql 9.5 and down
  • Removed init_postgresql_database and drop_postgresql_database functions. They were long deprecated and their role perfectly covered by DatabaseJanitor class.
  • pytest_postgresql.factories.get_config was moved to pytest_postgresql.config.get_config
  • all db_name keywords and attributes were renamed to dbname
  • postgresql_nooproc fixture was renamed to postgresql_noproc


  • Use postgresql_logsprefix and –postgresql-logsprefix again. They were stopped being used somewhere along the way.
  • Sometimes pytest-postrgesql would fail to start postgresql with “FATAL: the database system is starting up” message. It’s not really a fatal error, but a message indicating that the process still starts. Now pytest-postgresql will wait properly in this cases.


  • [bugfix] To not fail loading code if no postgresql version is installed. Fallback for janitor and process fixture only, if called upon.


  • [enhancement] add ability to pass options to pg_ctl’s -o flag to send arguments to the underlying postgres executable Use postgres_options as fixture argument, –postgresql-postgres-options as pytest starting option or postgresql_postgres_options as pytest.ini configuration option


  • [enhancement] Add ability to set up isolation level for fixture and janitor


  • [fix] Status checks for running postgres depend on pg_ctl status code, not on pg_ctl log language. Fixes starting on systems without C locale. Thanks @Martin Meyries.


  • [fix] Added LC_* env vars to running initdb and other utilities. Now all tools and server are using same, C locale


  • [feature] Ability to define default schema to initialize database with
  • [docs] Added more examples to readme on how to use the plugin


  • [enhancement] extract NoopExecutor into it’s own submodule
  • [bugfix] Ignore occasional ProcessFinishedWithError error on executor exit.
  • [bugfix] Fixed setting custom password for process fixture
  • [bugfix] Fix version detection, to allow for two-digit minor version part


  • [feature] Drop support for python 3.5
  • [enhancement] require at least mirakuru 2.3.0 (executor’s stop method parameter’s change)
  • [bug] pass password to DatabaseJanitor in client’s factory


  • [feature] Allow to set password for postgresql. Use it throughout the flow.
  • [bugfix] Default Janitor’s connections to postgres database. When using custom users, postgres attempts to use user’s database and it might not exist.
  • [bugfix] NoopExecutor connects to read version by context manager to properly handle cases where it can’t connect to the server.


  • [bugfix] Fix drop_postgresql_database to actually use DatabaseJanitor.drop instead of an init


  • [feature] ability to properly connect to already existing postgresql server using postgresql_nooproc fixture.


  • [enhancement] Gather helper functions maintaining postgresql database in DatabaseJanitor class.
  • [deprecate] Deprecate init_postgresql_database in favour of DatabaseJanitor.init
  • [deprecate] Deprecate drop_postgresql_database in favour of DatabaseJanitor.drop


  • [feature] Drop support for python 2.7. From now on, only support python 3.5 and up
  • [feature] Ability to configure database name through plugin options
  • [enhancement] Use tmpdir_factory. Drop logsdir parameter
  • [ehnancement] Support only Postgresql 9.0 and up
  • [bugfix] Always start postgresql with LC_ALL, LC_TYPE and LANG set to C.UTF-8. It makes postgresql start in english.


  • [bugfix] Allow creating test database with hyphens


  • [enhancements] Ability to configure additional options for postgresql process and connection
  • [bugfix] - removed hard dependency on psycopg2, allowing any of its alternative packages, like psycopg2-binary, to be used.
  • [maintenance] Drop support for python 3.4 and use 3.7 instead


  • [bugfix] properly detect if executor running and clean after executor is being stopped


    Previously if a test failed, there was a possibility of the executor being removed when python was closing, causing it to print ignored errors on already unloaded modules.


  • [enhancement] use executor’s context manager to start/stop postrgesql server in a fixture


  • [bugfix] version regexp to correctly catch postgresql 10


  • [enhancement] explicitly turn off logging_collector


  • [feature] pypy compatibility


  • [bugfix] - disallow connection to database before it gets dropped.


    Otherwise it caused random test subprocess to connect again and this the drop was unsuccessful which resulted in many more test fails on setup.

  • [cleanup] - removed dependency


  • [bugfix] - Fixing the default pg_ctl path creation


  • [feature] - migrate usage of getfuncargvalue to getfixturevalue. require at least pytest 3.0.0


  • create command line and pytest.ini configuration options for postgresql starting parameters
  • create command line and pytest.ini configuration options for postgresql username
  • make the port random by default
  • create command line and pytest.ini configuration options for executable
  • create command line and pytest.ini configuration options for host
  • create command line and pytest.ini configuration options for port
  • Extracted code from pytest-dbfixtures

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pytest-postgresql-4.1.1.tar.gz (45.2 kB view hashes)

Uploaded source

Built Distribution

pytest_postgresql-4.1.1-py3-none-any.whl (41.9 kB view hashes)

Uploaded py3

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Huawei Huawei PSF Sponsor Microsoft Microsoft PSF Sponsor NVIDIA NVIDIA PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page