pytest-servex 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,53 @@
1
+ """Pytest fixtures that start test services in Docker once per run and give each worker its own database."""
2
+
3
+ from pytest_servex.errors import (
4
+ Conflict,
5
+ DockerError,
6
+ DockerUnavailable,
7
+ ImageNotFound,
8
+ NotFound,
9
+ NotReady,
10
+ ServexError,
11
+ )
12
+ from pytest_servex.lifecycle import remove_stale, running, start, stop
13
+ from pytest_servex.postgres import POSTGRES, PostgresDatabase, PostgresServer
14
+ from pytest_servex.spec import (
15
+ Container,
16
+ Endpoint,
17
+ Mount,
18
+ Network,
19
+ RunningContainer,
20
+ RunningNetwork,
21
+ RunningVolume,
22
+ Tmpfs,
23
+ Volume,
24
+ )
25
+
26
+ __version__ = "0.1.1" # the single source of truth; pyproject reads it via [tool.hatch.version]
27
+
28
+ __all__ = [
29
+ "POSTGRES",
30
+ "Conflict",
31
+ "Container",
32
+ "DockerError",
33
+ "DockerUnavailable",
34
+ "Endpoint",
35
+ "ImageNotFound",
36
+ "Mount",
37
+ "Network",
38
+ "NotFound",
39
+ "NotReady",
40
+ "PostgresDatabase",
41
+ "PostgresServer",
42
+ "RunningContainer",
43
+ "RunningNetwork",
44
+ "RunningVolume",
45
+ "ServexError",
46
+ "Tmpfs",
47
+ "Volume",
48
+ "__version__",
49
+ "remove_stale",
50
+ "running",
51
+ "start",
52
+ "stop",
53
+ ]
@@ -0,0 +1,183 @@
1
+ """A minimal Docker Engine API client: ``http.client`` over the Docker socket, stdlib only.
2
+
3
+ One ``Engine`` holds one keep-alive connection, so the create, start, and inspect requests
4
+ of a container start share it. No engine outlives a ``with`` block: under pytest-parallex a
5
+ connection inherited by forked workers breaks when they use it at once.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import http.client
12
+ import json
13
+ import os
14
+ import socket
15
+ import struct
16
+ from collections.abc import Iterator, Mapping
17
+ from dataclasses import dataclass
18
+ from types import TracebackType
19
+ from typing import Any, Literal, Self
20
+ from urllib.parse import urlencode, urlsplit
21
+
22
+ from pytest_servex.errors import DockerError, DockerUnavailable, docker_error
23
+
24
+ API = "/v1.41" # Docker 20.10+, and Podman's Docker-compatible API
25
+ DEFAULT_SOCKET = "/var/run/docker.sock"
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class DockerHost:
30
+ """Where the Docker API listens, and where published ports are reachable.
31
+
32
+ ``kind`` is ``"unix"`` (``address`` is a socket path) or ``"tcp"`` (``address`` is a
33
+ host name, plain HTTP, no TLS). ``published_host`` is the address tests connect to.
34
+ """
35
+
36
+ kind: Literal["unix", "tcp"]
37
+ address: str
38
+ port: int
39
+ published_host: str
40
+
41
+ @classmethod
42
+ def from_env(cls, docker_host: str | None, published_host: str | None = None) -> DockerHost:
43
+ """Parse a ``DOCKER_HOST`` value. Unset means the local default socket.
44
+
45
+ ``published_host`` (from ``SERVEX_HOST``) overrides where tests connect. Set it when
46
+ the published ports are on another address than the API, for example in GitLab CI
47
+ with a ``docker:dind`` service, where the ports are on the service host ``docker``.
48
+ The host is never guessed from "am I inside a container" checks: they break.
49
+
50
+ Raises:
51
+ ValueError: An ``ssh://`` or other unsupported scheme.
52
+ """
53
+ if not docker_host:
54
+ return cls("unix", DEFAULT_SOCKET, 0, published_host or "127.0.0.1")
55
+ parts = urlsplit(docker_host)
56
+ if parts.scheme == "unix":
57
+ return cls("unix", parts.path, 0, published_host or "127.0.0.1")
58
+ if parts.scheme in {"tcp", "http"} and parts.hostname:
59
+ return cls("tcp", parts.hostname, parts.port or 2375, published_host or parts.hostname)
60
+ raise ValueError(f"unsupported DOCKER_HOST {docker_host!r}: use unix:// or tcp://")
61
+
62
+
63
+ class _UnixConnection(http.client.HTTPConnection):
64
+ def __init__(self, path: str, timeout: float) -> None:
65
+ super().__init__("localhost", timeout=timeout)
66
+ self._path = path
67
+
68
+ def connect(self) -> None:
69
+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
70
+ sock.settimeout(self.timeout)
71
+ sock.connect(self._path)
72
+ self.sock = sock
73
+
74
+
75
+ class Engine:
76
+ """One connection to the Docker API. Use it as a context manager."""
77
+
78
+ def __init__(self, host: DockerHost | None = None, timeout: float = 120.0) -> None:
79
+ """Open nothing yet; the first request connects."""
80
+ self.host = host or DockerHost.from_env(
81
+ os.environ.get("DOCKER_HOST"), os.environ.get("SERVEX_HOST")
82
+ )
83
+ if self.host.kind == "unix":
84
+ self._conn: http.client.HTTPConnection = _UnixConnection(self.host.address, timeout)
85
+ else:
86
+ self._conn = http.client.HTTPConnection(
87
+ self.host.address, self.host.port, timeout=timeout
88
+ )
89
+
90
+ def __enter__(self) -> Self:
91
+ """Return the engine."""
92
+ return self
93
+
94
+ def __exit__(
95
+ self,
96
+ exc_type: type[BaseException] | None,
97
+ exc: BaseException | None,
98
+ tb: TracebackType | None,
99
+ ) -> None:
100
+ """Close the connection."""
101
+ self._conn.close()
102
+
103
+ def _send(
104
+ self, method: str, path: str, query: Mapping[str, str] | None, body: object
105
+ ) -> http.client.HTTPResponse:
106
+ url = API + path + (f"?{urlencode(query)}" if query else "")
107
+ payload = None if body is None else json.dumps(body).encode()
108
+ headers = {"Content-Type": "application/json"} if payload is not None else {}
109
+ try:
110
+ self._conn.request(method, url, body=payload, headers=headers)
111
+ except (FileNotFoundError, ConnectionRefusedError) as err:
112
+ where = (
113
+ self.host.address
114
+ if self.host.kind == "unix"
115
+ else f"{self.host.address}:{self.host.port}"
116
+ )
117
+ raise DockerUnavailable(f"cannot reach the Docker API at {where}: {err}") from err
118
+ return self._conn.getresponse()
119
+
120
+ def call(
121
+ self,
122
+ method: str,
123
+ path: str,
124
+ *,
125
+ query: Mapping[str, str] | None = None,
126
+ body: object = None,
127
+ ) -> Any: # noqa: ANN401 # JSON of many shapes
128
+ """Send one request and return the decoded JSON body (None when empty).
129
+
130
+ Raises:
131
+ DockerError: The status is 400 or above.
132
+ """
133
+ response = self._send(method, path, query, body)
134
+ data = response.read()
135
+ if response.status >= 400: # noqa: PLR2004
136
+ message = data.decode(errors="replace")
137
+ with contextlib.suppress(ValueError):
138
+ message = json.loads(data).get("message", message)
139
+ raise docker_error(response.status, message)
140
+ return json.loads(data) if data else None
141
+
142
+ def stream_json(self, method: str, path: str, *, query: Mapping[str, str]) -> Iterator[Any]:
143
+ """Send one request and yield each JSON line of a streamed body, as it arrives.
144
+
145
+ Used for image pulls, so progress is never held in memory as a whole.
146
+
147
+ Raises:
148
+ DockerError: The status is 400 or above, or a streamed line carries ``error``.
149
+ """
150
+ response = self._send(method, path, query, None)
151
+ if response.status >= 400: # noqa: PLR2004
152
+ raise docker_error(response.status, response.read().decode(errors="replace"))
153
+ for line in response:
154
+ if line.strip():
155
+ item = json.loads(line)
156
+ if "error" in item:
157
+ raise DockerError(500, str(item["error"]))
158
+ yield item
159
+
160
+ def raw(self, method: str, path: str, *, query: Mapping[str, str]) -> bytes:
161
+ """Send one request and return the raw body. Raises ``DockerError`` on 400 or above."""
162
+ response = self._send(method, path, query, None)
163
+ data = response.read()
164
+ if response.status >= 400: # noqa: PLR2004
165
+ raise docker_error(response.status, data.decode(errors="replace"))
166
+ return data
167
+
168
+
169
+ def demux_logs(data: bytes) -> str:
170
+ """Return the text of a non-TTY log stream, dropping Docker's 8-byte frame headers.
171
+
172
+ Each frame is: stream type (1 byte), 3 zero bytes, payload length (4 bytes, big
173
+ endian), payload. Data that does not start with a valid header is returned as is.
174
+ """
175
+ out: list[bytes] = []
176
+ offset = 0
177
+ while offset + 8 <= len(data):
178
+ kind, length = struct.unpack(">B3xI", data[offset : offset + 8])
179
+ if kind not in {0, 1, 2}:
180
+ return data.decode(errors="replace")
181
+ out.append(data[offset + 8 : offset + 8 + length])
182
+ offset += 8 + length
183
+ return b"".join(out).decode(errors="replace")
@@ -0,0 +1,65 @@
1
+ """Exceptions. Each one also subclasses the built-in it resembles, so plain ``except`` works.
2
+
3
+ ``except ServexError`` catches everything this library raises. ``except TimeoutError``
4
+ catches ``NotReady``; ``except LookupError`` catches ``NotFound``; ``except ConnectionError``
5
+ catches ``DockerUnavailable``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+
11
+ class ServexError(Exception):
12
+ """Base class of every error pytest-servex raises."""
13
+
14
+
15
+ class DockerUnavailable(ServexError, ConnectionError): # noqa: N818 # reads as a state, like TimeoutError
16
+ """The Docker API socket is missing or refuses connections (is the daemon running?)."""
17
+
18
+
19
+ class DockerError(ServexError):
20
+ """The Docker API answered with an error status.
21
+
22
+ Args:
23
+ status: The HTTP status code.
24
+ message: Docker's own error message.
25
+ """
26
+
27
+ def __init__(self, status: int, message: str) -> None:
28
+ """Keep the status and Docker's message."""
29
+ super().__init__(f"Docker API {status}: {message}")
30
+ self.status = status
31
+ self.message = message
32
+
33
+
34
+ class NotFound(DockerError, LookupError): # noqa: N818
35
+ """Docker has no such container, network, volume, or image (HTTP 404)."""
36
+
37
+
38
+ class Conflict(DockerError): # noqa: N818 # pairs with NotFound
39
+ """The name is taken, or the object is still in use (HTTP 409)."""
40
+
41
+
42
+ class ImageNotFound(NotFound):
43
+ """The image is not local and the pull policy forbids pulling it, or the pull failed."""
44
+
45
+
46
+ class NotReady(ServexError, TimeoutError): # noqa: N818
47
+ """A container did not pass its ``ready`` check: it timed out, or it exited first.
48
+
49
+ The container is removed before this is raised. ``logs`` holds its last lines.
50
+ """
51
+
52
+ def __init__(self, image: str, reason: str, logs: str) -> None:
53
+ """Keep the image and the container's last log lines."""
54
+ super().__init__(f"{image} not ready: {reason}. Last logs:\n{logs}")
55
+ self.image = image
56
+ self.logs = logs
57
+
58
+
59
+ def docker_error(status: int, message: str) -> DockerError:
60
+ """Return the most specific ``DockerError`` subclass for an HTTP status."""
61
+ if status == 404: # noqa: PLR2004
62
+ return NotFound(status, message)
63
+ if status == 409: # noqa: PLR2004
64
+ return Conflict(status, message)
65
+ return DockerError(status, message)
@@ -0,0 +1,325 @@
1
+ """Start and stop networks, volumes, and containers: ``start``, ``stop``, ``running``.
2
+
3
+ Starting a container costs three API requests on one connection (create, start,
4
+ inspect), plus a streamed pull the first time an image is missing. Every object carries
5
+ labels with the run's pid and host, so ``remove_stale`` can delete what a killed run left.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import os
12
+ import socket
13
+ import time
14
+ from collections.abc import Generator
15
+ from contextlib import AbstractContextManager, contextmanager
16
+ from typing import Any, overload
17
+
18
+ from pytest_servex._engine import Engine, demux_logs
19
+ from pytest_servex.errors import DockerError, ImageNotFound, NotFound, NotReady
20
+ from pytest_servex.spec import (
21
+ Container,
22
+ Mount,
23
+ Network,
24
+ RunningContainer,
25
+ RunningNetwork,
26
+ RunningVolume,
27
+ Tmpfs,
28
+ Volume,
29
+ )
30
+
31
+ LABEL = "pytest-servex"
32
+ LABEL_PID = "pytest-servex.pid"
33
+ LABEL_HOST = "pytest-servex.host"
34
+
35
+ type Spec = Network | Volume | Container
36
+ type Running = RunningNetwork | RunningVolume | RunningContainer
37
+
38
+
39
+ def run_labels() -> dict[str, str]:
40
+ """Return the labels that tie an object to this process on this host."""
41
+ return {LABEL: "1", LABEL_PID: str(os.getpid()), LABEL_HOST: socket.gethostname()}
42
+
43
+
44
+ def is_stale(labels: dict[str, str], host: str, *, pid_alive: bool) -> bool:
45
+ """Return True if a labelled object belongs to a run on ``host`` whose pid has died.
46
+
47
+ Objects from another host are never stale here: their pid says nothing about this machine.
48
+ """
49
+ return labels.get(LABEL_HOST) == host and not pid_alive
50
+
51
+
52
+ def container_create_body(
53
+ spec: Container, labels: dict[str, str], publish_ip: str
54
+ ) -> dict[str, Any]:
55
+ """Return the JSON body of ``POST /containers/create`` for ``spec``.
56
+
57
+ Only the first network is joined at create time (API 1.41 allows one); ``start``
58
+ connects the others before the container starts.
59
+ """
60
+ host_config: dict[str, Any] = {
61
+ "PortBindings": {f"{p}/tcp": [{"HostIp": publish_ip, "HostPort": ""}] for p in spec.ports},
62
+ "Tmpfs": {m.target: m.options for m in spec.mounts if isinstance(m, Tmpfs)},
63
+ "Mounts": [
64
+ {"Type": "volume", "Source": m.volume.name, "Target": m.target}
65
+ for m in spec.mounts
66
+ if isinstance(m, Mount)
67
+ ],
68
+ }
69
+ body: dict[str, Any] = {
70
+ "Image": spec.image,
71
+ "Env": [f"{k}={v}" for k, v in spec.env.items()],
72
+ "Labels": labels,
73
+ "ExposedPorts": {f"{p}/tcp": {} for p in spec.ports},
74
+ "HostConfig": host_config,
75
+ }
76
+ if spec.command:
77
+ body["Cmd"] = list(spec.command)
78
+ if spec.entrypoint:
79
+ body["Entrypoint"] = list(spec.entrypoint)
80
+ if spec.user:
81
+ body["User"] = spec.user
82
+ if spec.working_dir:
83
+ body["WorkingDir"] = spec.working_dir
84
+ if spec.memory is not None:
85
+ host_config["Memory"] = spec.memory
86
+ if spec.shm_size is not None:
87
+ host_config["ShmSize"] = spec.shm_size
88
+ host_config.update(spec.host_config)
89
+ if spec.networks:
90
+ first = spec.networks[0].name
91
+ host_config["NetworkMode"] = first
92
+ body["NetworkingConfig"] = {"EndpointsConfig": {first: _endpoint_config(spec)}}
93
+ return body
94
+
95
+
96
+ def _endpoint_config(spec: Container) -> dict[str, Any]:
97
+ return {"Aliases": [spec.alias]} if spec.alias else {}
98
+
99
+
100
+ def split_image(image: str) -> tuple[str, str]:
101
+ """Split ``repo[:tag]`` into repo and tag (default ``latest``). A registry port is not a tag."""
102
+ repo, sep, tag = image.rpartition(":")
103
+ if not sep or "/" in tag:
104
+ return image, "latest"
105
+ return repo, tag
106
+
107
+
108
+ def _pull(engine: Engine, image: str) -> None:
109
+ repo, tag = split_image(image)
110
+ try:
111
+ for _ in engine.stream_json(
112
+ "POST", "/images/create", query={"fromImage": repo, "tag": tag}
113
+ ):
114
+ pass # progress lines are read and dropped one by one
115
+ except DockerError as err:
116
+ raise ImageNotFound(err.status, f"pull of {image} failed: {err.message}") from err
117
+
118
+
119
+ def _create_container(engine: Engine, spec: Container) -> str:
120
+ publish_ip = "127.0.0.1" if engine.host.kind == "unix" else ""
121
+ body = container_create_body(spec, run_labels(), publish_ip)
122
+ if spec.pull == "always":
123
+ _pull(engine, spec.image)
124
+ try:
125
+ created = engine.call("POST", "/containers/create", body=body)
126
+ except NotFound as err:
127
+ if spec.pull != "missing":
128
+ raise ImageNotFound(
129
+ err.status, f"{spec.image} is not local and pull={spec.pull!r}"
130
+ ) from err
131
+ _pull(engine, spec.image)
132
+ created = engine.call("POST", "/containers/create", body=body)
133
+ return str(created["Id"])
134
+
135
+
136
+ def _start_container(engine: Engine, spec: Container, timeout: float) -> RunningContainer:
137
+ container_id = _create_container(engine, spec)
138
+ try:
139
+ for network in spec.networks[1:]:
140
+ engine.call(
141
+ "POST",
142
+ f"/networks/{network.name}/connect",
143
+ body={"Container": container_id, "EndpointConfig": _endpoint_config(spec)},
144
+ )
145
+ engine.call("POST", f"/containers/{container_id}/start")
146
+ info = engine.call("GET", f"/containers/{container_id}/json")
147
+ bound: dict[str, list[dict[str, str]]] = info["NetworkSettings"]["Ports"] or {}
148
+ ports = tuple(sorted((p, int(bound[f"{p}/tcp"][0]["HostPort"])) for p in spec.ports))
149
+ started = RunningContainer(
150
+ id=container_id, spec=spec, host=engine.host.published_host, ports=ports
151
+ )
152
+ _wait_ready(engine, started, timeout)
153
+ except BaseException:
154
+ _remove_container(engine, container_id)
155
+ raise
156
+ return started
157
+
158
+
159
+ POLL = 0.05 # seconds between ready checks
160
+ STATE_EVERY = 20 # ask Docker whether the container still runs every 20 polls (1 s)
161
+
162
+
163
+ def _wait_ready(engine: Engine, started: RunningContainer, timeout: float) -> None:
164
+ """Poll ``ready`` until True. Fail fast if the container exits, instead of waiting."""
165
+ deadline = time.monotonic() + timeout
166
+ polls = 0
167
+ while not started.spec.ready(started):
168
+ polls += 1
169
+ reason = ""
170
+ if time.monotonic() > deadline:
171
+ reason = f"no success after {timeout:g}s"
172
+ elif polls % STATE_EVERY == 0:
173
+ state = engine.call("GET", f"/containers/{started.id}/json")["State"]
174
+ if not state["Running"]:
175
+ reason = f"container exited with code {state['ExitCode']}"
176
+ if reason:
177
+ raw = engine.raw(
178
+ "GET",
179
+ f"/containers/{started.id}/logs",
180
+ query={"stdout": "1", "stderr": "1", "tail": "40"},
181
+ )
182
+ raise NotReady(started.spec.image, reason, demux_logs(raw))
183
+ time.sleep(POLL)
184
+
185
+
186
+ def _remove_container(engine: Engine, container_id: str) -> None:
187
+ # v=1 also removes anonymous volumes, so nothing is left on disk.
188
+ with contextlib.suppress(NotFound):
189
+ engine.call("DELETE", f"/containers/{container_id}", query={"force": "1", "v": "1"})
190
+
191
+
192
+ @overload
193
+ def start(spec: Network, *, timeout: float = ...) -> RunningNetwork: ...
194
+ @overload
195
+ def start(spec: Volume, *, timeout: float = ...) -> RunningVolume: ...
196
+ @overload
197
+ def start(spec: Container, *, timeout: float = ...) -> RunningContainer: ...
198
+ def start(spec: Spec, *, timeout: float = 60.0) -> Running:
199
+ """Create ``spec`` in Docker and return what was started.
200
+
201
+ A container is started and waited on until ``spec.ready`` is True. Its networks and
202
+ volumes must exist already: start them first.
203
+
204
+ Raises:
205
+ NotReady: The container was not ready within ``timeout`` seconds. It is removed
206
+ before raising, and the error carries its last 40 log lines.
207
+ ImageNotFound: The image is missing and the pull policy or the pull failed.
208
+ Conflict: A network or volume with that name exists already.
209
+ DockerUnavailable: The Docker API cannot be reached.
210
+ """
211
+ return _start(spec, timeout)
212
+
213
+
214
+ def _start(spec: Spec, timeout: float) -> Running:
215
+ with Engine() as engine:
216
+ match spec:
217
+ case Network():
218
+ body = {"Name": spec.name, "Driver": "bridge", "Labels": run_labels()}
219
+ created = engine.call("POST", "/networks/create", body=body)
220
+ return RunningNetwork(id=str(created["Id"]), spec=spec)
221
+ case Volume():
222
+ engine.call(
223
+ "POST", "/volumes/create", body={"Name": spec.name, "Labels": run_labels()}
224
+ )
225
+ return RunningVolume(spec=spec)
226
+ case Container():
227
+ return _start_container(engine, spec, timeout)
228
+
229
+
230
+ def stop(running: Running) -> None:
231
+ """Remove what ``start`` created. Something already gone is fine.
232
+
233
+ A container is removed with its anonymous volumes. A network or volume still in use
234
+ by a container raises ``Conflict``: stop containers first.
235
+ """
236
+ with Engine() as engine:
237
+ match running:
238
+ case RunningContainer():
239
+ _remove_container(engine, running.id)
240
+ case RunningNetwork():
241
+ _delete(engine, f"/networks/{running.id}")
242
+ case RunningVolume():
243
+ _delete(engine, f"/volumes/{running.spec.name}")
244
+
245
+
246
+ def _delete(engine: Engine, path: str) -> None:
247
+ with contextlib.suppress(NotFound):
248
+ engine.call("DELETE", path)
249
+
250
+
251
+ @overload
252
+ def running(spec: Network, *, timeout: float = ...) -> AbstractContextManager[RunningNetwork]: ...
253
+ @overload
254
+ def running(spec: Volume, *, timeout: float = ...) -> AbstractContextManager[RunningVolume]: ...
255
+ @overload
256
+ def running(
257
+ spec: Container, *, timeout: float = ...
258
+ ) -> AbstractContextManager[RunningContainer]: ...
259
+ def running(spec: Spec, *, timeout: float = 60.0) -> AbstractContextManager[Running]:
260
+ """Start ``spec`` on enter and stop it on exit, even when the block raises.
261
+
262
+ Nest them in dependency order and they stop in reverse::
263
+
264
+ with running(net), running(pg) as started:
265
+ started.endpoint(5432)
266
+ """
267
+ return _running(spec, timeout)
268
+
269
+
270
+ @contextmanager
271
+ def _running(spec: Spec, timeout: float) -> Generator[Running]:
272
+ started = _start(spec, timeout)
273
+ try:
274
+ yield started
275
+ finally:
276
+ stop(started)
277
+
278
+
279
+ def _pid_alive(pid: int) -> bool:
280
+ try:
281
+ os.kill(pid, 0)
282
+ except ProcessLookupError:
283
+ return False
284
+ except PermissionError:
285
+ return True # exists, owned by another user
286
+ return True
287
+
288
+
289
+ def _stale(labels: dict[str, str] | None, host: str) -> bool:
290
+ labels = labels or {}
291
+ pid = labels.get(LABEL_PID, "")
292
+ return is_stale(labels, host, pid_alive=pid.isdigit() and _pid_alive(int(pid)))
293
+
294
+
295
+ def remove_stale() -> int:
296
+ """Remove the containers, networks, and volumes of killed runs on this host.
297
+
298
+ A normal run removes its own objects. A run killed with SIGKILL cannot, so the next
299
+ run does it here. This replaces the Ryuk container testcontainers runs alongside each
300
+ session. Returns how many objects were removed.
301
+ """
302
+ host = socket.gethostname()
303
+ filters = {"filters": f'{{"label": ["{LABEL}"]}}'}
304
+ removed = 0
305
+ with Engine() as engine:
306
+ containers: list[dict[str, Any]] = engine.call(
307
+ "GET", "/containers/json", query={"all": "1", **filters}
308
+ )
309
+ for item in containers:
310
+ if _stale(item.get("Labels"), host):
311
+ _remove_container(engine, item["Id"])
312
+ removed += 1
313
+ networks: list[dict[str, Any]] = engine.call("GET", "/networks", query=filters)
314
+ for item in networks:
315
+ if _stale(item.get("Labels"), host):
316
+ _delete(engine, f"/networks/{item['Id']}")
317
+ removed += 1
318
+ volumes: list[dict[str, Any]] = (
319
+ engine.call("GET", "/volumes", query=filters)["Volumes"] or []
320
+ )
321
+ for item in volumes:
322
+ if _stale(item.get("Labels"), host):
323
+ _delete(engine, f"/volumes/{item['Name']}")
324
+ removed += 1
325
+ return removed
@@ -0,0 +1,112 @@
1
+ """The pytest plugin: Postgres fixtures, one server per run and one database per worker.
2
+
3
+ Fixture graph::
4
+
5
+ servex_postgres_server (session, once per run: container or SERVEX_POSTGRES_URL)
6
+ -> servex_postgres_template (session, once per run: runs servex_postgres_prepare)
7
+ -> servex_postgres (session, once per worker: needs worker_id)
8
+
9
+ Under pytest-parallex the first two are built in the controller before the fork, so one
10
+ container and one template serve every worker. ``servex_postgres`` requests
11
+ ``worker_id``, which is how parallex knows to build it in each worker instead.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ from collections.abc import Callable, Iterator
18
+
19
+ import pytest
20
+
21
+ from pytest_servex import postgres
22
+ from pytest_servex.lifecycle import remove_stale, running
23
+ from pytest_servex.postgres import PostgresDatabase, PostgresServer
24
+
25
+ ENV_URL = "SERVEX_POSTGRES_URL"
26
+ ENV_IMAGE = "SERVEX_POSTGRES_IMAGE"
27
+ TEMPLATE_NAME = "servex_template"
28
+ WORKER_PREFIX = "servex"
29
+
30
+ Prepare = Callable[[str], None]
31
+
32
+
33
+ class _MainWorkerId:
34
+ """Provides ``worker_id`` = ``"main"`` when neither pytest-xdist nor pytest-parallex does."""
35
+
36
+ @pytest.fixture(scope="session")
37
+ def worker_id(self) -> str:
38
+ """The worker name; always ``"main"`` in a serial run without a parallel plugin."""
39
+ return "main"
40
+
41
+
42
+ @pytest.hookimpl(trylast=True)
43
+ def pytest_configure(config: pytest.Config) -> None:
44
+ """Register a fallback ``worker_id`` fixture if no parallel plugin provides one.
45
+
46
+ ``trylast`` runs this after pytest-parallex's own ``pytest_configure``, which is where
47
+ parallex registers its ``worker_id``.
48
+ """
49
+ has_worker_id = config.pluginmanager.hasplugin("xdist") or config.pluginmanager.hasplugin(
50
+ "parallex-worker-id"
51
+ )
52
+ if not has_worker_id:
53
+ config.pluginmanager.register(_MainWorkerId(), "servex-worker-id")
54
+
55
+
56
+ @pytest.fixture(scope="session")
57
+ def servex_postgres_server() -> Iterator[PostgresServer]:
58
+ """The run's Postgres server.
59
+
60
+ If ``SERVEX_POSTGRES_URL`` is set (for example in CI, with a Postgres service), that
61
+ server is used and nothing is started. The URL must reach a database the user may
62
+ create databases from. Otherwise a container is started from ``SERVEX_POSTGRES_IMAGE``
63
+ (default ``postgres:17-alpine``) and removed at the end of the run.
64
+ """
65
+ if url := os.environ.get(ENV_URL):
66
+ yield PostgresServer(url=url)
67
+ return
68
+ service = postgres.POSTGRES
69
+ if image := os.environ.get(ENV_IMAGE):
70
+ service = postgres.postgres_image(image)
71
+ remove_stale()
72
+ with running(service) as started:
73
+ yield PostgresServer(url=postgres.admin_url(started.endpoint(postgres.PORT)))
74
+
75
+
76
+ @pytest.fixture(scope="session")
77
+ def servex_postgres_prepare() -> Prepare | None:
78
+ """Override this to fill the template database: run migrations, insert seed rows.
79
+
80
+ Return a function that takes the template's URL. It runs once per run, before any
81
+ worker database is cloned. Close every connection it opens: Postgres refuses to copy a
82
+ template with open connections. The default returns None, which leaves the template
83
+ empty.
84
+ """
85
+ return None
86
+
87
+
88
+ @pytest.fixture(scope="session")
89
+ def servex_postgres_template(
90
+ servex_postgres_server: PostgresServer,
91
+ servex_postgres_prepare: Prepare | None,
92
+ ) -> str:
93
+ """The name of the template database, built once per run."""
94
+ template = postgres.create_empty(servex_postgres_server, TEMPLATE_NAME)
95
+ if servex_postgres_prepare is not None:
96
+ servex_postgres_prepare(template.url)
97
+ return template.name
98
+
99
+
100
+ @pytest.fixture(scope="session")
101
+ def servex_postgres(
102
+ servex_postgres_server: PostgresServer,
103
+ servex_postgres_template: str,
104
+ worker_id: str,
105
+ ) -> Iterator[PostgresDatabase]:
106
+ """This worker's own database, a copy of the template. Dropped when the worker ends."""
107
+ name = postgres.worker_database_name(WORKER_PREFIX, worker_id)
108
+ database = postgres.clone(servex_postgres_server, servex_postgres_template, name)
109
+ try:
110
+ yield database
111
+ finally:
112
+ postgres.drop(servex_postgres_server, name)
@@ -0,0 +1,171 @@
1
+ """Postgres: the service definition, a migrated template database, and a clone per worker.
2
+
3
+ The template is built once per run (migrations and seed data go in here). Each worker
4
+ then gets its own database with ``CREATE DATABASE ... TEMPLATE``, which copies the
5
+ template's files instead of replaying migrations.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from dataclasses import dataclass, replace
12
+ from typing import Any
13
+ from urllib.parse import quote, urlsplit, urlunsplit
14
+
15
+ import psycopg
16
+ from psycopg import sql
17
+
18
+ from pytest_servex.spec import Container, Endpoint, RunningContainer, Tmpfs
19
+
20
+ USER = "servex"
21
+ PASSWORD = "servex" # noqa: S105 # a throwaway container on 127.0.0.1
22
+ ADMIN_DATABASE = "postgres"
23
+
24
+ _IDENTIFIER = re.compile(r"[a-z_][a-z0-9_]{0,62}")
25
+
26
+
27
+ PORT = 5432
28
+ FIRST_MAJOR_WITH_NEW_DATA_PATH = 18
29
+
30
+
31
+ def _ready(started: RunningContainer) -> bool:
32
+ """True once Postgres answers a query over TCP.
33
+
34
+ The image runs ``initdb`` with a temporary server that does not listen on TCP, so a
35
+ TCP connection only succeeds once the real server is up.
36
+ """
37
+ try:
38
+ with psycopg.connect(admin_url(started.endpoint(PORT)), connect_timeout=1) as conn:
39
+ conn.execute("SELECT 1")
40
+ except psycopg.OperationalError:
41
+ return False
42
+ return True
43
+
44
+
45
+ POSTGRES = Container(
46
+ image="postgres:17-alpine",
47
+ ports=(PORT,),
48
+ ready=_ready,
49
+ env={"POSTGRES_USER": USER, "POSTGRES_PASSWORD": PASSWORD},
50
+ # Durability settings off: test data never needs to survive a crash.
51
+ command=(
52
+ "postgres",
53
+ "-c",
54
+ "fsync=off",
55
+ "-c",
56
+ "synchronous_commit=off",
57
+ "-c",
58
+ "full_page_writes=off",
59
+ ),
60
+ mounts=(Tmpfs("/var/lib/postgresql/data"),),
61
+ )
62
+
63
+
64
+ def admin_url(endpoint: Endpoint) -> str:
65
+ """Return the libpq URL of the ``postgres`` database on a servex container."""
66
+ return f"postgresql://{USER}:{quote(PASSWORD)}@{endpoint.host}:{endpoint.port}/{ADMIN_DATABASE}"
67
+
68
+
69
+ def with_database(url: str, database: str) -> str:
70
+ """Return ``url`` pointing at ``database`` instead, keeping credentials and query."""
71
+ parts = urlsplit(url)
72
+ return urlunsplit(parts._replace(path=f"/{database}"))
73
+
74
+
75
+ def check_identifier(name: str) -> str:
76
+ """Return ``name`` if it is a safe unquoted Postgres identifier, else raise ValueError.
77
+
78
+ Names are quoted with ``psycopg.sql.Identifier``. The rule still refuses uppercase and
79
+ punctuation, so the name a user passes is the name ``psql`` shows, with no quoting.
80
+ """
81
+ if not _IDENTIFIER.fullmatch(name):
82
+ raise ValueError(f"not a safe database name: {name!r} (use [a-z_][a-z0-9_]*, max 63)")
83
+ return name
84
+
85
+
86
+ @dataclass(frozen=True)
87
+ class PostgresServer:
88
+ """A Postgres server for this run, as a URL to its admin (``postgres``) database.
89
+
90
+ Only strings: safe to hand to forked or spawned workers.
91
+ """
92
+
93
+ url: str
94
+
95
+ def database_url(self, database: str) -> str:
96
+ """Return the URL of ``database`` on this server."""
97
+ return with_database(self.url, database)
98
+
99
+
100
+ @dataclass(frozen=True)
101
+ class PostgresDatabase:
102
+ """One database on the run's server, owned by one worker."""
103
+
104
+ name: str
105
+ url: str
106
+
107
+ def sqlalchemy_url(self, driver: str = "psycopg") -> str:
108
+ """Return ``url`` with a SQLAlchemy driver in the scheme (``postgresql+psycopg://``)."""
109
+ return re.sub(r"^postgres(ql)?://", f"postgresql+{driver}://", self.url)
110
+
111
+
112
+ def _terminate_and_drop(conn: psycopg.Connection[Any], name: str) -> None:
113
+ conn.execute(
114
+ "SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
115
+ "WHERE datname = %s AND pid <> pg_backend_pid()",
116
+ (name,),
117
+ )
118
+ conn.execute(sql.SQL("DROP DATABASE IF EXISTS {}").format(sql.Identifier(name)))
119
+
120
+
121
+ def create_empty(server: PostgresServer, name: str) -> PostgresDatabase:
122
+ """Create (or recreate) an empty database ``name`` and return it."""
123
+ check_identifier(name)
124
+ with psycopg.connect(server.url, autocommit=True) as conn:
125
+ _terminate_and_drop(conn, name)
126
+ conn.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(name)))
127
+ return PostgresDatabase(name=name, url=server.database_url(name))
128
+
129
+
130
+ def clone(server: PostgresServer, template: str, name: str) -> PostgresDatabase:
131
+ """Create (or recreate) database ``name`` as a copy of database ``template``.
132
+
133
+ Postgres refuses to copy a template that has open connections, so close every
134
+ connection to the template before calling this.
135
+ """
136
+ check_identifier(template)
137
+ check_identifier(name)
138
+ with psycopg.connect(server.url, autocommit=True) as conn:
139
+ _terminate_and_drop(conn, name)
140
+ conn.execute(
141
+ sql.SQL("CREATE DATABASE {} TEMPLATE {}").format(
142
+ sql.Identifier(name), sql.Identifier(template)
143
+ )
144
+ )
145
+ return PostgresDatabase(name=name, url=server.database_url(name))
146
+
147
+
148
+ def drop(server: PostgresServer, name: str) -> None:
149
+ """Drop database ``name``, closing its open connections first. Missing is fine."""
150
+ check_identifier(name)
151
+ with psycopg.connect(server.url, autocommit=True) as conn:
152
+ _terminate_and_drop(conn, name)
153
+
154
+
155
+ def worker_database_name(prefix: str, worker_id: str) -> str:
156
+ """Return the database name for one worker (``servex_f0``, ``servex_gw1``, ``servex_main``)."""
157
+ safe = re.sub(r"[^a-z0-9_]", "_", worker_id.lower())
158
+ return check_identifier(f"{prefix}_{safe}")
159
+
160
+
161
+ def postgres_image(image: str) -> Container:
162
+ """Return the Postgres service with another image, for example ``postgres:18``.
163
+
164
+ Postgres 18 images keep data under ``/var/lib/postgresql`` instead of
165
+ ``/var/lib/postgresql/data``, so the tmpfs mount follows the major version.
166
+ """
167
+ tag = image.rsplit(":", 1)[-1] if ":" in image else ""
168
+ major = tag.split(".", 1)[0].split("-", 1)[0]
169
+ new_layout = major.isdigit() and int(major) >= FIRST_MAJOR_WITH_NEW_DATA_PATH
170
+ data = "/var/lib/postgresql" if new_layout else "/var/lib/postgresql/data"
171
+ return replace(POSTGRES, image=image, mounts=(Tmpfs(data),))
pytest_servex/py.typed ADDED
File without changes
pytest_servex/spec.py ADDED
@@ -0,0 +1,170 @@
1
+ """What to start (specs) and what was started (results). All frozen dataclasses.
2
+
3
+ A spec says what you want: a ``Network``, a ``Volume``, a ``Container``. ``start`` turns a
4
+ spec into a result (``RunningNetwork``, ``RunningVolume``, ``RunningContainer``) that holds
5
+ only ids and addresses. Change a spec with ``dataclasses.replace``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Callable, Mapping
11
+ from dataclasses import dataclass, field
12
+ from types import MappingProxyType
13
+ from typing import Any, Literal
14
+
15
+ type Pull = Literal["missing", "always", "never"]
16
+
17
+
18
+ def _freeze(env: Mapping[str, str]) -> Mapping[str, str]:
19
+ return MappingProxyType(dict(sorted(env.items())))
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class Endpoint:
24
+ """A host and port where a started container accepts connections."""
25
+
26
+ host: str
27
+ port: int
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Network:
32
+ """A user-defined bridge network. Containers on it reach each other by alias."""
33
+
34
+ name: str
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class Volume:
39
+ """A named Docker volume. Data survives the container, not the end of the run."""
40
+
41
+ name: str
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class Mount:
46
+ """Mount ``volume`` at ``target`` inside a container."""
47
+
48
+ volume: Volume
49
+ target: str
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class Tmpfs:
54
+ """A tmpfs at ``target`` inside a container: data in memory, nothing written to disk.
55
+
56
+ ``options`` are mount options, for example ``"size=256m"``.
57
+ """
58
+
59
+ target: str
60
+ options: str = ""
61
+
62
+
63
+ def _never_ready(_: RunningContainer) -> bool:
64
+ return True
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class Container:
69
+ """A container to start.
70
+
71
+ Args:
72
+ image: Image reference. Pin a tag; it is pulled only when missing.
73
+ ports: Container ports to publish on random host ports.
74
+ env: Environment variables. Stored sorted and read-only.
75
+ command: Replaces the image's default command when not empty.
76
+ mounts: ``Tmpfs`` and ``Mount`` entries.
77
+ networks: Networks to join. Start them first.
78
+ alias: The DNS name other containers on the same networks use.
79
+ ready: Returns True once the container accepts real work. Called in a loop until
80
+ True or until the start timeout. Return False for "not yet"; do not raise.
81
+ The default treats a started container as ready.
82
+ pull: When to pull the image, with the ``docker run --pull`` values: ``"missing"``
83
+ (default), ``"always"``, ``"never"`` (raise ``ImageNotFound`` if not local).
84
+ entrypoint: Replaces the image's entrypoint when not empty.
85
+ user: ``"uid[:gid]"`` or a user name to run as.
86
+ working_dir: The working directory inside the container.
87
+ memory: Memory limit in bytes.
88
+ shm_size: Size of ``/dev/shm`` in bytes (Postgres parallel queries use it).
89
+ host_config: Extra ``HostConfig`` fields of the Docker API, merged last, for
90
+ anything without its own field (for example ``{"CapAdd": ["NET_ADMIN"]}``).
91
+ """
92
+
93
+ image: str
94
+ ports: tuple[int, ...] = ()
95
+ env: Mapping[str, str] = field(default_factory=lambda: MappingProxyType({}))
96
+ command: tuple[str, ...] = ()
97
+ mounts: tuple[Tmpfs | Mount, ...] = ()
98
+ networks: tuple[Network, ...] = ()
99
+ alias: str = ""
100
+ ready: Callable[[RunningContainer], bool] = _never_ready
101
+ pull: Pull = "missing"
102
+ entrypoint: tuple[str, ...] = ()
103
+ user: str = ""
104
+ working_dir: str = ""
105
+ memory: int | None = None
106
+ shm_size: int | None = None
107
+ host_config: Mapping[str, Any] = field(default_factory=lambda: MappingProxyType({}))
108
+
109
+ def __post_init__(self) -> None:
110
+ """Freeze ``env`` and ``host_config`` so a spec cannot change after it is made."""
111
+ object.__setattr__(self, "env", _freeze(self.env))
112
+ object.__setattr__(self, "host_config", MappingProxyType(dict(self.host_config)))
113
+
114
+ def __hash__(self) -> int:
115
+ """Hash by value, with ``env`` as its sorted items."""
116
+ return hash(
117
+ (
118
+ self.image,
119
+ self.ports,
120
+ tuple(self.env.items()),
121
+ self.command,
122
+ self.mounts,
123
+ self.networks,
124
+ self.alias,
125
+ self.ready,
126
+ self.pull,
127
+ self.entrypoint,
128
+ self.user,
129
+ self.working_dir,
130
+ self.memory,
131
+ self.shm_size,
132
+ repr(sorted(self.host_config.items())), # values may be lists
133
+ )
134
+ )
135
+
136
+
137
+ @dataclass(frozen=True)
138
+ class RunningNetwork:
139
+ """A network that ``start`` created."""
140
+
141
+ id: str
142
+ spec: Network
143
+
144
+
145
+ @dataclass(frozen=True)
146
+ class RunningVolume:
147
+ """A volume that ``start`` created."""
148
+
149
+ spec: Volume
150
+
151
+
152
+ @dataclass(frozen=True)
153
+ class RunningContainer:
154
+ """A container that ``start`` created and started.
155
+
156
+ ``ports`` maps each container port to its published host port, as sorted pairs.
157
+ """
158
+
159
+ id: str
160
+ spec: Container
161
+ host: str
162
+ ports: tuple[tuple[int, int], ...]
163
+
164
+ def endpoint(self, port: int) -> Endpoint:
165
+ """Return where container ``port`` is reachable from the test process.
166
+
167
+ Raises:
168
+ KeyError: ``port`` was not in the spec's ``ports``.
169
+ """
170
+ return Endpoint(host=self.host, port=dict(self.ports)[port])
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.5
2
+ Name: pytest-servex
3
+ Version: 0.1.1
4
+ Summary: Pytest fixtures that start test services in Docker once per run and give each worker its own database.
5
+ Project-URL: Homepage, https://gitlab.com/cardona-oss/pytest-servex
6
+ Project-URL: Repository, https://gitlab.com/cardona-oss/pytest-servex
7
+ Project-URL: Documentation, https://cardona-oss.gitlab.io/pytest-servex/
8
+ Project-URL: Changelog, https://gitlab.com/cardona-oss/pytest-servex/-/blob/main/CHANGELOG.md
9
+ Project-URL: Issues, https://gitlab.com/cardona-oss/pytest-servex/-/issues
10
+ Author-email: Jorge Cardona <jorgeecardona@gmail.com>
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: docker,fixtures,parallel,postgres,pytest,testing
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Framework :: Pytest
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Software Development :: Testing
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.12
23
+ Requires-Dist: psycopg>=3.2
24
+ Requires-Dist: pytest>=8
25
+ Provides-Extra: docs
26
+ Requires-Dist: mkdocs-material>=9.5; extra == 'docs'
27
+ Requires-Dist: mkdocs>=1.6; extra == 'docs'
28
+ Requires-Dist: mkdocstrings[python]>=0.27; extra == 'docs'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # pytest-servex
32
+
33
+ [![pipeline status](https://gitlab.com/cardona-oss/pytest-servex/badges/main/pipeline.svg)](https://gitlab.com/cardona-oss/pytest-servex/-/pipelines)
34
+ [![PyPI version](https://img.shields.io/pypi/v/pytest-servex.svg)](https://pypi.org/project/pytest-servex/)
35
+ [![Python versions](https://img.shields.io/pypi/pyversions/pytest-servex.svg)](https://pypi.org/project/pytest-servex/)
36
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://gitlab.com/cardona-oss/pytest-servex/-/blob/main/LICENSE)
37
+
38
+ Pytest fixtures that start test services in Docker once per run and give each worker its own
39
+ database. Version 0.1 supports Postgres.
40
+
41
+ ## Install
42
+
43
+ ```bash
44
+ pip install pytest-servex "psycopg[binary]"
45
+ ```
46
+
47
+ Requires Python 3.12+ and a Docker daemon. Talks to the Docker API directly with the standard
48
+ library: no docker SDK, no requests.
49
+
50
+ ## Quickstart
51
+
52
+ Request `servex_postgres` in a test. It is a database of your own, on a container started once
53
+ for the run:
54
+
55
+ ```python
56
+ import psycopg
57
+
58
+
59
+ def test_insert(servex_postgres):
60
+ with psycopg.connect(servex_postgres.url) as conn:
61
+ conn.execute("CREATE TABLE t (x int)")
62
+ conn.execute("INSERT INTO t VALUES (1)")
63
+ ```
64
+
65
+ To run migrations once, override `servex_postgres_prepare` in `conftest.py`. Every worker
66
+ database starts as a copy of the result:
67
+
68
+ ```python
69
+ import subprocess
70
+
71
+ import pytest
72
+
73
+
74
+ @pytest.fixture(scope="session")
75
+ def servex_postgres_prepare():
76
+ def prepare(url: str) -> None:
77
+ subprocess.run(["alembic", "upgrade", "head"], env={"DATABASE_URL": url}, check=True)
78
+
79
+ return prepare
80
+ ```
81
+
82
+ ## How it works
83
+
84
+ 1. `servex_postgres_server` starts one Postgres container for the run, with `fsync` off and
85
+ data on tmpfs.
86
+ 2. `servex_postgres_template` creates the database `servex_template` and runs your prepare
87
+ function on it, once.
88
+ 3. `servex_postgres` copies the template into one database per worker
89
+ (`CREATE DATABASE servex_f0 TEMPLATE servex_template`). This copies files, so it takes
90
+ milliseconds instead of a migration run.
91
+
92
+ Under [pytest-parallex](https://pypi.org/project/pytest-parallex/) steps 1 and 2 run once in
93
+ the controller, before the fork. Under pytest-xdist each worker runs its own session, so each
94
+ worker starts its own container.
95
+
96
+ ## Outside pytest
97
+
98
+ Specs are frozen dataclasses. `running` starts one on enter and removes it on exit, so nested
99
+ blocks stop in reverse order:
100
+
101
+ ```python
102
+ from dataclasses import replace
103
+
104
+ from pytest_servex import POSTGRES, Network, running
105
+
106
+ net = Network("app")
107
+ pg = replace(POSTGRES, networks=(net,), alias="db", pull="never")
108
+
109
+ with running(net), running(pg) as started:
110
+ print(started.endpoint(5432)) # Endpoint(host='127.0.0.1', port=32771)
111
+ ```
112
+
113
+ Errors subclass the built-in they resemble, and all subclass `ServexError`:
114
+
115
+ | Error | Also a | When |
116
+ |---|---|---|
117
+ | `NotReady` | `TimeoutError` | The ready check timed out, or the container exited first. Has `.logs`. |
118
+ | `ImageNotFound` | `LookupError` | The image is missing and `pull="never"`, or the pull failed. |
119
+ | `NotFound` | `LookupError` | Docker has no such object (HTTP 404). |
120
+ | `Conflict` | | A name is taken, or a network or volume is still in use (HTTP 409). |
121
+ | `DockerUnavailable` | `ConnectionError` | The Docker socket is missing or refuses connections. |
122
+
123
+ ## Configuration
124
+
125
+ - `SERVEX_POSTGRES_URL`: use this server and start nothing (for example a CI service). It must
126
+ point at a database whose user may create databases.
127
+ - `SERVEX_POSTGRES_IMAGE`: the image to start. Default `postgres:17-alpine`.
128
+ - `DOCKER_HOST`: the Docker API, `unix://` or `tcp://`. Podman's Docker-compatible socket is
129
+ meant to work but is not tested yet.
130
+ - `SERVEX_HOST`: where tests connect to published ports, when that is not the `DOCKER_HOST`
131
+ address (for example `docker` with a GitLab `docker:dind` service).
132
+
133
+ ## Compared to testcontainers
134
+
135
+ - No Ryuk container. Containers carry labels with the run's pid. The next run removes the
136
+ containers of runs that were killed.
137
+ - No Docker client crosses a fork. Fixtures hand workers plain URL strings.
138
+ - A template database and one copy per worker are built in, not left to each `conftest.py`.
139
+
140
+ ## Links
141
+
142
+ - Documentation: https://cardona-oss.gitlab.io/pytest-servex/
143
+ - Source: https://gitlab.com/cardona-oss/pytest-servex
144
+ - Issues: https://gitlab.com/cardona-oss/pytest-servex/-/issues
145
+ - Changelog: https://gitlab.com/cardona-oss/pytest-servex/-/blob/main/CHANGELOG.md
146
+
147
+ ## License
148
+
149
+ MIT © 2026 Jorge Cardona.
@@ -0,0 +1,13 @@
1
+ pytest_servex/__init__.py,sha256=PkescgoezVHzNqknlavVHLd9p6nlBNi0fXOukvHxfdA,1127
2
+ pytest_servex/_engine.py,sha256=oROnd367qk6uXEFU-OyIZjqQGqQZ6eGYf1byU0H7Gwk,7287
3
+ pytest_servex/errors.py,sha256=2JzE-QSstJpVEWZpSa529JfM_rwPy5uOep_pkDChiU8,2304
4
+ pytest_servex/lifecycle.py,sha256=QRtyPtihphgaf7NYK28m0mF-XEG-MYsR7GQiR8ZmRVk,12071
5
+ pytest_servex/plugin.py,sha256=CTHvDl8ur9sii3tkj7wbztbB39k9SxKCD_ZRLtDgT_o,4138
6
+ pytest_servex/postgres.py,sha256=WgJ1dlxg9EuXAbJDwh7exlLiv2g1CpIsfH7YPRxceS8,6067
7
+ pytest_servex/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ pytest_servex/spec.py,sha256=MFY7W9sCMnmBQ7L1tVk_YU4kHgvfKCitDR8ztlE_lYw,5328
9
+ pytest_servex-0.1.1.dist-info/METADATA,sha256=Q8PQcvFeR6REYyyttfRIlpiA7o3T3vEtV0U-_h_K3r4,5840
10
+ pytest_servex-0.1.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
+ pytest_servex-0.1.1.dist-info/entry_points.txt,sha256=tfP2nm1jPtGFRami6E_1nSm9b7B-dZjVjH7LSlqnzgY,41
12
+ pytest_servex-0.1.1.dist-info/licenses/LICENSE,sha256=6dP7w8m4xJH1IQumkEnTTCY4BJO16jnKEG-xPIj9y90,1070
13
+ pytest_servex-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [pytest11]
2
+ servex = pytest_servex.plugin
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jorge Cardona
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.