Skip to main content

pytest-servex

pipeline status PyPI version Python versions License: MIT

Starts the Docker containers your tests need, once per test run, and shares them with all workers. Any image works, in pytest or plain Python. Postgres has a ready-made recipe with one database per worker.

Install

pip install pytest-servex "psycopg[binary]"

Requires Python 3.12+ and a Docker daemon. Talks to the Docker API directly with the standard library: no docker SDK, no requests.

Quickstart

Request servex_postgres in a test. It is a database of your own, on a container started once for the run:

import psycopg


def test_insert(servex_postgres):
    with psycopg.connect(servex_postgres.url) as conn:
        conn.execute("CREATE TABLE t (x int)")
        conn.execute("INSERT INTO t VALUES (1)")

To run migrations once, override servex_postgres_prepare in conftest.py. Every worker database starts as a copy of the result:

import subprocess

import pytest


@pytest.fixture(scope="session")
def servex_postgres_prepare():
    def prepare(url: str) -> None:
        subprocess.run(["alembic", "upgrade", "head"], env={"DATABASE_URL": url}, check=True)

    return prepare

Valkey and Redis

Request servex_valkey. Each worker gets its own database number on one shared server, flushed when the worker starts and ends:

import redis


def test_cache(servex_valkey):
    r = redis.Redis.from_url(servex_valkey.url)  # redis://127.0.0.1:32772/0
    r.set("k", "v")

The container runs with persistence off and 128 databases. Set SERVEX_VALKEY_IMAGE=redis:7-alpine to test against Redis instead.

Any image

container_fixture turns a Container into a session fixture. The variable name is the fixture name:

from pytest_servex import Container, container_fixture

api = container_fixture(Container(image="myorg/api:1.4", ports=(8080,), env={"MODE": "test"}))


def test_health(api):
    endpoint = api.endpoint(8080)  # Endpoint(host='127.0.0.1', port=32773)

Pass ready= to wait for the service. Speak its protocol (a query, a PING, an HTTP request): Docker accepts TCP connections on the published port before the service listens. Two checks are built in:

from pytest_servex import Bind, Container, http_ready, log_ready

registry = Container(
    image="registry:2",
    ports=(5000,),
    mounts=(Bind("tests/certs", "/auth"),),  # host path, read-only by default
    ready=http_ready(5000, "/v2/"),  # any answer below 500 counts, 401 included
)
worker = Container(image="myorg/worker:2", ready=log_ready("listening on"))

How Postgres works

  1. servex_postgres_server starts one Postgres container for the run, with fsync off and data on tmpfs.
  2. servex_postgres_template creates the database servex_template and runs your prepare function on it, once.
  3. servex_postgres copies the template into one database per worker (CREATE DATABASE servex_f0 TEMPLATE servex_template). This copies files, so it takes milliseconds instead of a migration run.

Under pytest-parallex steps 1 and 2 run once in the controller, before the fork. Under pytest-xdist each worker runs its own session, so each worker starts its own container.

Outside pytest

Specs are frozen dataclasses. running starts one on enter and removes it on exit, so nested blocks stop in reverse order:

from dataclasses import replace

from pytest_servex import POSTGRES, Network, running

net = Network("app")
pg = replace(POSTGRES, networks=(net,), alias="db", pull="never")

with running(net), running(pg) as started:
    print(started.endpoint(5432))  # Endpoint(host='127.0.0.1', port=32771)

Errors subclass the built-in they resemble, and all subclass ServexError:

Error Also a When
NotReady TimeoutError The ready check timed out, or the container exited first. Has .logs.
ImageNotFound LookupError The image is missing and pull="never", or the pull failed.
NotFound LookupError Docker has no such object (HTTP 404).
Conflict A name is taken, or a network or volume is still in use (HTTP 409).
DockerUnavailable ConnectionError The Docker socket is missing or refuses connections.

Configuration

  • SERVEX_POSTGRES_URL: use this server and start nothing (for example a CI service). It must point at a database whose user may create databases.
  • SERVEX_POSTGRES_IMAGE: the image to start. Default postgres:17-alpine.
  • SERVEX_VALKEY_URL: use this Valkey or Redis server and start nothing (redis://[:password@]host:port). An external server has 16 databases by default, so at most 16 workers.
  • SERVEX_VALKEY_IMAGE: the image to start. Default valkey/valkey:8-alpine.
  • DOCKER_HOST: the Docker API, unix:// or tcp://. Podman's Docker-compatible socket is meant to work but is not tested yet.
  • SERVEX_HOST: where tests connect to published ports, when that is not the DOCKER_HOST address (for example docker with a GitLab docker:dind service).

Compared to testcontainers

  • No Ryuk container. Containers carry labels with the run's pid. The next run removes the containers of runs that were killed.
  • No Docker client crosses a fork. Fixtures hand workers plain URL strings.
  • A template database and one copy per worker are built in, not left to each conftest.py.

License

MIT © 2026 Jorge Cardona.

Metadata

Release files for pytest-servex 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pytest-servex 0.3.0
File Size Uploaded Provenance Actions
pytest_servex-0.3.0.tar.gz 28.7 kB Without provenance Details for pytest_servex-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pytest-servex 0.3.0
File Interpreter ABI Platform Actions
pytest_servex-0.3.0-py3-none-any.whl Python 3 none any Details for pytest_servex-0.3.0-py3-none-any.whl

Total release size: 53.8 kB

Release files / pytest_servex-0.3.0.tar.gz

Download URL pytest_servex-0.3.0.tar.gz
Size 28.7 kB
Tags Source
SHA-256 checksum
How to use checksums
eb6d0f293fd9fc7ed5b2bdab8f3fe1bd772b776ae2381142ef65f3e7c1032279
BLAKE2b-256 checksum
How to use checksums
35087b34dca0a648fe89b154112d58e2af03e8d2e6197e2a456e2de2c30a1e8f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.11.19 {"installer":{"name":"uv","version":"0.11.19","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"12","id":"bookworm","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / pytest_servex-0.3.0-py3-none-any.whl

Download URL pytest_servex-0.3.0-py3-none-any.whl
Size 25.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8dc1c3f6371d3e8128efee75bfe7bbd962eb0a457e5fdf6bf7f7727e19368f3f
BLAKE2b-256 checksum
How to use checksums
a28896bc94864b623912d1ca5aeb9abc92ebc9801f5437b5fed48b0cd324567f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.11.19 {"installer":{"name":"uv","version":"0.11.19","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"12","id":"bookworm","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for pytest-servex 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page