|
| 1 | +# Copyright (c) 2025, PostgreSQL Global Development Group |
| 2 | + |
| 3 | +import contextlib |
| 4 | +import ctypes |
| 5 | +import platform |
| 6 | +import time |
| 7 | +from typing import Any, Callable, Dict |
| 8 | + |
| 9 | +import pytest |
| 10 | + |
| 11 | +from ._env import test_timeout_default |
| 12 | + |
| 13 | + |
| 14 | +@pytest.fixture |
| 15 | +def remaining_timeout(): |
| 16 | + """ |
| 17 | + This fixture provides a function that returns how much of the |
| 18 | + PG_TEST_TIMEOUT_DEFAULT remains for the current test, in fractional seconds. |
| 19 | + This value is never less than zero. |
| 20 | +
|
| 21 | + This fixture is per-test, so the deadline is also reset on a per-test basis. |
| 22 | + """ |
| 23 | + now = time.monotonic() |
| 24 | + deadline = now + test_timeout_default() |
| 25 | + |
| 26 | + return lambda: max(deadline - time.monotonic(), 0) |
| 27 | + |
| 28 | + |
| 29 | +class _PGconn(ctypes.Structure): |
| 30 | + pass |
| 31 | + |
| 32 | + |
| 33 | +class _PGresult(ctypes.Structure): |
| 34 | + pass |
| 35 | + |
| 36 | + |
| 37 | +_PGconn_p = ctypes.POINTER(_PGconn) |
| 38 | +_PGresult_p = ctypes.POINTER(_PGresult) |
| 39 | + |
| 40 | + |
| 41 | +@pytest.fixture(scope="session") |
| 42 | +def libpq_handle(): |
| 43 | + """ |
| 44 | + Loads a ctypes handle for libpq. Some common function prototypes are |
| 45 | + initialized for general use. |
| 46 | + """ |
| 47 | + system = platform.system() |
| 48 | + |
| 49 | + if system in ("Linux", "FreeBSD", "NetBSD", "OpenBSD"): |
| 50 | + name = "libpq.so.5" |
| 51 | + elif system == "Darwin": |
| 52 | + name = "libpq.5.dylib" |
| 53 | + elif system == "Windows": |
| 54 | + name = "libpq.dll" |
| 55 | + else: |
| 56 | + assert False, f"the libpq fixture must be updated for {system}" |
| 57 | + |
| 58 | + # XXX ctypes.CDLL() is a little stricter with load paths on Windows. The |
| 59 | + # preferred way around that is to know the absolute path to libpq.dll, but |
| 60 | + # that doesn't seem to mesh well with the current test infrastructure. For |
| 61 | + # now, enable "standard" LoadLibrary behavior. |
| 62 | + loadopts = {} |
| 63 | + if system == "Windows": |
| 64 | + loadopts["winmode"] = 0 |
| 65 | + |
| 66 | + lib = ctypes.CDLL(name, **loadopts) |
| 67 | + |
| 68 | + # |
| 69 | + # Function Prototypes |
| 70 | + # |
| 71 | + |
| 72 | + lib.PQconnectdb.restype = _PGconn_p |
| 73 | + lib.PQconnectdb.argtypes = [ctypes.c_char_p] |
| 74 | + |
| 75 | + lib.PQstatus.restype = ctypes.c_int |
| 76 | + lib.PQstatus.argtypes = [_PGconn_p] |
| 77 | + |
| 78 | + lib.PQexec.restype = _PGresult_p |
| 79 | + lib.PQexec.argtypes = [_PGconn_p, ctypes.c_char_p] |
| 80 | + |
| 81 | + lib.PQresultStatus.restype = ctypes.c_int |
| 82 | + lib.PQresultStatus.argtypes = [_PGresult_p] |
| 83 | + |
| 84 | + lib.PQclear.restype = None |
| 85 | + lib.PQclear.argtypes = [_PGresult_p] |
| 86 | + |
| 87 | + lib.PQerrorMessage.restype = ctypes.c_char_p |
| 88 | + lib.PQerrorMessage.argtypes = [_PGconn_p] |
| 89 | + |
| 90 | + lib.PQfinish.restype = None |
| 91 | + lib.PQfinish.argtypes = [_PGconn_p] |
| 92 | + |
| 93 | + return lib |
| 94 | + |
| 95 | + |
| 96 | +class PGresult(contextlib.AbstractContextManager): |
| 97 | + """Wraps a raw _PGresult_p with a more friendly interface.""" |
| 98 | + |
| 99 | + def __init__(self, lib: ctypes.CDLL, res: _PGresult_p): |
| 100 | + self._lib = lib |
| 101 | + self._res = res |
| 102 | + |
| 103 | + def __exit__(self, *exc): |
| 104 | + self._lib.PQclear(self._res) |
| 105 | + self._res = None |
| 106 | + |
| 107 | + def status(self): |
| 108 | + return self._lib.PQresultStatus(self._res) |
| 109 | + |
| 110 | + |
| 111 | +class PGconn(contextlib.AbstractContextManager): |
| 112 | + """ |
| 113 | + Wraps a raw _PGconn_p with a more friendly interface. This is just a |
| 114 | + stub; it's expected to grow. |
| 115 | + """ |
| 116 | + |
| 117 | + def __init__( |
| 118 | + self, |
| 119 | + lib: ctypes.CDLL, |
| 120 | + handle: _PGconn_p, |
| 121 | + stack: contextlib.ExitStack, |
| 122 | + ): |
| 123 | + self._lib = lib |
| 124 | + self._handle = handle |
| 125 | + self._stack = stack |
| 126 | + |
| 127 | + def __exit__(self, *exc): |
| 128 | + self._lib.PQfinish(self._handle) |
| 129 | + self._handle = None |
| 130 | + |
| 131 | + def exec(self, query: str) -> PGresult: |
| 132 | + """ |
| 133 | + Executes a query via PQexec() and returns a PGresult. |
| 134 | + """ |
| 135 | + res = self._lib.PQexec(self._handle, query.encode()) |
| 136 | + return self._stack.enter_context(PGresult(self._lib, res)) |
| 137 | + |
| 138 | + |
| 139 | +@pytest.fixture |
| 140 | +def libpq(libpq_handle, remaining_timeout): |
| 141 | + """ |
| 142 | + Provides a ctypes-based API wrapped around libpq.so. This fixture keeps |
| 143 | + track of allocated resources and cleans them up during teardown. See |
| 144 | + _Libpq's public API for details. |
| 145 | + """ |
| 146 | + |
| 147 | + class _Libpq(contextlib.ExitStack): |
| 148 | + CONNECTION_OK = 0 |
| 149 | + |
| 150 | + PGRES_EMPTY_QUERY = 0 |
| 151 | + |
| 152 | + class Error(RuntimeError): |
| 153 | + """ |
| 154 | + libpq.Error is the exception class for application-level errors that |
| 155 | + are encountered during libpq operations. |
| 156 | + """ |
| 157 | + |
| 158 | + pass |
| 159 | + |
| 160 | + def __init__(self): |
| 161 | + super().__init__() |
| 162 | + self.lib = libpq_handle |
| 163 | + |
| 164 | + def _connstr(self, opts: Dict[str, Any]) -> str: |
| 165 | + """ |
| 166 | + Flattens the provided options into a libpq connection string. Values |
| 167 | + are converted to str and quoted/escaped as necessary. |
| 168 | + """ |
| 169 | + settings = [] |
| 170 | + |
| 171 | + for k, v in opts.items(): |
| 172 | + v = str(v) |
| 173 | + if not v: |
| 174 | + v = "''" |
| 175 | + else: |
| 176 | + v = v.replace("\\", "\\\\") |
| 177 | + v = v.replace("'", "\\'") |
| 178 | + |
| 179 | + if " " in v: |
| 180 | + v = f"'{v}'" |
| 181 | + |
| 182 | + settings.append(f"{k}={v}") |
| 183 | + |
| 184 | + return " ".join(settings) |
| 185 | + |
| 186 | + def must_connect(self, **opts) -> PGconn: |
| 187 | + """ |
| 188 | + Connects to a server, using the given connection options, and |
| 189 | + returns a libpq.PGconn object wrapping the connection handle. A |
| 190 | + failure will raise libpq.Error. |
| 191 | +
|
| 192 | + Connections honor PG_TEST_TIMEOUT_DEFAULT unless connect_timeout is |
| 193 | + explicitly overridden in opts. |
| 194 | + """ |
| 195 | + |
| 196 | + if "connect_timeout" not in opts: |
| 197 | + t = int(remaining_timeout()) |
| 198 | + opts["connect_timeout"] = max(t, 1) |
| 199 | + |
| 200 | + conn_p = self.lib.PQconnectdb(self._connstr(opts).encode()) |
| 201 | + |
| 202 | + # Ensure the connection handle is always closed at the end of the |
| 203 | + # test. |
| 204 | + conn = self.enter_context(PGconn(self.lib, conn_p, stack=self)) |
| 205 | + |
| 206 | + if self.lib.PQstatus(conn_p) != self.CONNECTION_OK: |
| 207 | + raise self.Error(self.lib.PQerrorMessage(conn_p).decode()) |
| 208 | + |
| 209 | + return conn |
| 210 | + |
| 211 | + with _Libpq() as lib: |
| 212 | + yield lib |
0 commit comments