Debian Codegraph @

tests/unit_tests/conftest.py

raw
1 from __future__ import annotations
2
3 import os
4 import shutil
5 import subprocess
6 import sys
7 import tempfile
8 from pathlib import Path
9 from typing import Callable, Iterator, Mapping, Sequence
10
11 import pytest
12
13 from harlequin.adapter import HarlequinAdapter
14 from harlequin.query import ResultSet, RowLimit, execute, fetch
15 from harlequin.statements import split
16 from tests.hsql_sessions import HsqlSubprocess, ServeSession, WarmSession
17
18
19 @pytest.fixture
20 def result_set(
21 duckdb_adapter: type[HarlequinAdapter],
22 ) -> Callable[..., ResultSet]:
23 """Run one statement against an in-memory DuckDB and fetch its result.
24
25 DuckDB rather than a fake cursor: everything downstream of `fetch()` is
26 about how real values -- decimals, blobs, structs -- come out, and a fake
27 would only prove that the fixture and the assertion agree.
28 """
29 connection = duckdb_adapter([":memory:"], no_init=True).connect()
30
31 def _result_set(sql: str, limit: RowLimit | None = None) -> ResultSet:
32 (executed,) = execute(connection, split(sql), limit=limit)
33 return fetch(executed, limit=limit)
34
35 return _result_set
36
37
38 @pytest.fixture
39 def clean_env(tmp_path: Path) -> dict[str, str]:
40 """The environment a child process needs to leave this machine alone.
41
42 `no_discovered_config` and the `query_log_path` monkeypatch cannot reach
43 into a subprocess, so without this a child reads the config files of
44 whoever is running the tests and writes its queries into their history.
45 """
46 return {
47 **{key: value for key, value in os.environ.items() if key != "HSQL_SESSION"},
48 # where config discovery looks, on every platform platformdirs knows
49 "HOME": str(tmp_path),
50 "USERPROFILE": str(tmp_path),
51 "XDG_CONFIG_HOME": str(tmp_path / "xdg"),
52 "APPDATA": str(tmp_path / "appdata"),
53 "LOCALAPPDATA": str(tmp_path / "localappdata"),
54 # and where the query log goes, which a run writes as it runs. On
55 # Windows platformdirs asks the shell rather than the environment, and
56 # only these override it (platformdirs >= 4.2; the lock file has 4.11).
57 "XDG_STATE_HOME": str(tmp_path / "state"),
58 "WIN_PD_OVERRIDE_LOCAL_APPDATA": str(tmp_path / "localappdata"),
59 "WIN_PD_OVERRIDE_APPDATA": str(tmp_path / "appdata"),
60 }
61
62
63 @pytest.fixture
64 def run_python(
65 tmp_path: Path, clean_env: dict[str, str]
66 ) -> Callable[[str], subprocess.CompletedProcess[str]]:
67 """Run a snippet in a fresh interpreter and capture its streams.
68
69 In-process assertions can't see the state these tests care about: which
70 modules an import pulled in, and which stream something was written to.
71 Both are properties of a clean interpreter, and pytest has already imported
72 half the world by the time a test runs.
73 """
74
75 def _run(code: str) -> subprocess.CompletedProcess[str]:
76 return subprocess.run(
77 [sys.executable, "-c", code],
78 capture_output=True,
79 text=True,
80 check=True,
81 cwd=tmp_path,
82 env=clean_env,
83 )
84
85 return _run
86
87
88 @pytest.fixture
89 def hsql_subprocess(tmp_path: Path, clean_env: dict[str, str]) -> HsqlSubprocess:
90 """Run `main()` the way the console script does, in a fresh interpreter.
91
92 Bytes rather than text, because the bytes are what hsql promises. A clean
93 machine, as `run_python` gives: the child's cwd, home, config dir and state
94 dir are empty directories unless a test names a cwd, and no `HSQL_SESSION`
95 of whoever runs the tests reaches it -- a test that wants a session names
96 one in `env`.
97 """
98
99 def _run(
100 argv: Sequence[str],
101 *,
102 cwd: Path | None = None,
103 stdin: bytes | None = None,
104 env: Mapping[str, str] | None = None,
105 timeout: float | None = None,
106 ) -> subprocess.CompletedProcess[bytes]:
107 return subprocess.run(
108 [
109 sys.executable,
110 "-c",
111 "import sys\n"
112 f"sys.argv = ['hsql', *{list(argv)!r}]\n"
113 "from harlequin.hsql import main\n"
114 "main()\n",
115 ],
116 capture_output=True,
117 input=stdin,
118 # a test that names one is asserting the invocation *returns*, and
119 # a regression there would otherwise hang rather than fail
120 timeout=timeout,
121 cwd=tmp_path if cwd is None else cwd,
122 env={
123 **{key: value for key, value in clean_env.items() if key != "NO_COLOR"},
124 **(env or {}),
125 },
126 )
127
128 return _run
129
130
131 @pytest.fixture
132 def short_runtime_dir() -> Iterator[Path]:
133 """A runtime directory a socket path still fits under.
134
135 `sun_path` holds 104 bytes on macOS and pytest's `tmp_path` is longer than
136 that there before a socket name is added.
137 """
138 base = tempfile.mkdtemp(prefix="hsql-", dir="/tmp")
139 yield Path(base)
140 shutil.rmtree(base, ignore_errors=True)
141
142
143 @pytest.fixture
144 def serve_session(
145 short_runtime_dir: Path, tmp_path: Path, clean_env: dict[str, str]
146 ) -> Iterator[ServeSession]:
147 """Start sessions, and stop every one of them when the test is done."""
148 started: list[WarmSession] = []
149
150 def _serve(
151 name: str = "test",
152 *serve_argv: str,
153 wait: bool = True,
154 env: Mapping[str, str] | None = None,
155 ) -> WarmSession:
156 session = WarmSession(
157 name,
158 serve_argv or ("-a", "duckdb", "--no-init", ":memory:"),
159 runtime_dir=short_runtime_dir,
160 home=tmp_path,
161 base_env=clean_env,
162 env=env,
163 )
164 started.append(session)
165 if wait:
166 session.wait_until_ready()
167 return session
168
169 yield _serve
170 for session in started:
171 session.stop()