Skip to content

API reference

pytest_servex

A pytest plugin that starts the Docker containers your tests need, one database per worker.

POSTGRES module-attribute

POSTGRES = Container(
    image="postgres:17-alpine",
    ports=(PORT,),
    ready=_ready,
    env={
        "POSTGRES_USER": USER,
        "POSTGRES_PASSWORD": PASSWORD,
    },
    command=(
        "postgres",
        "-c",
        "fsync=off",
        "-c",
        "synchronous_commit=off",
        "-c",
        "full_page_writes=off",
    ),
    mounts=(Tmpfs("/var/lib/postgresql/data"),),
)

Postgres with durability off and data on tmpfs.

Docker empties tmpfs when the container stops, so a restart starts a new empty database. Use replace(POSTGRES, mounts=()) to keep data across a restart (#3).

REDIS module-attribute

REDIS = replace(
    VALKEY,
    image="redis:7-alpine",
    command=("redis-server", *_NO_DISK),
)

Redis with the same settings. Use it where production runs Redis, not Valkey.

VALKEY module-attribute

VALKEY = Container(
    image="valkey/valkey:8-alpine",
    ports=(PORT,),
    command=("valkey-server", *_NO_DISK),
    ready=_ready,
)

Valkey with persistence off and 128 databases.

Conflict

Bases: DockerError

The name is taken, or the object is still in use (HTTP 409).

Source code in src/pytest_servex/errors.py
class Conflict(DockerError):  # noqa: N818  # pairs with NotFound
    """The name is taken, or the object is still in use (HTTP 409)."""

DockerError

Bases: ServexError

The Docker API answered with an error status.

PARAMETER DESCRIPTION
status

The HTTP status code.

TYPE: int

message

Docker's own error message.

TYPE: str

Source code in src/pytest_servex/errors.py
class DockerError(ServexError):
    """The Docker API answered with an error status.

    Args:
        status: The HTTP status code.
        message: Docker's own error message.
    """

    def __init__(self, status: int, message: str) -> None:
        """Keep the status and Docker's message."""
        super().__init__(f"Docker API {status}: {message}")
        self.status = status
        self.message = message
__init__
__init__(status: int, message: str) -> None

Keep the status and Docker's message.

Source code in src/pytest_servex/errors.py
def __init__(self, status: int, message: str) -> None:
    """Keep the status and Docker's message."""
    super().__init__(f"Docker API {status}: {message}")
    self.status = status
    self.message = message

DockerUnavailable

Bases: ServexError, ConnectionError

The Docker API socket is missing or refuses connections (is the daemon running?).

Source code in src/pytest_servex/errors.py
class DockerUnavailable(ServexError, ConnectionError):  # noqa: N818  # reads as a state, like TimeoutError
    """The Docker API socket is missing or refuses connections (is the daemon running?)."""

ImageNotFound

Bases: NotFound

The image is not local and the pull policy forbids pulling it, or the pull failed.

Source code in src/pytest_servex/errors.py
class ImageNotFound(NotFound):
    """The image is not local and the pull policy forbids pulling it, or the pull failed."""

NotFound

Bases: DockerError, LookupError

Docker has no such container, network, volume, or image (HTTP 404).

Source code in src/pytest_servex/errors.py
class NotFound(DockerError, LookupError):  # noqa: N818
    """Docker has no such container, network, volume, or image (HTTP 404)."""

NotReady

Bases: ServexError, TimeoutError

A container did not pass its ready check: it timed out, or it exited first.

The container is removed before this is raised. logs holds its last lines.

Source code in src/pytest_servex/errors.py
class NotReady(ServexError, TimeoutError):  # noqa: N818
    """A container did not pass its ``ready`` check: it timed out, or it exited first.

    The container is removed before this is raised. ``logs`` holds its last lines.
    """

    def __init__(self, image: str, reason: str, logs: str) -> None:
        """Keep the image and the container's last log lines."""
        super().__init__(f"{image} not ready: {reason}. Last logs:\n{logs}")
        self.image = image
        self.logs = logs
__init__
__init__(image: str, reason: str, logs: str) -> None

Keep the image and the container's last log lines.

Source code in src/pytest_servex/errors.py
def __init__(self, image: str, reason: str, logs: str) -> None:
    """Keep the image and the container's last log lines."""
    super().__init__(f"{image} not ready: {reason}. Last logs:\n{logs}")
    self.image = image
    self.logs = logs

ServexError

Bases: Exception

Base class of every error pytest-servex raises.

Source code in src/pytest_servex/errors.py
class ServexError(Exception):
    """Base class of every error pytest-servex raises."""

PostgresDatabase dataclass

One database on the run's server, owned by one worker.

Source code in src/pytest_servex/postgres.py
@dataclass(frozen=True)
class PostgresDatabase:
    """One database on the run's server, owned by one worker."""

    name: str
    url: str

    def sqlalchemy_url(self, driver: str = "psycopg") -> str:
        """Return ``url`` with a SQLAlchemy driver in the scheme (``postgresql+psycopg://``)."""
        return re.sub(r"^postgres(ql)?://", f"postgresql+{driver}://", self.url)
sqlalchemy_url
sqlalchemy_url(driver: str = 'psycopg') -> str

Return url with a SQLAlchemy driver in the scheme (postgresql+psycopg://).

Source code in src/pytest_servex/postgres.py
def sqlalchemy_url(self, driver: str = "psycopg") -> str:
    """Return ``url`` with a SQLAlchemy driver in the scheme (``postgresql+psycopg://``)."""
    return re.sub(r"^postgres(ql)?://", f"postgresql+{driver}://", self.url)

PostgresServer dataclass

A Postgres server for this run, as a URL to its admin (postgres) database.

Only strings: safe to hand to forked or spawned workers.

Source code in src/pytest_servex/postgres.py
@dataclass(frozen=True)
class PostgresServer:
    """A Postgres server for this run, as a URL to its admin (``postgres``) database.

    Only strings: safe to hand to forked or spawned workers.
    """

    url: str

    def database_url(self, database: str) -> str:
        """Return the URL of ``database`` on this server."""
        return with_database(self.url, database)
database_url
database_url(database: str) -> str

Return the URL of database on this server.

Source code in src/pytest_servex/postgres.py
def database_url(self, database: str) -> str:
    """Return the URL of ``database`` on this server."""
    return with_database(self.url, database)

Bind dataclass

Mount host path source at target inside a container. Read-only by default.

source is a path on the machine that runs the Docker daemon (with a remote DOCKER_HOST, that is not the test machine). A relative path is made absolute against the current directory. (#1)

Source code in src/pytest_servex/spec.py
@dataclass(frozen=True)
class Bind:
    """Mount host path ``source`` at ``target`` inside a container. Read-only by default.

    ``source`` is a path on the machine that runs the Docker daemon (with a remote
    ``DOCKER_HOST``, that is not the test machine). A relative path is made absolute
    against the current directory. (#1)
    """

    source: str
    target: str
    read_only: bool = True

Container dataclass

A container to start.

PARAMETER DESCRIPTION
image

Image reference. Pin a tag; it is pulled only when missing.

TYPE: str

ports

Container ports to publish on random host ports.

TYPE: tuple[int, ...] DEFAULT: ()

env

Environment variables. Stored sorted and read-only.

TYPE: Mapping[str, str] DEFAULT: (lambda: MappingProxyType({}))()

command

Replaces the image's default command when not empty.

TYPE: tuple[str, ...] DEFAULT: ()

mounts

Tmpfs, Mount (named volume), and Bind (host path) entries.

TYPE: tuple[Tmpfs | Mount | Bind, ...] DEFAULT: ()

networks

Networks to join. Start them first.

TYPE: tuple[Network, ...] DEFAULT: ()

alias

The DNS name other containers on the same networks use.

TYPE: str DEFAULT: ''

ready

Returns True once the container accepts real work. Called in a loop until True or until the start timeout. Return False for "not yet"; do not raise. The default treats a started container as ready. Speak the service's own protocol (a query, a PING, an HTTP request): Docker's port proxy accepts TCP connections before the service listens, so a bare connect proves nothing.

TYPE: Callable[[RunningContainer], bool] DEFAULT: _always_ready

pull

When to pull the image, with the docker run --pull values: "missing" (default), "always", "never" (raise ImageNotFound if not local).

TYPE: Pull DEFAULT: 'missing'

entrypoint

Replaces the image's entrypoint when not empty.

TYPE: tuple[str, ...] DEFAULT: ()

user

"uid[:gid]" or a user name to run as.

TYPE: str DEFAULT: ''

working_dir

The working directory inside the container.

TYPE: str DEFAULT: ''

memory

Memory limit in bytes.

TYPE: int | None DEFAULT: None

shm_size

Size of /dev/shm in bytes (Postgres parallel queries use it).

TYPE: int | None DEFAULT: None

host_config

Extra HostConfig fields of the Docker API, merged last, for anything without its own field (for example {"CapAdd": ["NET_ADMIN"]}).

TYPE: Mapping[str, Any] DEFAULT: (lambda: MappingProxyType({}))()

Source code in src/pytest_servex/spec.py
@dataclass(frozen=True)
class Container:
    """A container to start.

    Args:
        image: Image reference. Pin a tag; it is pulled only when missing.
        ports: Container ports to publish on random host ports.
        env: Environment variables. Stored sorted and read-only.
        command: Replaces the image's default command when not empty.
        mounts: ``Tmpfs``, ``Mount`` (named volume), and ``Bind`` (host path) entries.
        networks: Networks to join. Start them first.
        alias: The DNS name other containers on the same networks use.
        ready: Returns True once the container accepts real work. Called in a loop until
            True or until the start timeout. Return False for "not yet"; do not raise.
            The default treats a started container as ready. Speak the service's own
            protocol (a query, a ``PING``, an HTTP request): Docker's port proxy accepts
            TCP connections before the service listens, so a bare connect proves nothing.
        pull: When to pull the image, with the ``docker run --pull`` values: ``"missing"``
            (default), ``"always"``, ``"never"`` (raise ``ImageNotFound`` if not local).
        entrypoint: Replaces the image's entrypoint when not empty.
        user: ``"uid[:gid]"`` or a user name to run as.
        working_dir: The working directory inside the container.
        memory: Memory limit in bytes.
        shm_size: Size of ``/dev/shm`` in bytes (Postgres parallel queries use it).
        host_config: Extra ``HostConfig`` fields of the Docker API, merged last, for
            anything without its own field (for example ``{"CapAdd": ["NET_ADMIN"]}``).
    """

    image: str
    ports: tuple[int, ...] = ()
    env: Mapping[str, str] = field(default_factory=lambda: MappingProxyType({}))
    command: tuple[str, ...] = ()
    mounts: tuple[Tmpfs | Mount | Bind, ...] = ()
    networks: tuple[Network, ...] = ()
    alias: str = ""
    ready: Callable[[RunningContainer], bool] = _always_ready
    pull: Pull = "missing"
    entrypoint: tuple[str, ...] = ()
    user: str = ""
    working_dir: str = ""
    memory: int | None = None
    shm_size: int | None = None
    host_config: Mapping[str, Any] = field(default_factory=lambda: MappingProxyType({}))

    def __post_init__(self) -> None:
        """Freeze ``env`` and ``host_config`` so a spec cannot change after it is made."""
        object.__setattr__(self, "env", _freeze(self.env))
        object.__setattr__(self, "host_config", MappingProxyType(dict(self.host_config)))

    def __hash__(self) -> int:
        """Hash by value, with ``env`` as its sorted items."""
        return hash(
            (
                self.image,
                self.ports,
                tuple(self.env.items()),
                self.command,
                self.mounts,
                self.networks,
                self.alias,
                self.ready,
                self.pull,
                self.entrypoint,
                self.user,
                self.working_dir,
                self.memory,
                self.shm_size,
                repr(sorted(self.host_config.items())),  # values may be lists
            )
        )
__post_init__
__post_init__() -> None

Freeze env and host_config so a spec cannot change after it is made.

Source code in src/pytest_servex/spec.py
def __post_init__(self) -> None:
    """Freeze ``env`` and ``host_config`` so a spec cannot change after it is made."""
    object.__setattr__(self, "env", _freeze(self.env))
    object.__setattr__(self, "host_config", MappingProxyType(dict(self.host_config)))
__hash__
__hash__() -> int

Hash by value, with env as its sorted items.

Source code in src/pytest_servex/spec.py
def __hash__(self) -> int:
    """Hash by value, with ``env`` as its sorted items."""
    return hash(
        (
            self.image,
            self.ports,
            tuple(self.env.items()),
            self.command,
            self.mounts,
            self.networks,
            self.alias,
            self.ready,
            self.pull,
            self.entrypoint,
            self.user,
            self.working_dir,
            self.memory,
            self.shm_size,
            repr(sorted(self.host_config.items())),  # values may be lists
        )
    )

Endpoint dataclass

A host and port where a started container accepts connections.

Source code in src/pytest_servex/spec.py
@dataclass(frozen=True)
class Endpoint:
    """A host and port where a started container accepts connections."""

    host: str
    port: int

Mount dataclass

Mount volume at target inside a container.

Source code in src/pytest_servex/spec.py
@dataclass(frozen=True)
class Mount:
    """Mount ``volume`` at ``target`` inside a container."""

    volume: Volume
    target: str

Network dataclass

A user-defined bridge network. Containers on it reach each other by alias.

Source code in src/pytest_servex/spec.py
@dataclass(frozen=True)
class Network:
    """A user-defined bridge network. Containers on it reach each other by alias."""

    name: str

RunningContainer dataclass

A container that start created and started.

ports maps each container port to its published host port, as sorted pairs.

Source code in src/pytest_servex/spec.py
@dataclass(frozen=True)
class RunningContainer:
    """A container that ``start`` created and started.

    ``ports`` maps each container port to its published host port, as sorted pairs.
    """

    id: str
    spec: Container
    host: str
    ports: tuple[tuple[int, int], ...]

    def endpoint(self, port: int) -> Endpoint:
        """Return where container ``port`` is reachable from the test process.

        Raises:
            KeyError: ``port`` was not in the spec's ``ports``.
        """
        return Endpoint(host=self.host, port=dict(self.ports)[port])
endpoint
endpoint(port: int) -> Endpoint

Return where container port is reachable from the test process.

RAISES DESCRIPTION
KeyError

port was not in the spec's ports.

Source code in src/pytest_servex/spec.py
def endpoint(self, port: int) -> Endpoint:
    """Return where container ``port`` is reachable from the test process.

    Raises:
        KeyError: ``port`` was not in the spec's ``ports``.
    """
    return Endpoint(host=self.host, port=dict(self.ports)[port])

RunningNetwork dataclass

A network that start created.

Source code in src/pytest_servex/spec.py
@dataclass(frozen=True)
class RunningNetwork:
    """A network that ``start`` created."""

    id: str
    spec: Network

RunningVolume dataclass

A volume that start created.

Source code in src/pytest_servex/spec.py
@dataclass(frozen=True)
class RunningVolume:
    """A volume that ``start`` created."""

    spec: Volume

Tmpfs dataclass

A tmpfs at target inside a container: data in memory, nothing written to disk.

options are mount options, for example "size=256m".

Source code in src/pytest_servex/spec.py
@dataclass(frozen=True)
class Tmpfs:
    """A tmpfs at ``target`` inside a container: data in memory, nothing written to disk.

    ``options`` are mount options, for example ``"size=256m"``.
    """

    target: str
    options: str = ""

Volume dataclass

A named Docker volume. Data survives the container, not the end of the run.

Source code in src/pytest_servex/spec.py
@dataclass(frozen=True)
class Volume:
    """A named Docker volume. Data survives the container, not the end of the run."""

    name: str

ValkeyDatabase dataclass

One worker's database on the run's server.

Source code in src/pytest_servex/valkey.py
@dataclass(frozen=True)
class ValkeyDatabase:
    """One worker's database on the run's server."""

    index: int
    url: str

ValkeyServer dataclass

The run's Valkey or Redis server, as a redis:// URL without a database number.

Source code in src/pytest_servex/valkey.py
@dataclass(frozen=True)
class ValkeyServer:
    """The run's Valkey or Redis server, as a ``redis://`` URL without a database number."""

    url: str

container_fixture

container_fixture(
    spec: Container, *, timeout: float = 60.0
) -> Callable[[], Iterator[RunningContainer]]

Return a session fixture that starts spec once per run and yields it running.

Assign it to a name in conftest.py; that name becomes the fixture name::

api = container_fixture(Container(image="myorg/api:1.4", ports=(8080,)))

def test_health(api):
    host, port = api.endpoint(8080).host, api.endpoint(8080).port

Under pytest-parallex the container starts once, before the workers fork, and every worker shares it. Under pytest-xdist each worker starts its own. The container is removed at the end of the run; containers of killed runs are removed first.

Source code in src/pytest_servex/fixtures.py
def container_fixture(
    spec: Container, *, timeout: float = 60.0
) -> Callable[[], Iterator[RunningContainer]]:
    """Return a session fixture that starts ``spec`` once per run and yields it running.

    Assign it to a name in ``conftest.py``; that name becomes the fixture name::

        api = container_fixture(Container(image="myorg/api:1.4", ports=(8080,)))

        def test_health(api):
            host, port = api.endpoint(8080).host, api.endpoint(8080).port

    Under pytest-parallex the container starts once, before the workers fork, and every
    worker shares it. Under pytest-xdist each worker starts its own. The container is
    removed at the end of the run; containers of killed runs are removed first.
    """

    @pytest.fixture(scope="session")
    def _container() -> Iterator[RunningContainer]:
        remove_stale()
        with running(spec, timeout=timeout) as started:
            yield started

    return _container

logs

logs(
    started: RunningContainer, *, tail: int | None = None
) -> str

Return the container's stdout and stderr as text, the last tail lines if given.

Source code in src/pytest_servex/lifecycle.py
def logs(started: RunningContainer, *, tail: int | None = None) -> str:
    """Return the container's stdout and stderr as text, the last ``tail`` lines if given."""
    query = {"stdout": "1", "stderr": "1", "tail": "all" if tail is None else str(tail)}
    with Engine() as engine:
        return demux_logs(engine.raw("GET", f"/containers/{started.id}/logs", query=query))

refresh

refresh(started: RunningContainer) -> RunningContainer

Return started with the ports Docker publishes now.

A restart gives the container new host ports, and started keeps the old ones. Call this after a restart, then use endpoint on the result.

RAISES DESCRIPTION
NotFound

The container is gone.

KeyError

The container is stopped, so Docker publishes no ports.

Source code in src/pytest_servex/lifecycle.py
def refresh(started: RunningContainer) -> RunningContainer:
    """Return ``started`` with the ports Docker publishes now.

    A restart gives the container new host ports, and ``started`` keeps the old ones. Call
    this after a restart, then use ``endpoint`` on the result.

    Raises:
        NotFound: The container is gone.
        KeyError: The container is stopped, so Docker publishes no ports.
    """
    with Engine() as engine:
        return _inspect(engine, started.id, started.spec)

remove_stale

remove_stale() -> int

Remove the containers, networks, and volumes of killed runs on this host.

A normal run removes its own objects. A run killed with SIGKILL cannot, so the next run does it here. This replaces the Ryuk container testcontainers runs alongside each session. Returns how many objects were removed.

Source code in src/pytest_servex/lifecycle.py
def remove_stale() -> int:
    """Remove the containers, networks, and volumes of killed runs on this host.

    A normal run removes its own objects. A run killed with SIGKILL cannot, so the next
    run does it here. This replaces the Ryuk container testcontainers runs alongside each
    session. Returns how many objects were removed.
    """
    host = socket.gethostname()
    filters = {"filters": f'{{"label": ["{LABEL}"]}}'}
    removed = 0
    with Engine() as engine:
        containers: list[dict[str, Any]] = engine.call(
            "GET", "/containers/json", query={"all": "1", **filters}
        )
        for item in containers:
            if _stale(item.get("Labels"), host):
                _remove_container(engine, item["Id"])
                removed += 1
        networks: list[dict[str, Any]] = engine.call("GET", "/networks", query=filters)
        for item in networks:
            if _stale(item.get("Labels"), host):
                _delete(engine, f"/networks/{item['Id']}")
                removed += 1
        volumes: list[dict[str, Any]] = (
            engine.call("GET", "/volumes", query=filters)["Volumes"] or []
        )
        for item in volumes:
            if _stale(item.get("Labels"), host):
                _delete(engine, f"/volumes/{item['Name']}")
                removed += 1
    return removed

running

running(
    spec: Network, *, timeout: float = ...
) -> AbstractContextManager[RunningNetwork]
running(
    spec: Volume, *, timeout: float = ...
) -> AbstractContextManager[RunningVolume]
running(
    spec: Container, *, timeout: float = ...
) -> AbstractContextManager[RunningContainer]
running(
    spec: Spec, *, timeout: float = 60.0
) -> AbstractContextManager[Running]

Start spec on enter and stop it on exit, even when the block raises.

Nest them in dependency order and they stop in reverse::

with running(net), running(pg) as started:
    started.endpoint(5432)
Source code in src/pytest_servex/lifecycle.py
def running(spec: Spec, *, timeout: float = 60.0) -> AbstractContextManager[Running]:
    """Start ``spec`` on enter and stop it on exit, even when the block raises.

    Nest them in dependency order and they stop in reverse::

        with running(net), running(pg) as started:
            started.endpoint(5432)
    """
    return _running(spec, timeout)

start

start(
    spec: Network, *, timeout: float = ...
) -> RunningNetwork
start(
    spec: Volume, *, timeout: float = ...
) -> RunningVolume
start(
    spec: Container, *, timeout: float = ...
) -> RunningContainer
start(spec: Spec, *, timeout: float = 60.0) -> Running

Create spec in Docker and return what was started.

A container is started and waited on until spec.ready is True. Its networks and volumes must exist already: start them first.

RAISES DESCRIPTION
NotReady

The container was not ready within timeout seconds. It is removed before raising, and the error carries its last 40 log lines.

ImageNotFound

The image is missing and pull is not "missing", or the pull failed.

Conflict

A network or volume with that name exists already.

DockerUnavailable

The Docker API cannot be reached.

Source code in src/pytest_servex/lifecycle.py
def start(spec: Spec, *, timeout: float = 60.0) -> Running:
    """Create ``spec`` in Docker and return what was started.

    A container is started and waited on until ``spec.ready`` is True. Its networks and
    volumes must exist already: start them first.

    Raises:
        NotReady: The container was not ready within ``timeout`` seconds. It is removed
            before raising, and the error carries its last 40 log lines.
        ImageNotFound: The image is missing and ``pull`` is not ``"missing"``, or the pull failed.
        Conflict: A network or volume with that name exists already.
        DockerUnavailable: The Docker API cannot be reached.
    """
    return _start(spec, timeout)

stop

stop(running: Running) -> None

Remove what start created. Something already gone is fine.

A container is removed with its anonymous volumes. A network or volume still in use by a container raises Conflict: stop containers first.

Source code in src/pytest_servex/lifecycle.py
def stop(running: Running) -> None:
    """Remove what ``start`` created. Something already gone is fine.

    A container is removed with its anonymous volumes. A network or volume still in use
    by a container raises ``Conflict``: stop containers first.
    """
    with Engine() as engine:
        match running:
            case RunningContainer():
                _remove_container(engine, running.id)
            case RunningNetwork():
                _delete(engine, f"/networks/{running.id}")
            case RunningVolume():
                _delete(engine, f"/volumes/{running.spec.name}")

http_ready

http_ready(port: int, path: str = '/') -> Ready

Return a check that passes once GET path on container port gets any answer below 500.

A 401 or 404 still means the server is up, which is what readiness asks.

Source code in src/pytest_servex/ready.py
def http_ready(port: int, path: str = "/") -> Ready:
    """Return a check that passes once ``GET path`` on container ``port`` gets any answer below 500.

    A 401 or 404 still means the server is up, which is what readiness asks.
    """

    def check(started: RunningContainer) -> bool:
        endpoint = started.endpoint(port)
        conn = http.client.HTTPConnection(endpoint.host, endpoint.port, timeout=1)
        try:
            conn.request("GET", path)
            return conn.getresponse().status < HTTP_SERVER_ERROR
        except (OSError, http.client.HTTPException):
            return False
        finally:
            conn.close()

    return check

log_ready

log_ready(pattern: str, *, times: int = 1) -> Ready

Return a check that passes once pattern (a regex) matched times log lines.

times covers images that print the same line twice, such as Postgres, which logs "ready to accept connections" once for its init server and once for the real one. Prefer a protocol check where one exists: a log line can appear before the port is served. (#2)

Source code in src/pytest_servex/ready.py
def log_ready(pattern: str, *, times: int = 1) -> Ready:
    """Return a check that passes once ``pattern`` (a regex) matched ``times`` log lines.

    ``times`` covers images that print the same line twice, such as Postgres, which logs
    "ready to accept connections" once for its init server and once for the real one.
    Prefer a protocol check where one exists: a log line can appear before the port is
    served. (#2)
    """
    regex = re.compile(pattern)

    def check(started: RunningContainer) -> bool:
        try:
            text = logs(started)
        except ServexError:
            return False
        return sum(1 for line in text.splitlines() if regex.search(line)) >= times

    return check