Debian Codegraph @

tests/conftest.py

raw
1 from __future__ import annotations
2
3 import csv
4 import sqlite3
5 import sys
6 from datetime import datetime
7 from pathlib import Path
8
9 import duckdb
10 import pytest
11
12 from harlequin import Harlequin
13 from harlequin.adapter import HarlequinAdapter
14 from harlequin.catalog_cache import HISTORY_CACHE_VERSION
15 from harlequin.locale_manager import set_locale
16 from harlequin.windows_timezone import download_tzdata, locate_tzdata
17
18 if sys.version_info < (3, 10):
19 from importlib_metadata import entry_points
20 else:
21 from importlib.metadata import entry_points
22
23
24 # The committed snapshots are generated on the lowest supported Python. On 3.12+,
25 # SQLite grows a transaction button, so the tests that show one render differently
26 # and skip their snapshot assertions (see the transaction_button_visible fixture).
27 SNAPSHOT_PYTHON = (3, 10)
28
29 LEGACY_CACHE_FILE = "catalog-cache-2.pickle"
30 LEGACY_HISTORY: dict[str, list[tuple[str, datetime, int, float]]] = {
31 "abc123": [
32 ("select 1", datetime(2026, 8, 1, 9, 30), 1, 0.5),
33 ("sel", datetime(2026, 8, 1, 9, 31), -1, 0.0),
34 ],
35 "foo": [("select * from line_items", datetime(2026, 8, 1, 10, 30), 3, 1.25)],
36 }
37 """What the committed version-2 cache holds, per connection: the four fields a
38 record of that version had -- sql, when it ran in local time, how many rows it
39 returned (negative for a failure), and how long it took in seconds."""
40
41
42 def pytest_configure(config: pytest.Config) -> None:
43 """Stop --snapshot-update on a newer Python from clobbering the baseline.
44
45 A full update run on 3.12+ silently rewrites the committed snapshots with
46 3.12 output, and deletes the ones those tests never take. The py12-only
47 snapshots can't be generated on 3.10 (their tests are skipped there), so
48 updating those on 3.12 is allowed -- but such a run covers a slice of the
49 suite, so it must not prune everything it didn't take.
50 """
51 if not config.option.update_snapshots:
52 return
53 if sys.version_info[:2] == SNAPSHOT_PYTHON:
54 return
55
56 baseline = ".".join(str(v) for v in SNAPSHOT_PYTHON)
57 if "py12" not in (config.option.markexpr or ""):
58 raise pytest.UsageError(
59 f"--snapshot-update must run on Python {baseline}, which is what the "
60 "committed snapshots were generated on:\n"
61 " uv run pytest --snapshot-update\n"
62 "To update the py12-only snapshots, which can only be generated on "
63 "3.12+, select just those tests:\n"
64 " uv run --python 3.12 --group test pytest -m 'py12 and not online' "
65 "--snapshot-update"
66 )
67 config.option.no_cleanup = True
68
69
70 @pytest.fixture(scope="session", autouse=True)
71 def install_tzdata() -> None:
72 if sys.platform == "win32" and not locate_tzdata():
73 download_tzdata()
74
75
76 @pytest.fixture(scope="session", autouse=True)
77 def set_locale_to_enUS() -> None:
78 set_locale("en_US.UTF-8")
79
80
81 @pytest.fixture(autouse=True)
82 def crash_reports_go_to_tmp(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
83 """Every crash a test causes writes here, not into the developer's log dir.
84
85 `run_test` re-raises through `_handle_exception`, so without this every
86 failing functional test in the suite leaves a crash report behind.
87 """
88 report_dir = tmp_path / "crash-reports"
89 monkeypatch.setattr("harlequin.crash.get_crash_report_dir", lambda: report_dir)
90 return report_dir
91
92
93 @pytest.fixture(autouse=True)
94 def no_discovered_config(monkeypatch: pytest.MonkeyPatch) -> None:
95 """Keep the machine running the tests out of them.
96
97 Config discovery walks the home directory, the user config dir and the cwd,
98 so without this a developer's own `.harlequin.toml` decides what a test
99 asserts.
100
101 The search is the seam, rather than `load_config()` or a command's own
102 `load_profile()`, because it is the one both commands share *and* that
103 leaves `--config-path` working -- a test that passes an explicit config
104 file still gets it. A test about discovery itself patches the seam back
105 (see `test_discover_config_files`) or replaces it with directories of its
106 own (see the `config_dirs` fixture).
107 """
108 monkeypatch.setattr("harlequin.config._search_directories", list)
109
110
111 @pytest.fixture(autouse=True)
112 def query_log_path(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
113 """Point the query log at a throwaway store so a test run never writes the
114 developer's own history, and return where it went."""
115 store = tmp_path / "history.db"
116 monkeypatch.setattr("harlequin.query_log.default_path", lambda: store)
117 return store
118
119
120 @pytest.fixture(autouse=True)
121 def catalog_cache_dir(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
122 """Point the catalog cache -- and the pickled history a migration reads --
123 at a throwaway directory, and return it."""
124 cache_dir = tmp_path / "cache"
125 monkeypatch.setattr(
126 "harlequin.catalog_cache.user_cache_dir", lambda **_: str(cache_dir)
127 )
128 return cache_dir
129
130
131 @pytest.fixture(autouse=True)
132 def forget_migrated_history(monkeypatch: pytest.MonkeyPatch) -> None:
133 """Start each test as a new process does, having adopted no connection."""
134 monkeypatch.setattr("harlequin.history._migrated", set())
135
136
137 @pytest.fixture
138 def legacy_history_cache(catalog_cache_dir: Path, data_dir: Path) -> Path:
139 """Put a version-2 catalog cache where Harlequin would find one.
140
141 Written by Harlequin 2.14.0 (`scripts/write_legacy_cache.py`), so it names
142 the classes it pickles exactly as a user's own file does. It holds
143 `LEGACY_HISTORY`: two connections, one of whose queries failed.
144 """
145 catalog_cache_dir.mkdir(parents=True, exist_ok=True)
146 cache_file = catalog_cache_dir / f"catalog-cache-{HISTORY_CACHE_VERSION}.pickle"
147 cache_file.write_bytes((data_dir / LEGACY_CACHE_FILE).read_bytes())
148 return cache_file
149
150
151 @pytest.fixture
152 def data_dir() -> Path:
153 here = Path(__file__)
154 return here.parent / "data"
155
156
157 @pytest.fixture
158 def fake_ssh_client(data_dir: Path) -> Path:
159 """The stand-in for the `ssh` binary, which needs no server to bind a forward."""
160 return data_dir / "unit_tests" / "ssh" / "ssh"
161
162
163 @pytest.fixture
164 def drop_trigger(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
165 """Touch the path this returns, and the fake client drops its forwards."""
166 path = tmp_path / "drop"
167 monkeypatch.setenv("FAKE_SSH_DROP_WHEN", str(path))
168 return path
169
170
171 @pytest.fixture
172 def tiny_duck(tmp_path: Path, data_dir: Path) -> Path:
173 """
174 Creates a duckdb database file from the contents of
175 data_dir/functional_tests/tiny
176 """
177 path_to_data = data_dir / "functional_tests" / "tiny"
178 path_to_db = tmp_path / "tiny.db"
179 conn = duckdb.connect(str(path_to_db))
180 conn.execute(f"import database '{path_to_data}';")
181 return path_to_db
182
183
184 @pytest.fixture
185 def tiny_sqlite(tmp_path: Path, data_dir: Path) -> Path:
186 path_to_data = data_dir / "functional_tests" / "tiny"
187 path_to_db = tmp_path / "tiny.sqlite"
188 _create_sqlite_db_from_data_dir(path_to_data, path_to_db)
189 return path_to_db
190
191
192 @pytest.fixture
193 def small_duck(tmp_path: Path, data_dir: Path) -> Path:
194 """
195 Creates a duckdb database file from the contents of
196 data_dir/functional_tests/small
197 """
198 path_to_data = data_dir / "functional_tests" / "small"
199 path_to_db = tmp_path / "small.db"
200 conn = duckdb.connect(str(path_to_db))
201 conn.execute(f"import database '{path_to_data}';")
202 return path_to_db
203
204
205 @pytest.fixture
206 def small_sqlite(tmp_path: Path, data_dir: Path) -> Path:
207 path_to_data = data_dir / "functional_tests" / "small"
208 path_to_db = tmp_path / "small.sqlite"
209 _create_sqlite_db_from_data_dir(path_to_data, path_to_db)
210 return path_to_db
211
212
213 @pytest.fixture
214 def duckdb_adapter() -> type[HarlequinAdapter]:
215 eps = entry_points(group="harlequin.adapter")
216 cls: type[HarlequinAdapter] = eps["duckdb"].load()
217 return cls
218
219
220 @pytest.fixture
221 def sqlite_adapter() -> type[HarlequinAdapter]:
222 eps = entry_points(group="harlequin.adapter")
223 cls: type[HarlequinAdapter] = eps["sqlite"].load()
224 return cls
225
226
227 @pytest.fixture(params=["duckdb", "sqlite"])
228 def all_adapters(request: pytest.FixtureRequest) -> type[HarlequinAdapter]:
229 eps = entry_points(group="harlequin.adapter")
230 cls: type[HarlequinAdapter] = eps[request.param].load()
231 return cls
232
233
234 @pytest.fixture
235 def app(duckdb_adapter: type[HarlequinAdapter]) -> Harlequin:
236 return Harlequin(duckdb_adapter([":memory:"], no_init=True), connection_hash="foo")
237
238
239 @pytest.fixture
240 def app_all_adapters(all_adapters: type[HarlequinAdapter]) -> Harlequin:
241 return Harlequin(all_adapters([":memory:"], no_init=True), connection_hash="foo")
242
243
244 @pytest.fixture
245 def app_small_duck(
246 duckdb_adapter: type[HarlequinAdapter], small_duck: Path
247 ) -> Harlequin:
248 return Harlequin(
249 duckdb_adapter([str(small_duck)], no_init=True), connection_hash="small"
250 )
251
252
253 @pytest.fixture
254 def app_small_sqlite(
255 sqlite_adapter: type[HarlequinAdapter], small_sqlite: Path
256 ) -> Harlequin:
257 return Harlequin(
258 sqlite_adapter([str(small_sqlite)], no_init=True), connection_hash="bar"
259 )
260
261
262 @pytest.fixture(params=["duckdb", "sqlite"])
263 def app_all_adapters_small_db(
264 request: pytest.FixtureRequest,
265 app_small_duck: Harlequin,
266 app_small_sqlite: Harlequin,
267 ) -> Harlequin:
268 if request.param == "duckdb":
269 return app_small_duck
270 else:
271 return app_small_sqlite
272
273
274 @pytest.fixture
275 def app_multi_duck(
276 duckdb_adapter: type[HarlequinAdapter], tiny_duck: Path, small_duck: Path
277 ) -> Harlequin:
278 return Harlequin(
279 duckdb_adapter([str(tiny_duck), str(small_duck)], no_init=True),
280 connection_hash="multi",
281 )
282
283
284 def _create_sqlite_db_from_data_dir(data_dir: Path, db_path: Path) -> None:
285 SINGLE_QUOTE = "'"
286 DOUBLED_SINGLE_QUOTE = "''"
287 conn = sqlite3.connect(str(db_path))
288 with open(data_dir / "schema_sqlite.sql") as f:
289 ddl = f.read()
290 for q in ddl.split(";"):
291 conn.execute(q)
292 for p in data_dir.iterdir():
293 if p.is_file() and p.suffix == ".csv":
294 with p.open("r", encoding="utf-8") as f:
295 reader = csv.reader(f)
296 for row in reader:
297 quoted = [
298 (
299 val
300 if isinstance(val, (int, float))
301 else f"'{val.replace(SINGLE_QUOTE, DOUBLED_SINGLE_QUOTE)}'"
302 )
303 for val in row
304 ]
305 conn.execute(f"insert into {p.stem} values({', '.join(quoted)})")
306 conn.commit()