Debian Codegraph @

tests/unit_tests/test_import_hygiene.py

raw
1 """Run-time guards for the import hygiene the headless CLI depends on.
2
3 The import-linter contracts in `pyproject.toml` read the static graph, so they
4 cannot tell a module-scope import from one deferred into the function that needs
5 it. These tests run the real thing in a subprocess and look at `sys.modules`,
6 which is the only way to prove a deferral actually defers.
7 """
8
9 from __future__ import annotations
10
11 import socket
12 import subprocess
13 from pathlib import Path
14 from typing import Callable
15
16 import pytest
17
18 # Importing any of these must not drag in the TUI. They are the modules an
19 # adapter -- or a headless front end -- reaches for.
20 HEADLESS_IMPORTS = [
21 "import harlequin",
22 "import harlequin.adapter",
23 "import harlequin.autocomplete",
24 "import harlequin.catalog",
25 "import harlequin.config",
26 "import harlequin.crash",
27 "import harlequin.environment",
28 "import harlequin.exception",
29 "import harlequin.export",
30 "import harlequin.hsql",
31 "import harlequin.hsql.cli",
32 "import harlequin.hsql.client",
33 "import harlequin.hsql.server",
34 "import harlequin.keymap",
35 "import harlequin.layout",
36 "import harlequin.navigate",
37 "import harlequin.options",
38 "import harlequin.plugins",
39 "import harlequin.redact",
40 "import harlequin.query",
41 "import harlequin.query_log",
42 "import harlequin.ssh",
43 "import harlequin.statements",
44 "import harlequin.transaction_mode",
45 "import harlequin_duckdb",
46 "import harlequin_sqlite",
47 "from textual_fastdatatable.backend import create_backend",
48 ]
49
50 FORBIDDEN = ("textual", "questionary", "prompt_toolkit", "sqlfmt", "rich")
51 """`rich` is here for the same reason as the rest: nothing headless renders.
52
53 It is the one that arrives sideways rather than from an import of ours --
54 `textual_fastdatatable.backend` pulled it in until 0.17.1 deferred it -- so the
55 guard is worth more here than the import-linter contracts, which only see this
56 repo's own graph.
57 """
58
59
60 @pytest.mark.parametrize("statement", HEADLESS_IMPORTS)
61 def test_headless_imports_do_not_load_the_tui(
62 statement: str, run_python: Callable[[str], subprocess.CompletedProcess[str]]
63 ) -> None:
64 proc = run_python(
65 f"{statement}\n"
66 "import sys\n"
67 f"print(','.join(m for m in {FORBIDDEN!r} if m in sys.modules))\n"
68 )
69 leaked = [m for m in proc.stdout.strip().split(",") if m]
70 assert not leaked, f"{statement!r} imported {leaked}"
71
72
73 # The warm-session client's whole graph, over a bare interpreter. A round trip
74 # to a session is about a millisecond, so what a caller waits for is this
75 # number -- and `import click` alone is +67 modules, which is why the client
76 # has neither it nor anything else of ours on its path.
77 CLIENT_MODULE_BUDGET = 40
78
79
80 def test_the_session_client_costs_almost_nothing_to_load(
81 run_python: Callable[[str], subprocess.CompletedProcess[str]],
82 ) -> None:
83 """Measured against a bare interpreter in the same environment, because the
84 absolute count moves with the Python version and this budget does not."""
85 bare = run_python("import sys\nprint(len(sys.modules))\n")
86 loaded = run_python(
87 "import harlequin.hsql.client\nimport sys\nprint(len(sys.modules))\n"
88 )
89 cost = int(loaded.stdout) - int(bare.stdout)
90 assert cost <= CLIENT_MODULE_BUDGET, (
91 f"loading the session client cost {cost} modules"
92 )
93
94
95 def test_deciding_whether_an_invocation_is_warm_does_not_import_click(
96 run_python: Callable[[str], subprocess.CompletedProcess[str]],
97 ) -> None:
98 """The single most important line-level decision in the feature.
99
100 `main()` looks at `--session` and `HSQL_SESSION` before it builds anything,
101 because `import click` costs more than the whole round trip it would be
102 paying for. import-linter reads the static graph and cannot see a deferral,
103 so this is what proves it defers.
104 """
105 proc = run_python(
106 "import harlequin.hsql\n"
107 "import sys\n"
108 "print(','.join(m for m in ('click', 'harlequin.hsql.cli', "
109 "'harlequin.hsql.diagnostics') if m in sys.modules))\n"
110 )
111 leaked = [m for m in proc.stdout.strip().split(",") if m]
112 assert not leaked, f"importing the entry point loaded {leaked}"
113
114
115 def test_a_warm_invocation_never_reaches_the_cold_path(
116 run_python: Callable[[str], subprocess.CompletedProcess[str]],
117 ) -> None:
118 """A typed session that is not running fails without building a command:
119 there is no server to parse the flags, and no reason to pay for a parser."""
120 proc = run_python(
121 "import sys\n"
122 "sys.argv = ['hsql', '--session', 'nobody-started-this', '-c', 'select 1']\n"
123 "from harlequin.hsql import main\n"
124 "try:\n"
125 " main()\n"
126 "except SystemExit as e:\n"
127 " print(e.code)\n"
128 "print(','.join(m for m in ('click', 'harlequin.config') "
129 "if m in sys.modules))\n"
130 )
131 # the client writes its refusal to stderr, so stdout is these two lines
132 code, leaked = proc.stdout.split("\n")[:2]
133 # 3 where a session could have been running and was not; 2 on a platform
134 # that has no sessions at all, which is native Windows
135 assert code == ("3" if hasattr(socket, "AF_UNIX") else "2")
136 assert not leaked
137
138
139 def test_importing_the_completers_does_not_parse_sql(
140 run_python: Callable[[str], subprocess.CompletedProcess[str]],
141 ) -> None:
142 """Every adapter imports the completers; only the Query Editor parses SQL.
143
144 `find_symbols()` defers `harlequin.statements`, so loading the grammar stays
145 off the path of everything that never reads a buffer.
146 """
147 proc = run_python(
148 "import harlequin.autocomplete\n"
149 "import sys\n"
150 "print(','.join(m for m in ('tree_sitter', 'tree_sitter_sql') "
151 "if m in sys.modules))\n"
152 )
153 assert not proc.stdout.strip(), f"importing the completers loaded {proc.stdout}"
154
155
156 @pytest.mark.parametrize("argv", [["--help"], ["--version"]])
157 def test_building_the_hsql_command_imports_no_adapter(
158 argv: list[str], run_python: Callable[[str], subprocess.CompletedProcess[str]]
159 ) -> None:
160 """The point of hsql's two-phase parse, and it regresses quietly.
161
162 Neither names an adapter: `--help` renders the adapter-agnostic surface and
163 `--version` prints a string that does not depend on one, so neither must pay
164 `ep.load()` for every adapter installed to do it.
165 """
166 proc = run_python(
167 "import sys\n"
168 "from harlequin.hsql.cli import build_cli\n"
169 f"build_cli({argv!r})\n"
170 "print(','.join(m for m in sys.modules if m.startswith('harlequin_')))\n"
171 )
172 loaded = [m for m in proc.stdout.strip().split(",") if m]
173 assert not loaded, f"building `hsql {' '.join(argv)}` imported {loaded}"
174
175
176 def test_building_the_ide_command_imports_only_the_named_adapter(
177 run_python: Callable[[str], subprocess.CompletedProcess[str]],
178 ) -> None:
179 """The IDE's half of the same two-phase parse.
180
181 An invocation opens the IDE with exactly one adapter, so building its
182 command imports exactly one. Every other installed adapter used to be
183 `ep.load()`ed on the way to a connection that would never use it, which is
184 ~200ms with four of them and grows with the fifth.
185 """
186 proc = run_python(
187 "import sys\n"
188 "from harlequin.cli import build_cli\n"
189 "build_cli(['-a', 'sqlite', ':memory:'])\n"
190 "print(','.join(sorted({m.split('.')[0] for m in sys.modules "
191 "if m.startswith('harlequin_')})))\n"
192 )
193 assert proc.stdout.strip() == "harlequin_sqlite"
194
195
196 def test_the_ides_help_still_documents_every_adapter(
197 run_python: Callable[[str], subprocess.CompletedProcess[str]],
198 ) -> None:
199 """The deliberate exception, and the one path that still pays for all of them.
200
201 `harlequin --help` lists what every installed adapter takes, because an
202 option a reader cannot discover is one they cannot use. The trade is the
203 right way round: help is not the invocation anyone waits on.
204 """
205 proc = run_python(
206 "import sys\n"
207 "from harlequin.cli import build_cli\n"
208 "build_cli(['--help'])\n"
209 "print(','.join(sorted({m.split('.')[0] for m in sys.modules "
210 "if m.startswith('harlequin_')})))\n"
211 )
212 # a superset: whatever else the machine running this has installed
213 assert {"harlequin_duckdb", "harlequin_sqlite"} <= set(
214 proc.stdout.strip().split(",")
215 )
216
217
218 # Not TUI modules, but slow ones on the path every start-up walks, each kept off
219 # it by a deferral the static graph cannot see. The cost is the reason: tomlkit
220 # parses a 10KB pyproject.toml ~30x slower than tomllib, and wcwidth costs
221 # ~25ms to import for a fast path that returns without calling it.
222 DEFERRED_ON_STARTUP = ("tomlkit", "wcwidth")
223
224
225 def test_reading_config_does_not_import_tomlkit(
226 run_python: Callable[[str], subprocess.CompletedProcess[str]],
227 ) -> None:
228 """Reads go through tomllib; tomlkit is for writes, which are rare.
229
230 Start-up reads config -- including whatever `pyproject.toml` is in the
231 working directory -- so an eager tomlkit here is paid by every invocation.
232 """
233 proc = run_python(
234 "import sys\n"
235 "from harlequin.config import load_config\n"
236 "load_config(config_path=None)\n"
237 "print('tomlkit' in sys.modules)\n"
238 )
239 assert proc.stdout.strip() == "False"
240
241
242 def test_an_all_ascii_run_defers_the_slow_startup_imports(
243 run_python: Callable[[str], subprocess.CompletedProcess[str]],
244 ) -> None:
245 """A full `hsql -c 'select 1'`, end to end, in a clean interpreter."""
246 proc = run_python(
247 "import sys\n"
248 "sys.argv = ['hsql', '-c', 'select 1']\n"
249 "from harlequin.hsql import main\n"
250 "try:\n"
251 " main()\n"
252 "except SystemExit:\n"
253 " pass\n"
254 f"print(','.join(m for m in {DEFERRED_ON_STARTUP!r} if m in sys.modules), "
255 "file=sys.stderr)\n"
256 )
257 leaked = [m for m in proc.stderr.strip().split(",") if m]
258 assert not leaked, f"`hsql -c 'select 1'` imported {leaked}"
259
260
261 def test_a_run_that_records_its_queries_does_not_render_one(
262 run_python: Callable[[str], subprocess.CompletedProcess[str]],
263 ) -> None:
264 """The query log writes what the History screen renders, and only one of
265 them may import rich."""
266 proc = run_python(
267 "import sys\n"
268 "sys.argv = ['hsql', '-c', 'select 1']\n"
269 "from harlequin.hsql import main\n"
270 "try:\n"
271 " main()\n"
272 "except SystemExit:\n"
273 " pass\n"
274 "import sqlite3, pathlib, platformdirs\n"
275 "state = pathlib.Path(platformdirs.user_state_dir('harlequin'))\n"
276 "db = sqlite3.connect(state / 'history.db')\n"
277 "print(db.execute('select sql from queries').fetchall(), file=sys.stderr)\n"
278 f"print(','.join(m for m in {FORBIDDEN!r} if m in sys.modules), "
279 "file=sys.stderr)\n"
280 )
281 recorded, leaked = proc.stderr.splitlines()
282 assert "select 1" in recorded, "the run recorded nothing, so this proves nothing"
283 assert not [m for m in leaked.split(",") if m], f"a logged run imported {leaked}"
284
285
286 def test_non_ascii_output_still_measures_correctly(
287 run_python: Callable[[str], subprocess.CompletedProcess[str]],
288 ) -> None:
289 """The other half of the wcwidth deferral: it still loads when needed.
290
291 A deferral that never fires on the path that needs it would be a silent
292 misalignment bug rather than a slow import, so assert the column is padded
293 to the width the ideographs actually occupy.
294 """
295 proc = run_python(
296 "import sys\n"
297 "sys.argv = ['hsql', '-c', \"select '\\u4e2d\\u6587' as a, 'ab' as b\"]\n"
298 "from harlequin.hsql import main\n"
299 "try:\n"
300 " main()\n"
301 "except SystemExit:\n"
302 " pass\n"
303 "print('wcwidth' in sys.modules, file=sys.stderr)\n"
304 )
305 assert proc.stderr.strip() == "True"
306 # two ideographs are four cells, so column `a` is four wide and its rule is
307 # six. Measured with `len()` instead it would be two wide and rule four --
308 # which is the misalignment this asserts against, so match the whole line.
309 assert "------+----" in proc.stdout
310
311
312 @pytest.mark.parametrize(
313 "mode,forbidden",
314 [
315 # a document, so it needs neither the row machinery nor a database.
316 # It does write TOML, so tomlkit is not on its list
317 ("show", ("duckdb", "pyarrow")),
318 # rows, so it pays for pyarrow -- and for no database driver, because
319 # `ResultSet.text_columns()` returns strings unchanged, and no tomlkit,
320 # because a listing is not a TOML document
321 ("list-profiles", ("duckdb", "tomlkit")),
322 ],
323 )
324 def test_the_config_modes_import_no_database(
325 mode: str,
326 forbidden: tuple[str, ...],
327 run_python: Callable[[str], subprocess.CompletedProcess[str]],
328 ) -> None:
329 """Neither mode reaches for a database driver of its own accord.
330
331 There is no config file here, so `show` has no profile to redact and no
332 adapter to ask about one -- which is the floor this asserts. What it costs
333 when there *is* a profile is the test below.
334 `--format csv|json|parquet` is the exception a caller asks for by name:
335 those are written by `harlequin.export`, which serializes through duckdb or
336 pyarrow whatever produced the rows.
337 """
338 proc = run_python(
339 "import sys\n"
340 f"sys.argv = ['hsql', '--config', {mode!r}]\n"
341 "from harlequin.hsql import main\n"
342 "try:\n"
343 " main()\n"
344 "except SystemExit:\n"
345 " pass\n"
346 f"print(','.join(m for m in {forbidden!r} if m in sys.modules), "
347 "file=sys.stderr)\n"
348 "print(','.join(m for m in sys.modules if m.startswith('harlequin_')), "
349 "file=sys.stderr)\n"
350 )
351 leaked = [m for m in proc.stderr.strip().replace("\n", ",").split(",") if m]
352 assert not leaked, f"`hsql --config {mode}` imported {leaked}"
353
354
355 def test_the_catalog_mode_imports_only_the_adapter_it_connects_with(
356 run_python: Callable[[str], subprocess.CompletedProcess[str]],
357 ) -> None:
358 """A listing is rows that never went through a database, so nothing casts.
359
360 `ResultSet.text_columns()` returns strings unchanged, which is what keeps
361 duckdb out of a listing from any other adapter -- it is ~85ms, on the one
362 mode whose whole job is a fast look at what is there.
363 """
364 proc = run_python(
365 "import sys\n"
366 "sys.argv = ['hsql', '-a', 'sqlite', '--catalog', ':memory:']\n"
367 "from harlequin.hsql import main\n"
368 "try:\n"
369 " main()\n"
370 "except SystemExit:\n"
371 " pass\n"
372 "print(','.join(sorted({m.split('.')[0] for m in sys.modules "
373 "if m.startswith('harlequin_')})), file=sys.stderr)\n"
374 "print(','.join(m for m in ('duckdb', 'tomlkit') if m in sys.modules), "
375 "file=sys.stderr)\n"
376 )
377 adapters, forbidden = proc.stderr.split("\n")[:2]
378 assert adapters == "harlequin_sqlite"
379 assert not forbidden
380
381
382 def test_the_search_mode_imports_only_the_adapter_it_connects_with(
383 run_python: Callable[[str], subprocess.CompletedProcess[str]],
384 ) -> None:
385 """A search is rows that never went through a database, so nothing casts."""
386 proc = run_python(
387 "import sys\n"
388 "sys.argv = "
389 "['hsql', '-a', 'sqlite', '--catalog-search', 'orders', ':memory:']\n"
390 "from harlequin.hsql import main\n"
391 "try:\n"
392 " main()\n"
393 "except SystemExit:\n"
394 " pass\n"
395 "print(','.join(sorted({m.split('.')[0] for m in sys.modules "
396 "if m.startswith('harlequin_')})), file=sys.stderr)\n"
397 "print(','.join(m for m in ('duckdb', 'tomlkit') if m in sys.modules), "
398 "file=sys.stderr)\n"
399 )
400 adapters, forbidden = proc.stderr.split("\n")[:2]
401 assert adapters == "harlequin_sqlite"
402 assert not forbidden
403
404
405 def test_a_run_does_not_import_the_catalog_walk(
406 run_python: Callable[[str], subprocess.CompletedProcess[str]],
407 ) -> None:
408 """The other half of the mode-per-module rule: a query pays for no mode."""
409 proc = run_python(
410 "import sys\n"
411 "sys.argv = ['hsql', '-c', 'select 1']\n"
412 "from harlequin.hsql import main\n"
413 "try:\n"
414 " main()\n"
415 "except SystemExit:\n"
416 " pass\n"
417 "print(','.join(m for m in sys.modules "
418 "if m.startswith('harlequin.hsql.modes.') "
419 "or m == 'harlequin.navigate'), file=sys.stderr)\n"
420 )
421 assert not proc.stderr.strip()
422
423
424 def test_config_validate_imports_only_the_adapters_its_profiles_name(
425 tmp_path: Path, run_python: Callable[[str], subprocess.CompletedProcess[str]]
426 ) -> None:
427 """The one mode here that pays for adapters, paying for as few as it can.
428
429 Checking a profile's options against the ones its adapter declares takes
430 importing that adapter -- and only that one. A mode that imported every
431 installed adapter to check a config naming one would cost a caller with
432 four of them four times what the answer is worth. It is rows rather than a
433 document, so it pays for pyarrow and not for tomlkit, like `list-profiles`.
434
435 `tmp_path` is the subprocess's cwd and its home, so this file is the whole
436 of the config it discovers.
437 """
438 (tmp_path / ".harlequin.toml").write_text(
439 '[profiles.lite]\nadapter = "sqlite"\nread_only = true\n'
440 )
441 proc = run_python(
442 "import sys\n"
443 "sys.argv = ['hsql', '--config', 'validate']\n"
444 "from harlequin.hsql import main\n"
445 "try:\n"
446 " main()\n"
447 "except SystemExit:\n"
448 " pass\n"
449 "print(','.join(sorted({m.split('.')[0] for m in sys.modules "
450 "if m.startswith('harlequin_')})), file=sys.stderr)\n"
451 "print(','.join(m for m in ('duckdb', 'tomlkit') if m in sys.modules), "
452 "file=sys.stderr)\n"
453 )
454 # two lines, and the second is empty when nothing forbidden was imported
455 adapters, forbidden = proc.stderr.split("\n")[:2]
456 assert adapters == "harlequin_sqlite"
457 assert not forbidden
458
459
460 def test_config_schema_writes_a_document_and_reads_no_file(
461 tmp_path: Path, run_python: Callable[[str], subprocess.CompletedProcess[str]]
462 ) -> None:
463 """The second mode that pays for adapters on purpose, and pays for nothing else.
464
465 Describing the options an adapter declares means importing every installed
466 adapter, as `--spec` does. It is a document rather than rows, so it never
467 reaches the execution core, and it reads no config file, so no tomlkit -- a
468 schema says what a config file may hold whether or not this machine has
469 one.
470
471 `tmp_path` is the subprocess's cwd and its home, so this file is the whole
472 of the config it would discover.
473 """
474 (tmp_path / ".harlequin.toml").write_text('[profiles.lite]\nadapter = "sqlite"\n')
475 proc = run_python(
476 "import sys\n"
477 "sys.argv = ['hsql', '--config', 'schema']\n"
478 "from harlequin.hsql import main\n"
479 "try:\n"
480 " main()\n"
481 "except SystemExit:\n"
482 " pass\n"
483 "print(','.join(sorted({m.split('.')[0] for m in sys.modules "
484 "if m.startswith('harlequin_')})), file=sys.stderr)\n"
485 "print(','.join(m for m in ('harlequin.query', 'tomlkit') "
486 "if m in sys.modules), file=sys.stderr)\n"
487 )
488 adapters, forbidden = proc.stderr.split("\n")[:2]
489 # both of the bundled ones, where every other mode here costs at most one
490 assert {"harlequin_duckdb", "harlequin_sqlite"} <= set(adapters.split(","))
491 assert not forbidden
492
493
494 def test_config_init_imports_tomlkit_and_one_adapter(
495 tmp_path: Path, run_python: Callable[[str], subprocess.CompletedProcess[str]]
496 ) -> None:
497 """The one mode that writes a file, and so the one that pays for tomlkit.
498
499 It pays for one adapter too, because the options it writes into a profile
500 are the ones that adapter declares -- and for nothing else: it writes a
501 file rather than rows, and connects to nothing.
502
503 `tmp_path` is the subprocess's cwd and its home, so the file it writes is
504 the only config there is.
505 """
506 proc = run_python(
507 "import sys\n"
508 "sys.argv = ['hsql', '--config', 'init', '-P', 'lite', '-a', 'sqlite']\n"
509 "from harlequin.hsql import main\n"
510 "try:\n"
511 " main()\n"
512 "except SystemExit:\n"
513 " pass\n"
514 "print(','.join(sorted({m.split('.')[0] for m in sys.modules "
515 "if m.startswith('harlequin_')})), file=sys.stderr)\n"
516 "print(','.join(m for m in ('duckdb', 'pyarrow') "
517 "if m in sys.modules), file=sys.stderr)\n"
518 "print('tomlkit' in sys.modules, file=sys.stderr)\n"
519 )
520 # the last three lines, because this mode says what it wrote on stderr too
521 adapters, forbidden, tomlkit = proc.stderr.strip().split("\n")[-3:]
522 assert adapters == "harlequin_sqlite"
523 assert not forbidden
524 # the other half of the deferral: the mode that needs it still gets it
525 assert tomlkit == "True"
526 assert (tmp_path / ".harlequin.toml").exists()
527
528
529 def test_spec_imports_only_the_adapter_it_was_narrowed_to(
530 run_python: Callable[[str], subprocess.CompletedProcess[str]],
531 ) -> None:
532 """`--spec` is the one mode that pays for adapters on purpose.
533
534 Reading an adapter's options means importing it, so the whole document
535 costs every installed adapter -- which is fine for a once-per-task lookup
536 and the reason `-a` exists here. Under `-a` it costs one, and it still
537 writes a document rather than rows, so no pyarrow and no tomlkit.
538 """
539 proc = run_python(
540 "import sys\n"
541 "sys.argv = ['hsql', '--spec', '-a', 'sqlite']\n"
542 "from harlequin.hsql import main\n"
543 "try:\n"
544 " main()\n"
545 "except SystemExit:\n"
546 " pass\n"
547 "print(','.join(sorted({m.split('.')[0] for m in sys.modules "
548 "if m.startswith('harlequin_')})), file=sys.stderr)\n"
549 "print(','.join(m for m in ('duckdb', 'pyarrow', 'tomlkit') "
550 "if m in sys.modules), file=sys.stderr)\n"
551 )
552 adapters, forbidden = proc.stderr.split("\n")[:2]
553 assert adapters == "harlequin_sqlite"
554 assert not forbidden
555
556
557 def test_info_imports_only_the_adapter_it_was_narrowed_to(
558 run_python: Callable[[str], subprocess.CompletedProcess[str]],
559 ) -> None:
560 """`--info` reads capabilities off the adapter class, so it imports one per
561 adapter it reports -- and under `-a`, exactly one.
562
563 It opens no connection, and it writes a document rather than rows, so no
564 pyarrow and no tomlkit either.
565 """
566 proc = run_python(
567 "import sys\n"
568 "sys.argv = ['hsql', '--info', '-a', 'sqlite']\n"
569 "from harlequin.hsql import main\n"
570 "try:\n"
571 " main()\n"
572 "except SystemExit:\n"
573 " pass\n"
574 "print(','.join(sorted({m.split('.')[0] for m in sys.modules "
575 "if m.startswith('harlequin_')})), file=sys.stderr)\n"
576 "print(','.join(m for m in ('duckdb', 'pyarrow', 'tomlkit') "
577 "if m in sys.modules), file=sys.stderr)\n"
578 )
579 adapters, forbidden = proc.stderr.split("\n")[:2]
580 assert adapters == "harlequin_sqlite"
581 assert not forbidden
582
583
584 def test_public_names_still_resolve() -> None:
585 """Every name `harlequin/__init__.py` exported before it went lazy.
586
587 Each must resolve to the same object as a direct import from its home
588 module, and resolve to the *same* object twice (the second lookup is served
589 from the module globals, not `__getattr__`).
590 """
591 import harlequin
592 from harlequin.adapter import (
593 HarlequinAdapter,
594 HarlequinConnection,
595 HarlequinCursor,
596 )
597 from harlequin.app import Harlequin
598 from harlequin.autocomplete import HarlequinCompletion
599 from harlequin.keymap import HarlequinKeyBinding, HarlequinKeyMap
600 from harlequin.keys_app import HarlequinKeys
601 from harlequin.options import HarlequinAdapterOption, HarlequinCopyFormat
602 from harlequin.transaction_mode import HarlequinTransactionMode
603
604 expected = {
605 "Harlequin": Harlequin,
606 "HarlequinAdapter": HarlequinAdapter,
607 "HarlequinAdapterOption": HarlequinAdapterOption,
608 "HarlequinCompletion": HarlequinCompletion,
609 "HarlequinConnection": HarlequinConnection,
610 "HarlequinCopyFormat": HarlequinCopyFormat,
611 "HarlequinCursor": HarlequinCursor,
612 "HarlequinTransactionMode": HarlequinTransactionMode,
613 "HarlequinKeys": HarlequinKeys,
614 "HarlequinKeyMap": HarlequinKeyMap,
615 "HarlequinKeyBinding": HarlequinKeyBinding,
616 }
617 assert sorted(expected) == sorted(harlequin.__all__)
618 for name, obj in expected.items():
619 assert getattr(harlequin, name) is obj
620 assert getattr(harlequin, name) is getattr(harlequin, name)
621
622 assert sorted(dir(harlequin)) == sorted(harlequin.__all__)
623
624
625 def test_unknown_attribute_still_raises_attribute_error() -> None:
626 import harlequin
627
628 with pytest.raises(AttributeError):
629 _ = harlequin.NotAThing
630
631
632 def test_config_show_imports_the_adapters_its_profiles_name(
633 tmp_path: Path, run_python: Callable[[str], subprocess.CompletedProcess[str]]
634 ) -> None:
635 """What `show` buys with an import, and what it refuses to pay for.
636
637 Which of a profile's values are secret is the adapter's declaration, so a
638 mode that prints those values asks the adapter -- one import per adapter
639 its profiles name, and not one more. It stays a document either way: no
640 pyarrow, whatever it had to import to redact.
641
642 `tmp_path` is the subprocess's cwd and its home, so this file is the whole
643 of the config it discovers.
644 """
645 (tmp_path / ".harlequin.toml").write_text(
646 "[profiles.lite]\n"
647 'adapter = "sqlite"\n'
648 "[profiles.md]\n"
649 'adapter = "duckdb"\n'
650 'conn_str = [ "md:my_db?motherduck_token=hunter2-and-then-some" ]\n'
651 'md_token = "hunter2-and-then-some"\n'
652 )
653 proc = run_python(
654 "import sys\n"
655 "sys.argv = ['hsql', '--config', 'show']\n"
656 "from harlequin.hsql import main\n"
657 "try:\n"
658 " main()\n"
659 "except SystemExit:\n"
660 " pass\n"
661 "print(','.join(sorted({m.split('.')[0] for m in sys.modules "
662 "if m.startswith('harlequin_')})), file=sys.stderr)\n"
663 "print(','.join(m for m in ('pyarrow',) if m in sys.modules), "
664 "file=sys.stderr)\n"
665 )
666 assert "hunter2-and-then-some" not in proc.stdout
667 assert "********" in proc.stdout
668 # the last two lines this wrote, and the second is empty when nothing
669 # forbidden was imported -- so they are indexed rather than unpacked off a
670 # stripped string, which would have swallowed the empty one
671 lines = proc.stderr.split("\n")
672 assert lines[-3] == "harlequin_duckdb,harlequin_sqlite"
673 assert not lines[-2]
674
675
676 def test_config_show_masks_by_name_when_an_adapter_will_not_import(
677 tmp_path: Path, run_python: Callable[[str], subprocess.CompletedProcess[str]]
678 ) -> None:
679 """The backstop, and the line that says it is standing in.
680
681 A profile naming an adapter this machine cannot import has no declaration
682 to redact against, so the key's name is all there is -- and a caller whose
683 report was masked the weaker way is told which adapter it was.
684 """
685 (tmp_path / ".harlequin.toml").write_text(
686 '[profiles.pg]\nadapter = "nonesuch"\npassword = "hunter2-and-then-some"\n'
687 )
688 proc = run_python(
689 "import sys\n"
690 "sys.argv = ['hsql', '--config', 'show']\n"
691 "from harlequin.hsql import main\n"
692 "try:\n"
693 " main()\n"
694 "except SystemExit:\n"
695 " pass\n"
696 )
697 assert "hunter2-and-then-some" not in proc.stdout
698 assert 'password = "********"' in proc.stdout
699 assert "could not import nonesuch" in proc.stderr