Embedded PostgreSQL#
Runs a real PostgreSQL server from local binaries, without Docker or Podman.
Overview#
pytest_databases.embedded.postgres runs initdb and postgres in a temporary directory and serves the
cluster on a loopback TCP port. The cluster uses trust authentication (password defaults to "" and is
reflected in dsn and connection_config whenever non-empty) and has Unix-domain sockets
disabled, plus non-durable settings (fsync = off, synchronous_commit = off, full_page_writes = off) that
suit throwaway test data. The fixture runs its own SQL over a stdlib PostgreSQL v3 wire client (which supports trust, cleartext, MD5, and
SCRAM-SHA-256 authentication and also powers postgres_external_service in PostgreSQL), so neither psql
nor a Python driver is required. EmbeddedPostgresService satisfies PostgresServiceProtocol
alongside PostgresService and ExternalPostgresService. Any PostgreSQL client (psycopg, asyncpg, SQLAlchemy, SQLSpec) connects with
dsn or connection_config.
Installation#
Install the embedded-postgres extra (see Installation for other installers). It pulls
in pgembed on Python 3.12+ and pgserver on Python 3.11, which ship the server binaries:
pip install "pytest-databases[embedded-postgres]"
Without the extra, the binaries are looked up in this order: the embedded_postgres_bin_dir fixture, the
PG_BIN_DIR environment variable, the pgembed / pgserver packages, the PATH, pg_config --bindir,
and common install directories (/usr/lib/postgresql/*/bin, Homebrew postgresql@*, /usr/pgsql-*). Only
initdb and postgres are required; pg_ctl is used for shutdown when present.
Usage Example#
import psycopg
from pytest_databases.embedded.postgres import EmbeddedPostgresService
pytest_plugins = ["pytest_databases.embedded.postgres"]
def test_embedded_postgres(embedded_postgres_service: EmbeddedPostgresService) -> None:
with psycopg.connect(embedded_postgres_service.dsn) as conn:
row = conn.execute("SELECT 1").fetchone()
assert row is not None and row[0] == 1
def test_exec_sql(embedded_postgres_service: EmbeddedPostgresService) -> None:
exit_code, output = embedded_postgres_service.exec_sql("SELECT current_database()", tuples_only=True)
assert exit_code == 0
assert output.strip().decode() == embedded_postgres_service.database
exec_sql(sql, *, database=None, tuples_only=False, timeout=30.0) returns (exit_code, output) as
tuple[int, bytes], matching exec_sql(): one line per row
with | between columns, exit code 1 for an SQL error, and 2 for a connection failure.
Portable PostgreSQL Backend Switching#
Use the postgres_any_service fixture typed as PostgresServiceProtocol to write suites
that target either containerized PostgreSQL or local embedded binaries:
from pytest_databases import PostgresServiceProtocol
pytest_plugins = ["pytest_databases.embedded.postgres"]
def test_portable_postgres(postgres_any_service: PostgresServiceProtocol) -> None:
exit_code, output = postgres_any_service.exec_sql("SELECT 1", tuples_only=True, timeout=30.0)
assert exit_code == 0
assert output.strip() == b"1"
Switch backends with --postgres-backend=embedded, ini postgres_backend = "embedded", or
PYTEST_DATABASES_POSTGRES_BACKEND=embedded (precedence CLI -> ini -> env -> "docker"). Suites registering
only pytest_databases.docker.postgres still resolve embedded lazily via resolve_postgres_binaries() (honoring
PG_BIN_DIR) without probing Docker or Podman.
Isolation and Template Databases#
xdist_embedded_postgres_isolation_level controls how databases are created:
"template"(the default): a template database is built once fromembedded_postgres_template_setupand the service database is cloned from it. Underpytest-xdistevery worker shares one cluster and gets its own clone (pytest_databases_<worker>); without xdist the single clone ispytest_databases."database": as above, but each database starts empty."server": each worker starts its own cluster.
The shared cluster is stopped and its data directory removed when the last worker finishes; worker databases are dropped at teardown.
import pytest
from pytest_databases.embedded.postgres import EmbeddedPostgresService
pytest_plugins = ["pytest_databases.embedded.postgres"]
@pytest.fixture(scope="session")
def embedded_postgres_template_setup() -> list[str]:
return [
"CREATE TABLE users (id serial PRIMARY KEY, username text NOT NULL)",
"INSERT INTO users (username) VALUES ('alice')",
]
def test_worker_database(embedded_postgres_service: EmbeddedPostgresService) -> None:
exit_code, output = embedded_postgres_service.exec_sql("SELECT count(*) FROM users")
assert exit_code == 0
assert output == b"1"
The setup can also be a list of pathlib.Path objects pointing at .sql files, or a callable that receives the
staging service:
from collections.abc import Callable
import pytest
from pytest_databases.embedded.postgres import EmbeddedPostgresService
@pytest.fixture(scope="session")
def embedded_postgres_template_setup() -> Callable[[EmbeddedPostgresService], None]:
def setup(service: EmbeddedPostgresService) -> None:
exit_code, output = service.exec_sql("CREATE TABLE users (id serial PRIMARY KEY)")
assert exit_code == 0, output
return setup
SQL text and file contents are hashed into the template name, so a changed schema builds a new template. A callable
cannot be hashed; return its inputs from embedded_postgres_template_fingerprint_sources. The template helpers
(ensure_template(), create_worker_database_from_template(), clone_template_database(),
drop_database_force(), sweep_worker_databases()) work as described in PostgreSQL.
Available Fixtures#
embedded_postgres_service: AnEmbeddedPostgresServicepointed at this process’s database (withpassword=""default undertrustauth).postgres_any_service: Cross-backend session fixture yielding aPostgresServiceProtocolinstance (delegating toembedded_postgres_servicewhen--postgres-backend=embedded).embedded_postgres_user: Superuser name (defaults to"postgres").embedded_postgres_database: Base name of the yielded database (defaults to"pytest_databases";pytest_databases_<worker>under xdist).embedded_postgres_port: Server port (defaults to0, a free port).embedded_postgres_bin_dir: Directory holdinginitdb/postgres(defaults toNone, which searches the locations listed above).xdist_embedded_postgres_isolation_level:"template"(default),"database", or"server".embedded_postgres_template_name: Template name prefix (Nonemeans"pytest_databases_template").embedded_postgres_template_setup: SQL statements,.sqlpaths, or a callable that builds the template.embedded_postgres_template_fingerprint_sources: Extra strings, bytes, files, or directories hashed into the template name.embedded_postgres_template_lock_dir: Directory for the template lock file (Nonemeans the system temp directory).
For a cluster outside the fixture, use provide_embedded_postgres_service(..., password="", init_sql=None) and
ensure_template(..., init_sql=...) for extension initialization prior to user template setup. Its
cleanup_mode="delete" removes the temporary data directory on exit and "keep" leaves it for inspection; a
data_dir you pass is never deleted.
Service API#
Embedded PostgreSQL service that runs local initdb / postgres binaries without a container runtime.
Binaries come from an explicit directory, PG_BIN_DIR, the pgembed or pgserver packages (the
embedded-postgres extra), the PATH, pg_config --bindir, or common system locations. The cluster uses
trust authentication on a loopback TCP port with Unix sockets disabled, and SQL runs over the PostgreSQL wire
protocol, so neither psql nor a Python driver is required.
- class pytest_databases.embedded.postgres.EmbeddedPostgresService(host: str, port: int, user: str, database: str, data_dir: Path, binaries: PostgresBinaries, process: Popen[bytes] | None = None, password: str = '')[source]#
Bases:
PostgresTemplateSupportConnection metadata and helpers for an embedded PostgreSQL server.
The cluster defaults to
trustauthentication with an emptypassword. Template helpers (ensure_template(),create_worker_database_from_template(),sweep_worker_databases(),clone_template_database(),drop_database_force()) behave as on the container service.- binaries: PostgresBinaries#
- property connection_config: dict[str, Any]#
host,port,user,database, and optionalpassword.- Returns:
The connection parameters.
- Type:
Driver keyword arguments
- exec_sql(sql: str, *, database: str | None = None, tuples_only: bool = False, timeout: float = 30.0) tuple[int, bytes][source]#
Run
sqlagainstdatabase(defaults to this service’s database).Output mirrors
psql -tA; exit code1is an SQL error and2a connection failure.- Returns:
The exit code and output bytes.
- class pytest_databases.embedded.postgres.PostgresBinaries(initdb: Path, postgres: Path, pg_ctl: Path | None = None)[source]#
Bases:
objectPaths to the local PostgreSQL server binaries.
pg_ctlis optional; without it the server is stopped with signals.- classmethod from_directory(directory: Path) PostgresBinaries | None[source]#
Return the binaries in
directory, or None wheninitdborpostgresis missing.- Returns:
The discovered binaries or None.
- pytest_databases.embedded.postgres.embedded_postgres_bin_dir() Path | str | None[source]#
Return a directory holding
initdb/postgres(None searches the usual locations).
- pytest_databases.embedded.postgres.embedded_postgres_database() str[source]#
Return the base name of the database the service yields (
<name>_<worker>under xdist).
- pytest_databases.embedded.postgres.embedded_postgres_port() int[source]#
Return the server port (0 picks a free port).
- pytest_databases.embedded.postgres.embedded_postgres_service(tmp_path_factory: pytest.TempPathFactory, embedded_postgres_user: str, embedded_postgres_database: str, embedded_postgres_port: int, embedded_postgres_bin_dir: Path | str | None, xdist_embedded_postgres_isolation_level: PostgresXdistIsolationLevel, embedded_postgres_template_name: str | None, embedded_postgres_template_setup: Callable[[EmbeddedPostgresService], object] | str | Path | Sequence[str | Path] | None, embedded_postgres_template_fingerprint_sources: Sequence[str | bytes | Path], embedded_postgres_template_lock_dir: Path | str | None) Generator[EmbeddedPostgresService, None, None][source]#
Provide an embedded PostgreSQL service.
Without xdist, or with
"server"isolation, each process starts its own cluster. Under xdist with"template"or"database"isolation, workers share one cluster and each gets its own database. With"template"the database is cloned from a template built once fromembedded_postgres_template_setup.- Yields:
The service pointed at this process’s database.
- pytest_databases.embedded.postgres.embedded_postgres_template_fingerprint_sources() Sequence[str | bytes | Path][source]#
Return extra strings, bytes, files, or directories folded into the template name digest.
- pytest_databases.embedded.postgres.embedded_postgres_template_lock_dir() Path | str | None[source]#
Return the directory for template lock files (None means the system temp directory).
- pytest_databases.embedded.postgres.embedded_postgres_template_name() str | None[source]#
Return the template name prefix (None means
"pytest_databases_template").
- pytest_databases.embedded.postgres.embedded_postgres_template_setup() Callable[[EmbeddedPostgresService], object] | str | Path | Sequence[str | Path] | None[source]#
Return the template setup: a callable receiving the staging service, or SQL statements /
.sqlpaths.
- pytest_databases.embedded.postgres.embedded_postgres_user() str[source]#
Return the superuser name (trust authentication, no password).
- pytest_databases.embedded.postgres.init_cluster(binaries: PostgresBinaries, data_dir: Path, *, user: str = 'postgres') None[source]#
Run
initdbwith trust authentication and append fast, non-durable settings.An existing cluster (
PG_VERSIONpresent) is left alone.- Raises:
RuntimeError – If
initdbfails.
- pytest_databases.embedded.postgres.postgres_any_service(request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory) Generator[PostgresServiceProtocol, None, None][source]#
Provide a session-scoped Docker or embedded PostgreSQL service selected via
--postgres-backend.- Yields:
Active PostgreSQL service conforming to
PostgresServiceProtocol.
- pytest_databases.embedded.postgres.provide_default_embedded_postgres_session(request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory) Generator[EmbeddedPostgresService, None, None][source]#
Yield
embedded_postgres_serviceif registered, else provision an xdist-safe embedded session cluster.- Yields:
Active
EmbeddedPostgresServicepointed at the worker database.
- pytest_databases.embedded.postgres.provide_embedded_postgres_service(*, data_dir: Path | str | None = None, bin_dir: Path | str | None = None, binaries: PostgresBinaries | None = None, host: str = '127.0.0.1', port: int = 0, user: str = 'postgres', password: str = '', database: str = 'postgres', cleanup_mode: Literal['delete', 'keep'] = 'delete', timeout: float = 15.0, init_sql: str | Path | Sequence[str | Path] | None = None) Generator[EmbeddedPostgresService, None, None][source]#
Start a private embedded PostgreSQL cluster for the duration of the context.
- Parameters:
data_dir – Cluster directory; an existing cluster is reused and never deleted. None creates a temporary one.
bin_dir – Directory holding
initdb/postgres; ignored whenbinariesis given.binaries – Already resolved binaries.
host – Loopback address to listen on.
port – TCP port, or 0 for a free port.
user – Superuser created by
initdb(trust authentication by default).password – Role password attached to
EmbeddedPostgresService(empty string for trust auth).database – Database to create and return;
"postgres"uses the default database.cleanup_mode –
"delete"removes the temporarydata_diron exit,"keep"leaves it for inspection.timeout – Seconds to wait for the server to answer.
init_sql – Optional SQL statement,
.sqlpath, or sequence executed directly againstdatabase.
- Yields:
The running service.
- pytest_databases.embedded.postgres.resolve_postgres_binaries(bin_dir: Path | str | None = None) PostgresBinaries[source]#
Find
initdbandpostgres(andpg_ctlwhen present).Search order:
bin_dir,PG_BIN_DIR, thepgembed/pgserverpackages, thePATH,pg_config --bindir, then common system install directories. A candidate missing either required binary is skipped.- Returns:
The discovered binaries.
- Raises:
RuntimeError – If
bin_dirlacks the binaries, or no candidate has them.
- pytest_databases.embedded.postgres.start_cluster(binaries: PostgresBinaries, data_dir: Path, *, host: str = '127.0.0.1', port: int = 0, user: str = 'postgres', startup_timeout: float = 15.0) tuple[Popen[bytes], int][source]#
Start
postgresonhost:port(a free port whenportis 0) and wait forSELECT 1.Unix sockets are disabled (
-k ""). With a dynamic port, a server that exits during startup (usually a port race) is retried on a new port up to three times. The server log isdata_dir/postgresql.log.- Returns:
The server process and its port.
- Raises:
RuntimeError – If the server exits during startup.
TimeoutError – If the server does not answer within
startup_timeout; the message carries the last query result and the log tail.
- pytest_databases.embedded.postgres.stop_cluster(binaries: PostgresBinaries, data_dir: Path, process: Popen[bytes] | None = None, timeout: float = 10.0) None[source]#
Stop the server for
data_dirwith a fast shutdown and reapprocesswhen given.Uses
pg_ctl stop -m fastwhen available, otherwiseSIGINTto the postmaster (processor the PID inpostmaster.pid), escalating toSIGKILLaftertimeoutseconds.