pytest-postgresql

8.0.0 · active · verified Thu Apr 09

pytest-postgresql is a pytest plugin that enables you to test code relying on a running PostgreSQL database. It provides fixtures for managing both the PostgreSQL process and client connections, automatically cleaning up temporary databases after tests. The current version is 8.0.0, and it is actively maintained.

Warnings

Install

Imports

Quickstart

Demonstrates a basic test using the `postgresql` fixture to interact with a temporary PostgreSQL database. The fixture provides a `psycopg.Connection` object, automatically handling database setup and teardown for isolation.

import pytest
from psycopg import Connection

def test_example(postgresql: Connection):
    """Check main postgresql fixture."""
    with postgresql.cursor() as cur:
        cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")
    postgresql.commit()

    # Optional: Verify data insertion
    with postgresql.cursor() as cur:
        cur.execute("INSERT INTO test (num, data) VALUES (1, 'test_data');")
    postgresql.commit()

    with postgresql.cursor() as cur:
        cur.execute("SELECT num, data FROM test WHERE id = 1;")
        result = cur.fetchone()
        assert result == (1, 'test_data')

view raw JSON →