Debian Codegraph @

tests/hsql_sessions.py

raw
1 """A `hsql --serve` process for tests to talk to, in a fresh interpreter.
2
3 Not in-process: a server swaps the process's streams, environment and working
4 directory for the length of every request, and pytest owns all three.
5 """
6
7 from __future__ import annotations
8
9 import os
10 import signal
11 import socket
12 import subprocess
13 import sys
14 import time
15 from pathlib import Path
16 from typing import Callable, Mapping, Sequence
17
18 from harlequin.hsql.session import socket_path
19
20 HsqlSubprocess = Callable[..., "subprocess.CompletedProcess[bytes]"]
21 """One invocation of the console script, in a fresh interpreter, as bytes."""
22
23
24 class WarmSession:
25 """One session, and the environment a client reaches it through."""
26
27 def __init__(
28 self,
29 name: str,
30 serve_argv: Sequence[str],
31 *,
32 runtime_dir: Path,
33 home: Path,
34 base_env: Mapping[str, str] | None = None,
35 env: Mapping[str, str] | None = None,
36 ) -> None:
37 self.name = name
38 self.runtime_dir = runtime_dir
39 self.env = {"XDG_RUNTIME_DIR": str(runtime_dir)}
40 self.stderr_path = runtime_dir / f"{name}.stderr"
41 self._stderr_file = self.stderr_path.open("wb")
42 self.process = subprocess.Popen(
43 [
44 sys.executable,
45 "-c",
46 "import sys\n"
47 f"sys.argv = ['hsql', '--serve', {name!r}, *{list(serve_argv)!r}]\n"
48 "from harlequin.hsql import main\n"
49 "main()\n",
50 ],
51 stdout=subprocess.PIPE,
52 stderr=self._stderr_file,
53 cwd=home,
54 # `base_env` is what keeps a session off the machine running the
55 # tests: its config files, and the history a served query writes
56 env={
57 **{
58 key: value
59 for key, value in (
60 os.environ if base_env is None else base_env
61 ).items()
62 if key not in ("HSQL_SESSION", "NO_COLOR")
63 },
64 "HOME": str(home),
65 "USERPROFILE": str(home),
66 "XDG_CONFIG_HOME": str(home / "xdg"),
67 **self.env,
68 # the server's own, which a request must not inherit
69 **(env or {}),
70 },
71 )
72
73 @property
74 def socket_path(self) -> Path:
75 return Path(socket_path(self.name, self.env))
76
77 def wait_until_ready(self, timeout: float = 30.0) -> None:
78 """Block until the server answers a connection, or it exited."""
79 deadline = time.monotonic() + timeout
80 while time.monotonic() < deadline:
81 if self.process.poll() is not None:
82 raise RuntimeError(
83 f"the server exited {self.process.returncode}: {self.stderr()}"
84 )
85 probe = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
86 try:
87 probe.connect(str(self.socket_path))
88 except OSError:
89 time.sleep(0.05)
90 continue
91 finally:
92 probe.close()
93 return
94 raise RuntimeError(f"the server never listened: {self.stderr()}")
95
96 def stderr(self) -> str:
97 return self.stderr_path.read_text(encoding="utf-8", errors="replace")
98
99 def stop(self, timeout: float = 30.0) -> int:
100 """Stop it the way an operator does, and return its exit code."""
101 if self.process.poll() is None:
102 self.process.send_signal(signal.SIGINT)
103 try:
104 return self.process.wait(timeout)
105 except subprocess.TimeoutExpired:
106 self.process.kill()
107 return self.process.wait(5)
108 finally:
109 if self.process.stdout is not None:
110 self.process.stdout.close()
111 self._stderr_file.close()
112
113
114 ServeSession = Callable[..., WarmSession]
115 """Start a session under a name, and stop it when the test is done."""