| 1 |
"""hsql's contract: what lands on stdout, what lands on stderr, and the code. |
| 2 |
|
| 3 |
The output format and the exit codes are the part of hsql that is an API, so |
| 4 |
most of what is asserted here is a promise rather than an implementation: that |
| 5 |
stdout carries data and only data, that a truncated result says so, that the |
| 6 |
same query renders the same bytes wherever it is run. |
| 7 |
""" |
| 8 |
|
| 9 |
from __future__ import annotations |
| 10 |
|
| 11 |
import csv |
| 12 |
import io |
| 13 |
import json |
| 14 |
import sqlite3 |
| 15 |
import subprocess |
| 16 |
import sys |
| 17 |
import threading |
| 18 |
from pathlib import Path |
| 19 |
from typing import Any, Callable, Sequence, cast |
| 20 |
from unittest.mock import MagicMock |
| 21 |
|
| 22 |
import click |
| 23 |
import pytest |
| 24 |
from click.testing import CliRunner, Result |
| 25 |
|
| 26 |
from harlequin.crash import ISSUE_URL |
| 27 |
from harlequin.exception import ( |
| 28 |
HarlequinConfigError, |
| 29 |
HarlequinConnectionError, |
| 30 |
HarlequinCopyError, |
| 31 |
HarlequinQueryError, |
| 32 |
) |
| 33 |
from harlequin.hsql.cli import PROGRAM, build_cli |
| 34 |
from harlequin.hsql.diagnostics import IDE_THEMES, ExitCode, exit_code_for |
| 35 |
from harlequin.hsql.modes import CONFIG_MODES |
| 36 |
|
| 37 |
Hsql = Callable[..., Result] |
| 38 |
|
| 39 |
TEN_ROWS = ( |
| 40 |
"with recursive t(n) as (" |
| 41 |
"select 1 union all select n + 1 from t where n < 10" |
| 42 |
") select n from t" |
| 43 |
) |
| 44 |
"""Ten rows, in a spelling both bundled adapters accept.""" |
| 45 |
|
| 46 |
HUNDRED_ROWS = TEN_ROWS.replace("n < 10", "n < 100") |
| 47 |
"""More rows than any layout prints by default, and fewer than --limit fetches.""" |
| 48 |
|
| 49 |
LAYOUTS = ["table", "markdown", "md", "vertical"] |
| 50 |
TEXT_FILES = ["csv", "tsv", "json", "jsonl", "ndjson"] |
| 51 |
BINARY_FILES = ["parquet", "orc", "arrow"] |
| 52 |
FILE_FORMATS = TEXT_FILES + BINARY_FILES |
| 53 |
|
| 54 |
|
| 55 |
@pytest.fixture |
| 56 |
def hsql(no_discovered_config: None) -> Hsql: |
| 57 |
"""Invoke hsql the way the console script does, in process.""" |
| 58 |
runner = CliRunner() |
| 59 |
|
| 60 |
def _run(*args: str, **kwargs: Any) -> Result: |
| 61 |
argv = [str(arg) for arg in args] |
| 62 |
return runner.invoke(build_cli(argv), argv, catch_exceptions=False, **kwargs) |
| 63 |
|
| 64 |
return _run |
| 65 |
|
| 66 |
|
| 67 |
@pytest.fixture |
| 68 |
def duck() -> list[str]: |
| 69 |
"""The arguments that get a hermetic in-memory DuckDB.""" |
| 70 |
return ["-a", "duckdb", "--no-init", ":memory:"] |
| 71 |
|
| 72 |
|
| 73 |
@pytest.fixture(params=["duckdb", "sqlite"]) |
| 74 |
def both_adapters(request: pytest.FixtureRequest) -> list[str]: |
| 75 |
return ["-a", request.param, "--no-init", ":memory:"] |
| 76 |
|
| 77 |
|
| 78 |
# --- help, and what it costs ------------------------------------------------- |
| 79 |
|
| 80 |
|
| 81 |
def test_help_is_adapter_agnostic(hsql: Hsql) -> None: |
| 82 |
res = hsql("--help") |
| 83 |
assert res.exit_code == ExitCode.OK |
| 84 |
assert "Formats:" in res.output |
| 85 |
assert "Exit codes:" in res.output |
| 86 |
assert "Installed adapters:" in res.output |
| 87 |
assert "hsql --help -a <adapter>" in res.output |
| 88 |
# no adapter's connection options, and none of the IDE's options either |
| 89 |
assert "--no-init" not in res.output |
| 90 |
assert "--theme" not in res.output |
| 91 |
assert "--show-files" not in res.output |
| 92 |
|
| 93 |
|
| 94 |
def test_help_for_one_adapter(hsql: Hsql) -> None: |
| 95 |
res = hsql("--help", "-a", "duckdb") |
| 96 |
assert res.exit_code == ExitCode.OK |
| 97 |
assert "--no-init" in res.output |
| 98 |
assert "Showing duckdb's connection options." in res.output |
| 99 |
|
| 100 |
|
| 101 |
def test_bare_invocation_prints_help_and_leaves_stdout_empty(hsql: Hsql) -> None: |
| 102 |
"""An invocation with nothing to run is a usage error, not a result. |
| 103 |
|
| 104 |
Putting the help on stdout would mean `hsql | ...` could carry help text |
| 105 |
where data belongs, which is the one thing stdout is not allowed to do. |
| 106 |
""" |
| 107 |
res = hsql() |
| 108 |
assert res.exit_code == ExitCode.USAGE |
| 109 |
assert res.stdout == "" |
| 110 |
assert "Usage:" in res.stderr |
| 111 |
|
| 112 |
|
| 113 |
def test_no_sql_to_run(hsql: Hsql, duck: list[str]) -> None: |
| 114 |
res = hsql(*duck) |
| 115 |
assert res.exit_code == ExitCode.USAGE |
| 116 |
assert res.stdout == "" |
| 117 |
assert "no SQL to run" in res.stderr |
| 118 |
|
| 119 |
|
| 120 |
# --- the shapes of output ---------------------------------------------------- |
| 121 |
|
| 122 |
|
| 123 |
def test_select_1(hsql: Hsql, duck: list[str]) -> None: |
| 124 |
res = hsql(*duck, "-c", "select 1 as a") |
| 125 |
assert res.exit_code == ExitCode.OK |
| 126 |
assert res.stdout == " a\n---\n 1\n(1 row)\n" |
| 127 |
# the count is the footer's job. A run with nothing to warn about writes |
| 128 |
# nothing at all to stderr. |
| 129 |
assert res.stderr == "" |
| 130 |
|
| 131 |
|
| 132 |
def test_the_tac_idiom(hsql: Hsql, duck: list[str]) -> None: |
| 133 |
"""`-tAc` capturing a scalar is the first thing a script will try.""" |
| 134 |
res = hsql(*duck, "-tAc", "select 42") |
| 135 |
assert res.exit_code == ExitCode.OK |
| 136 |
assert res.stdout == "42\n" |
| 137 |
|
| 138 |
|
| 139 |
@pytest.mark.parametrize( |
| 140 |
"args,expected", |
| 141 |
[ |
| 142 |
([], " a\n---\n 1\n(1 row)\n"), |
| 143 |
(["-t"], " 1\n"), |
| 144 |
(["-A"], "a\n1\n(1 row)\n"), |
| 145 |
(["--no-header"], " 1\n(1 row)\n"), |
| 146 |
(["--no-footer"], " a\n---\n 1\n"), |
| 147 |
(["--no-header", "--no-footer"], " 1\n"), |
| 148 |
(["-tA"], "1\n"), |
| 149 |
], |
| 150 |
) |
| 151 |
def test_psql_flag_algebra( |
| 152 |
hsql: Hsql, duck: list[str], args: list[str], expected: str |
| 153 |
) -> None: |
| 154 |
"""`-t` and `-A` are independent switches, so `-tA` is not a special case. |
| 155 |
|
| 156 |
`--no-header --no-footer` is `-t` spelled out, and has to agree with it. |
| 157 |
""" |
| 158 |
res = hsql(*duck, *args, "-c", "select 1 as a") |
| 159 |
assert res.exit_code == ExitCode.OK |
| 160 |
assert res.stdout == expected |
| 161 |
|
| 162 |
|
| 163 |
@pytest.mark.parametrize("format_name", LAYOUTS + FILE_FORMATS + ["none"]) |
| 164 |
def test_every_format_runs(hsql: Hsql, duck: list[str], format_name: str) -> None: |
| 165 |
res = hsql(*duck, "--format", format_name, "-c", "select 1 as a, null as b") |
| 166 |
assert res.exit_code == ExitCode.OK |
| 167 |
assert bool(res.stdout_bytes) is (format_name != "none") |
| 168 |
|
| 169 |
|
| 170 |
@pytest.mark.parametrize( |
| 171 |
"flag,format_name", |
| 172 |
[ |
| 173 |
("--csv", "csv"), |
| 174 |
("--json", "json"), |
| 175 |
("--jsonl", "jsonl"), |
| 176 |
("--markdown", "markdown"), |
| 177 |
("--vertical", "vertical"), |
| 178 |
("-x", "vertical"), |
| 179 |
], |
| 180 |
) |
| 181 |
def test_format_shorthands( |
| 182 |
hsql: Hsql, duck: list[str], flag: str, format_name: str |
| 183 |
) -> None: |
| 184 |
sql = "select 1 as a" |
| 185 |
assert ( |
| 186 |
hsql(*duck, flag, "-c", sql).stdout_bytes |
| 187 |
== hsql(*duck, "--format", format_name, "-c", sql).stdout_bytes |
| 188 |
) |
| 189 |
|
| 190 |
|
| 191 |
@pytest.mark.parametrize( |
| 192 |
"args", |
| 193 |
[["--csv", "--json"], ["--csv", "--format", "json"], ["--format", "json", "--csv"]], |
| 194 |
) |
| 195 |
def test_two_formats_is_a_usage_error( |
| 196 |
hsql: Hsql, duck: list[str], args: list[str] |
| 197 |
) -> None: |
| 198 |
res = hsql(*duck, *args, "-c", "select 1") |
| 199 |
assert res.exit_code == ExitCode.USAGE |
| 200 |
assert res.stdout == "" |
| 201 |
assert res.stderr.startswith("hsql: error: ") |
| 202 |
|
| 203 |
|
| 204 |
def test_null_string(hsql: Hsql, duck: list[str]) -> None: |
| 205 |
assert " NULL\n" in hsql(*duck, "-c", "select null as a").stdout |
| 206 |
assert " ∅\n" in hsql(*duck, "--null-string", "∅", "-c", "select null as a").stdout |
| 207 |
# csv renders a null as nothing at all unless told otherwise |
| 208 |
assert hsql(*duck, "--csv", "-c", "select null as a").stdout == "a\n\n" |
| 209 |
assert ( |
| 210 |
hsql(*duck, "--csv", "--null-string", "∅", "-c", "select null as a").stdout |
| 211 |
== "a\n∅\n" |
| 212 |
) |
| 213 |
|
| 214 |
|
| 215 |
def test_zero_rows_is_not_an_error(hsql: Hsql, duck: list[str]) -> None: |
| 216 |
"""A0 vs A3: "matched nothing" has to be distinguishable from "failed".""" |
| 217 |
res = hsql(*duck, "--csv", "--stats", "-c", "select 1 as a where false") |
| 218 |
assert res.exit_code == ExitCode.OK |
| 219 |
assert res.stdout == "a\n" |
| 220 |
assert json.loads(res.stderr.splitlines()[-1])["rows"] == 0 |
| 221 |
|
| 222 |
|
| 223 |
# --- stdout is data ---------------------------------------------------------- |
| 224 |
|
| 225 |
|
| 226 |
@pytest.mark.parametrize("format_name", LAYOUTS + FILE_FORMATS) |
| 227 |
def test_stats_does_not_touch_stdout( |
| 228 |
hsql: Hsql, duck: list[str], format_name: str |
| 229 |
) -> None: |
| 230 |
sql = "select 1 as a, 'x' as b" |
| 231 |
plain = hsql(*duck, "--format", format_name, "-c", sql) |
| 232 |
with_stats = hsql(*duck, "--format", format_name, "--stats", "-c", sql) |
| 233 |
assert plain.stdout_bytes == with_stats.stdout_bytes |
| 234 |
assert with_stats.stderr != plain.stderr |
| 235 |
|
| 236 |
|
| 237 |
def test_stats_payload(hsql: Hsql, duck: list[str]) -> None: |
| 238 |
res = hsql(*duck, "--format", "none", "--stats", "--limit", "3", "-c", TEN_ROWS) |
| 239 |
payload = json.loads(res.stderr.splitlines()[-1]) |
| 240 |
assert payload == { |
| 241 |
"status": "ok", |
| 242 |
"statements": 1, |
| 243 |
"rows": 3, |
| 244 |
"truncated": True, |
| 245 |
"limit": 3, |
| 246 |
"elapsed_ms": payload["elapsed_ms"], |
| 247 |
"columns": [{"name": "n", "type": payload["columns"][0]["type"]}], |
| 248 |
} |
| 249 |
|
| 250 |
|
| 251 |
def test_stats_reports_a_failure(hsql: Hsql, duck: list[str]) -> None: |
| 252 |
res = hsql(*duck, "--stats", "-c", "select from nowhere") |
| 253 |
payload = json.loads(res.stderr.splitlines()[-1]) |
| 254 |
assert payload["status"] == "error" |
| 255 |
assert payload["rows"] == 0 |
| 256 |
assert payload["error"] |
| 257 |
|
| 258 |
|
| 259 |
def test_a_query_error_leaves_stdout_empty(hsql: Hsql, duck: list[str]) -> None: |
| 260 |
res = hsql(*duck, "-c", "select * from no_such_table") |
| 261 |
assert res.exit_code == ExitCode.QUERY |
| 262 |
assert res.stdout == "" |
| 263 |
assert res.stderr.startswith("hsql: error: ") |
| 264 |
# plain: no panel, no box drawing, no ANSI |
| 265 |
assert "─" not in res.stderr |
| 266 |
assert "\x1b[" not in res.stderr |
| 267 |
|
| 268 |
|
| 269 |
# --- truncation -------------------------------------------------------------- |
| 270 |
|
| 271 |
|
| 272 |
@pytest.mark.parametrize( |
| 273 |
"limit,rows,truncated", [(20, 10, False), (10, 10, False), (3, 3, True)] |
| 274 |
) |
| 275 |
def test_truncation( |
| 276 |
hsql: Hsql, both_adapters: list[str], limit: int, rows: int, truncated: bool |
| 277 |
) -> None: |
| 278 |
"""Exactly at the limit is the ambiguous case, and the reason for limit+1.""" |
| 279 |
res = hsql(*both_adapters, "--limit", str(limit), "-c", TEN_ROWS) |
| 280 |
assert res.exit_code == ExitCode.OK |
| 281 |
body = res.stdout.splitlines()[2:-1] # between the rule and the footer |
| 282 |
assert len(body) == rows |
| 283 |
assert ("truncated" in res.stderr) is truncated |
| 284 |
assert (f"({rows} of >{rows} rows)" in res.stdout) is truncated |
| 285 |
|
| 286 |
|
| 287 |
def test_one_truncated_row_is_still_rows(hsql: Hsql, duck: list[str]) -> None: |
| 288 |
"""`-l 1` is where the count and the noun disagree. |
| 289 |
|
| 290 |
One row was kept, and the limit+1 fetch proved there is another, so the |
| 291 |
total the noun has to agree with is at least two. |
| 292 |
""" |
| 293 |
res = hsql(*duck, "--limit", "1", "-c", TEN_ROWS) |
| 294 |
assert "(1 of >1 rows)" in res.stdout |
| 295 |
|
| 296 |
|
| 297 |
def test_no_limit_counts_exactly(hsql: Hsql, duck: list[str]) -> None: |
| 298 |
res = hsql(*duck, "--limit", "-1", "--stats", "--format", "none", "-c", TEN_ROWS) |
| 299 |
payload = json.loads(res.stderr.splitlines()[-1]) |
| 300 |
assert payload["rows"] == 10 |
| 301 |
assert payload["truncated"] is False |
| 302 |
assert payload["limit"] is None |
| 303 |
|
| 304 |
|
| 305 |
def test_limit_zero_fetches_a_header_and_no_rows( |
| 306 |
hsql: Hsql, both_adapters: list[str] |
| 307 |
) -> None: |
| 308 |
"""`limit 0` is how a caller asks what a query's columns are. |
| 309 |
|
| 310 |
So 0 is zero rows, and -1 is the spelling for "all of them" -- the reverse |
| 311 |
would spend the idiom on a synonym for a flag that already exists. |
| 312 |
""" |
| 313 |
res = hsql(*both_adapters, "--limit", "0", "-c", TEN_ROWS) |
| 314 |
assert res.exit_code == ExitCode.OK |
| 315 |
lines = res.stdout.splitlines() |
| 316 |
assert lines[0].strip() == "n" |
| 317 |
assert lines[-1] == "(0 of >0 rows)" |
| 318 |
|
| 319 |
|
| 320 |
@pytest.mark.parametrize("flag", ["-t", "--no-footer"]) |
| 321 |
def test_the_truncation_notice_survives_a_suppressed_footer( |
| 322 |
hsql: Hsql, duck: list[str], flag: str |
| 323 |
) -> None: |
| 324 |
"""These suppress stdout chrome. They do not suppress a warning. |
| 325 |
|
| 326 |
The footer is where a truncated result says `3 of >3`, so with it gone the |
| 327 |
stderr note is the only thing that says so at all. |
| 328 |
""" |
| 329 |
res = hsql(*duck, flag, "--limit", "3", "-c", TEN_ROWS) |
| 330 |
assert "of >3" not in res.stdout |
| 331 |
assert "results truncated at --limit 3" in res.stderr |
| 332 |
|
| 333 |
|
| 334 |
# --- the row cap the layouts print under ------------------------------------- |
| 335 |
|
| 336 |
|
| 337 |
@pytest.mark.parametrize( |
| 338 |
("format_name", "expected"), [("table", 40), ("markdown", 40), ("vertical", 10)] |
| 339 |
) |
| 340 |
def test_each_layout_has_its_own_default_cap( |
| 341 |
hsql: Hsql, duck: list[str], format_name: str, expected: int |
| 342 |
) -> None: |
| 343 |
"""A screen holds ten records vertically and forty rows as a table.""" |
| 344 |
res = hsql(*duck, "-tA", "--format", format_name, "-c", HUNDRED_ROWS) |
| 345 |
assert res.exit_code == ExitCode.OK |
| 346 |
printed = [line for line in res.stdout.splitlines() if line] |
| 347 |
assert len(printed) == expected |
| 348 |
|
| 349 |
|
| 350 |
def test_the_footer_says_what_was_not_printed(hsql: Hsql, duck: list[str]) -> None: |
| 351 |
"""The rows were fetched, so unlike a hard limit this total is exact.""" |
| 352 |
res = hsql(*duck, "-c", HUNDRED_ROWS) |
| 353 |
assert res.stdout.splitlines()[-1] == "(40 of 100 rows)" |
| 354 |
assert res.stderr == "" |
| 355 |
|
| 356 |
|
| 357 |
def test_both_caps_at_once_keep_their_own_meanings(hsql: Hsql, duck: list[str]) -> None: |
| 358 |
"""Fifty fetched of an unknown number, forty printed of the fifty.""" |
| 359 |
res = hsql(*duck, "--limit", "50", "-c", HUNDRED_ROWS) |
| 360 |
assert res.stdout.splitlines()[-1] == "(40 of >50 rows)" |
| 361 |
|
| 362 |
|
| 363 |
@pytest.mark.parametrize("value,expected", [("5", 5), ("-1", 100), ("0", 0)]) |
| 364 |
def test_display_rows_sets_the_cap( |
| 365 |
hsql: Hsql, duck: list[str], value: str, expected: int |
| 366 |
) -> None: |
| 367 |
res = hsql( |
| 368 |
*duck, "-tA", "--limit", "-1", "--display-rows", value, "-c", HUNDRED_ROWS |
| 369 |
) |
| 370 |
assert res.exit_code == ExitCode.OK |
| 371 |
assert len([line for line in res.stdout.splitlines() if line]) == expected |
| 372 |
|
| 373 |
|
| 374 |
def test_the_cap_does_not_reach_a_file_format(hsql: Hsql, duck: list[str]) -> None: |
| 375 |
"""A csv is written for a machine; dropping rows out of it is a different |
| 376 |
promise from not filling a screen with them.""" |
| 377 |
res = hsql(*duck, "--csv", "-c", HUNDRED_ROWS) |
| 378 |
assert len(res.stdout.splitlines()) == 101 # header and every row |
| 379 |
assert res.stderr == "" |
| 380 |
|
| 381 |
|
| 382 |
def test_a_cap_a_file_format_cannot_honor_says_so(hsql: Hsql, duck: list[str]) -> None: |
| 383 |
"""Asked for five rows, given a hundred: silence would read as five.""" |
| 384 |
res = hsql(*duck, "--csv", "--display-rows", "5", "-c", HUNDRED_ROWS) |
| 385 |
assert len(res.stdout.splitlines()) == 101 |
| 386 |
assert "--display-rows" in res.stderr |
| 387 |
assert "csv" in res.stderr |
| 388 |
|
| 389 |
|
| 390 |
@pytest.mark.parametrize("flag", ["-t", "--no-footer"]) |
| 391 |
def test_a_suppressed_footer_moves_the_cap_notice_to_stderr( |
| 392 |
hsql: Hsql, duck: list[str], flag: str |
| 393 |
) -> None: |
| 394 |
"""The footer is the only thing on stdout that says rows were dropped.""" |
| 395 |
res = hsql(*duck, flag, "-c", HUNDRED_ROWS) |
| 396 |
assert " 40" in res.stdout and " 41" not in res.stdout |
| 397 |
assert "rows)" not in res.stdout |
| 398 |
assert "printed 40 of 100 rows" in res.stderr |
| 399 |
|
| 400 |
|
| 401 |
def test_the_footer_is_not_restated_on_stderr(hsql: Hsql, duck: list[str]) -> None: |
| 402 |
"""`40 of 100 rows` is already under the result; stderr adds nothing.""" |
| 403 |
res = hsql(*duck, "-c", HUNDRED_ROWS) |
| 404 |
assert "printed" not in res.stderr |
| 405 |
|
| 406 |
|
| 407 |
def test_a_profile_can_set_the_cap(hsql: Hsql, tmp_path: Path) -> None: |
| 408 |
path = tmp_path / ".harlequin.toml" |
| 409 |
path.write_text( |
| 410 |
"default_profile = 'duck'\n" |
| 411 |
"\n[profiles.duck]\n" |
| 412 |
"adapter = 'duckdb'\n" |
| 413 |
"conn_str = [ ':memory:' ]\n" |
| 414 |
"no_init = true\n" |
| 415 |
"display_rows = 3\n" |
| 416 |
) |
| 417 |
res = hsql("--config-path", str(path), "-tA", "-c", HUNDRED_ROWS) |
| 418 |
assert res.stdout == "1\n2\n3\n" |
| 419 |
|
| 420 |
|
| 421 |
def test_diagnostics_follow_the_data_they_describe( |
| 422 |
tmp_path: Path, clean_env: dict[str, str] |
| 423 |
) -> None: |
| 424 |
"""stdout is block-buffered when it is a pipe; stderr is not. |
| 425 |
|
| 426 |
Without a flush between them a note overtakes the result set it is about, |
| 427 |
and `hsql ... 2>&1 | less` reads in an order the terminal never showed. Only |
| 428 |
a real subprocess can prove it: in-process, `CliRunner`'s stdout is not a |
| 429 |
pipe and so is not buffered the way the shipped command's is. |
| 430 |
""" |
| 431 |
proc = subprocess.run( |
| 432 |
[ |
| 433 |
sys.executable, |
| 434 |
"-c", |
| 435 |
"import sys; from harlequin.hsql import main; sys.argv = sys.argv[1:]; " |
| 436 |
"main()", |
| 437 |
"hsql", |
| 438 |
*["-a", "duckdb", "--no-init", ":memory:"], |
| 439 |
*["--limit", "3", "--stats", "-c", TEN_ROWS], |
| 440 |
], |
| 441 |
stdout=subprocess.PIPE, |
| 442 |
stderr=subprocess.STDOUT, |
| 443 |
text=True, |
| 444 |
cwd=tmp_path, # out of the repo, whose own .harlequin.toml would apply |
| 445 |
env=clean_env, |
| 446 |
) |
| 447 |
assert proc.returncode == ExitCode.OK, proc.stdout |
| 448 |
combined = proc.stdout |
| 449 |
assert combined.index("(3 of >3 rows)") < combined.index("results truncated") |
| 450 |
assert combined.index("results truncated") < combined.index('"status":"ok"') |
| 451 |
|
| 452 |
|
| 453 |
# --- several statements ------------------------------------------------------ |
| 454 |
|
| 455 |
|
| 456 |
def test_result_all_by_default(hsql: Hsql, duck: list[str]) -> None: |
| 457 |
res = hsql(*duck, "-tA", "-c", "select 1; select 2") |
| 458 |
assert res.stdout == "1\n2\n" |
| 459 |
|
| 460 |
|
| 461 |
@pytest.mark.parametrize("spec,expected", [("last", "2\n"), ("1", "1\n"), ("2", "2\n")]) |
| 462 |
def test_result_selection( |
| 463 |
hsql: Hsql, duck: list[str], spec: str, expected: str |
| 464 |
) -> None: |
| 465 |
res = hsql(*duck, "-tA", "--result", spec, "-c", "select 1; select 2") |
| 466 |
assert res.exit_code == ExitCode.OK |
| 467 |
assert res.stdout == expected |
| 468 |
|
| 469 |
|
| 470 |
@pytest.mark.parametrize("spec", ["3", "0", "penultimate"]) |
| 471 |
def test_bad_result_selection(hsql: Hsql, duck: list[str], spec: str) -> None: |
| 472 |
res = hsql(*duck, "--result", spec, "-c", "select 1; select 2") |
| 473 |
assert res.exit_code == ExitCode.USAGE |
| 474 |
assert res.stdout == "" |
| 475 |
|
| 476 |
|
| 477 |
def test_two_result_sets_will_not_fit_in_a_csv(hsql: Hsql, duck: list[str]) -> None: |
| 478 |
"""Two headers in one file is silent corruption; an error costs one retry.""" |
| 479 |
res = hsql(*duck, "--csv", "-c", "select 1; select 2") |
| 480 |
assert res.exit_code == ExitCode.USAGE |
| 481 |
assert res.stdout == "" |
| 482 |
assert "2 result sets, but csv holds one" in res.stderr |
| 483 |
assert "--result last" in res.stderr |
| 484 |
assert "-o DIR" in res.stderr |
| 485 |
|
| 486 |
|
| 487 |
def test_two_result_sets_do_fit_in_jsonl(hsql: Hsql, duck: list[str]) -> None: |
| 488 |
res = hsql(*duck, "--jsonl", "-c", "select 1 as a; select 2 as a") |
| 489 |
assert res.exit_code == ExitCode.OK |
| 490 |
assert res.stdout == '{"a":1}\n{"a":2}\n' |
| 491 |
|
| 492 |
|
| 493 |
def test_on_error_stop(hsql: Hsql, duck: list[str]) -> None: |
| 494 |
res = hsql(*duck, "-tA", "-c", "select 1; select bad; select 3") |
| 495 |
assert res.exit_code == ExitCode.QUERY |
| 496 |
assert res.stdout == "1\n" |
| 497 |
|
| 498 |
|
| 499 |
def test_on_error_continue(hsql: Hsql, duck: list[str]) -> None: |
| 500 |
res = hsql( |
| 501 |
*duck, "-tA", "--on-error", "continue", "-c", "select 1; select bad; select 3" |
| 502 |
) |
| 503 |
assert res.exit_code == ExitCode.QUERY, "a run with a failure in it is not ok" |
| 504 |
assert res.stdout == "1\n3\n" |
| 505 |
|
| 506 |
|
| 507 |
def test_ddl_produces_no_result_set(hsql: Hsql, duck: list[str]) -> None: |
| 508 |
res = hsql(*duck, "-c", "create table t (a int)", "-c", "insert into t values (1)") |
| 509 |
assert res.exit_code == ExitCode.OK |
| 510 |
assert res.stdout == "" |
| 511 |
|
| 512 |
|
| 513 |
# --- where the SQL comes from ------------------------------------------------ |
| 514 |
|
| 515 |
|
| 516 |
def test_file_source(hsql: Hsql, duck: list[str], tmp_path: Path) -> None: |
| 517 |
script = tmp_path / "q.sql" |
| 518 |
script.write_text("select 42 as answer;\n") |
| 519 |
res = hsql(*duck, "-tA", "-f", str(script)) |
| 520 |
assert res.exit_code == ExitCode.OK |
| 521 |
assert res.stdout == "42\n" |
| 522 |
|
| 523 |
|
| 524 |
def test_stdin_source(hsql: Hsql, duck: list[str]) -> None: |
| 525 |
res = hsql(*duck, "-tA", "-f", "-", input="select 42\n") |
| 526 |
assert res.exit_code == ExitCode.OK |
| 527 |
assert res.stdout == "42\n" |
| 528 |
|
| 529 |
|
| 530 |
def test_sources_run_in_the_order_they_were_given( |
| 531 |
hsql: Hsql, duck: list[str], tmp_path: Path |
| 532 |
) -> None: |
| 533 |
script = tmp_path / "setup.sql" |
| 534 |
script.write_text("create table t (a int); insert into t values (7);") |
| 535 |
res = hsql(*duck, "-tA", "-f", str(script), "-c", "select a from t") |
| 536 |
assert res.exit_code == ExitCode.OK |
| 537 |
assert res.stdout == "7\n" |
| 538 |
|
| 539 |
|
| 540 |
def test_a_missing_file_is_a_usage_error(hsql: Hsql, duck: list[str]) -> None: |
| 541 |
res = hsql(*duck, "-f", "no-such-file.sql") |
| 542 |
assert res.exit_code == ExitCode.USAGE |
| 543 |
assert "could not read" in res.stderr |
| 544 |
|
| 545 |
|
| 546 |
def test_a_binary_file_is_a_usage_error( |
| 547 |
hsql: Hsql, duck: list[str], tmp_path: Path |
| 548 |
) -> None: |
| 549 |
"""A file that isn't text says so, instead of raising a decode error.""" |
| 550 |
script = tmp_path / "database.db" |
| 551 |
script.write_bytes(b"\xcd\xe3k.4,9\x97DUCK") |
| 552 |
res = hsql(*duck, "-f", str(script)) |
| 553 |
assert res.exit_code == ExitCode.USAGE |
| 554 |
assert "could not read" in res.stderr |
| 555 |
assert "not UTF-8 text" in res.stderr |
| 556 |
|
| 557 |
|
| 558 |
def test_binary_stdin_is_a_usage_error(hsql: Hsql, duck: list[str]) -> None: |
| 559 |
res = hsql(*duck, "-f", "-", input=b"\xcd\xe3k.4,9\x97DUCK") |
| 560 |
assert res.exit_code == ExitCode.USAGE |
| 561 |
assert "could not read standard input" in res.stderr |
| 562 |
|
| 563 |
|
| 564 |
# --- writing to a file ------------------------------------------------------- |
| 565 |
|
| 566 |
|
| 567 |
@pytest.mark.parametrize( |
| 568 |
"format_name,sql", |
| 569 |
[ |
| 570 |
*( |
| 571 |
(name, "select 1 as a, null as b, 'ü' as c") |
| 572 |
for name in LAYOUTS + TEXT_FILES |
| 573 |
), |
| 574 |
# A null's value bytes are whatever was in the buffer, and Arrow does |
| 575 |
# not zero them -- so two processes writing the same null column write |
| 576 |
# different padding. That is the data, not the write path, so the |
| 577 |
# columnar formats are checked without one. |
| 578 |
*((name, "select 1 as a, 'ü' as c") for name in BINARY_FILES), |
| 579 |
], |
| 580 |
) |
| 581 |
def test_output_file_and_redirect_agree( |
| 582 |
hsql: Hsql, duck: list[str], tmp_path: Path, format_name: str, sql: str |
| 583 |
) -> None: |
| 584 |
"""The one thing a second write path could plausibly get wrong.""" |
| 585 |
destination = tmp_path / f"out.{format_name}" |
| 586 |
written = hsql(*duck, "--format", format_name, "-o", str(destination), "-c", sql) |
| 587 |
piped = hsql(*duck, "--format", format_name, "-c", sql) |
| 588 |
assert written.exit_code == ExitCode.OK |
| 589 |
assert written.stdout_bytes == b"" |
| 590 |
assert destination.read_bytes() == piped.stdout_bytes |
| 591 |
|
| 592 |
|
| 593 |
def test_a_file_never_gets_color(hsql: Hsql, duck: list[str], tmp_path: Path) -> None: |
| 594 |
destination = tmp_path / "out.txt" |
| 595 |
hsql(*duck, "--color", "always", "-o", str(destination), "-c", "select 1 as a") |
| 596 |
assert b"\x1b[" not in destination.read_bytes() |
| 597 |
|
| 598 |
|
| 599 |
def test_an_unwritable_destination_is_a_usage_error( |
| 600 |
hsql: Hsql, duck: list[str], tmp_path: Path |
| 601 |
) -> None: |
| 602 |
in_the_way = tmp_path / "not-a-directory" |
| 603 |
in_the_way.write_text("") |
| 604 |
res = hsql(*duck, "-o", str(in_the_way / "out.csv"), "-c", "select 1") |
| 605 |
assert res.exit_code == ExitCode.USAGE |
| 606 |
assert res.stderr.startswith("hsql: error: ") |
| 607 |
|
| 608 |
|
| 609 |
def test_a_missing_parent_directory_is_created( |
| 610 |
hsql: Hsql, duck: list[str], tmp_path: Path |
| 611 |
) -> None: |
| 612 |
destination = tmp_path / "exports" / "nested" / "out.csv" |
| 613 |
res = hsql(*duck, "-o", str(destination), "-tA", "-c", "select 1") |
| 614 |
assert res.exit_code == ExitCode.OK |
| 615 |
assert destination.read_text() == "1\n" |
| 616 |
|
| 617 |
|
| 618 |
# --- writing to a directory -------------------------------------------------- |
| 619 |
|
| 620 |
|
| 621 |
def test_a_directory_takes_one_file_per_result_set( |
| 622 |
hsql: Hsql, duck: list[str], tmp_path: Path |
| 623 |
) -> None: |
| 624 |
"""A folder is what lets a format that holds one result set take a script |
| 625 |
that produced several.""" |
| 626 |
destination = tmp_path / "exports" |
| 627 |
res = hsql(*duck, "--csv", "-o", str(destination), "-c", "select 1; select 2") |
| 628 |
assert res.exit_code == ExitCode.OK |
| 629 |
assert res.stdout == "" |
| 630 |
assert (destination / "results_1.csv").read_text() == "1\n1\n" |
| 631 |
assert (destination / "results_2.csv").read_text() == "2\n2\n" |
| 632 |
|
| 633 |
|
| 634 |
def test_a_directory_names_what_it_wrote_on_stderr( |
| 635 |
hsql: Hsql, duck: list[str], tmp_path: Path |
| 636 |
) -> None: |
| 637 |
"""The caller did not name these files, so stderr says what they are.""" |
| 638 |
destination = tmp_path / "exports" |
| 639 |
res = hsql(*duck, "--csv", "-o", str(destination), "-c", "select 1; select 2") |
| 640 |
assert "results_1.csv" in res.stderr |
| 641 |
assert "results_2.csv" in res.stderr |
| 642 |
|
| 643 |
|
| 644 |
def test_a_named_file_is_not_named_again( |
| 645 |
hsql: Hsql, duck: list[str], tmp_path: Path |
| 646 |
) -> None: |
| 647 |
destination = tmp_path / "out.csv" |
| 648 |
res = hsql(*duck, "-o", str(destination), "-c", "select 1") |
| 649 |
assert res.stderr == "" |
| 650 |
|
| 651 |
|
| 652 |
@pytest.mark.parametrize("format_name", FILE_FORMATS + LAYOUTS) |
| 653 |
def test_a_directory_file_holds_what_the_same_format_writes( |
| 654 |
hsql: Hsql, duck: list[str], tmp_path: Path, format_name: str |
| 655 |
) -> None: |
| 656 |
destination = tmp_path / "exports" |
| 657 |
hsql(*duck, "--format", format_name, "-o", str(destination), "-c", "select 1 as a") |
| 658 |
(written,) = destination.iterdir() |
| 659 |
piped = hsql(*duck, "--format", format_name, "-c", "select 1 as a") |
| 660 |
assert written.read_bytes() == piped.stdout_bytes |
| 661 |
|
| 662 |
|
| 663 |
def test_a_directory_is_created_when_it_is_not_there( |
| 664 |
hsql: Hsql, duck: list[str], tmp_path: Path |
| 665 |
) -> None: |
| 666 |
destination = tmp_path / "exports" / "nested" |
| 667 |
res = hsql(*duck, "--csv", "-o", f"{destination}/", "-c", "select 1") |
| 668 |
assert res.exit_code == ExitCode.OK |
| 669 |
assert (destination / "results_1.csv").is_file() |
| 670 |
|
| 671 |
|
| 672 |
def test_an_existing_directory_takes_files_whatever_it_is_called( |
| 673 |
hsql: Hsql, duck: list[str], tmp_path: Path |
| 674 |
) -> None: |
| 675 |
destination = tmp_path / "exports.old" |
| 676 |
destination.mkdir() |
| 677 |
res = hsql(*duck, "--csv", "-o", str(destination), "-c", "select 1") |
| 678 |
assert res.exit_code == ExitCode.OK |
| 679 |
assert (destination / "results_1.csv").is_file() |
| 680 |
|
| 681 |
|
| 682 |
@pytest.mark.parametrize( |
| 683 |
"args,written", |
| 684 |
[ |
| 685 |
(("--info",), "info.json"), |
| 686 |
(("--spec",), "spec.json"), |
| 687 |
(("--config", "show"), "config-show.toml"), |
| 688 |
(("--config", "show", "--format", "json"), "config-show.json"), |
| 689 |
(("--config", "schema"), "config-schema.json"), |
| 690 |
(("--config", "list-profiles", "--csv"), "config-list-profiles.csv"), |
| 691 |
], |
| 692 |
) |
| 693 |
def test_a_mode_names_its_document_in_a_directory( |
| 694 |
hsql: Hsql, tmp_path: Path, args: tuple[str, ...], written: str |
| 695 |
) -> None: |
| 696 |
"""A document has no position to be numbered by, so it takes its own name -- |
| 697 |
and the extension of what it is actually written as.""" |
| 698 |
destination = tmp_path / "exports" |
| 699 |
res = hsql(*args, "-o", str(destination)) |
| 700 |
assert res.stdout == "" |
| 701 |
assert (destination / written).stat().st_size > 0 |
| 702 |
assert written in res.stderr |
| 703 |
|
| 704 |
|
| 705 |
def test_format_none_names_no_file(hsql: Hsql, duck: list[str], tmp_path: Path) -> None: |
| 706 |
"""The rows are discarded, so there is no file to write and no folder to |
| 707 |
make -- but the run still reports what it did.""" |
| 708 |
destination = tmp_path / "exports" |
| 709 |
res = hsql( |
| 710 |
*duck, "--format", "none", "-o", str(destination), "--stats", "-c", "select 1" |
| 711 |
) |
| 712 |
assert res.exit_code == ExitCode.OK |
| 713 |
assert not destination.exists() |
| 714 |
assert json.loads(res.stderr.splitlines()[-1])["rows"] == 1 |
| 715 |
|
| 716 |
|
| 717 |
# --- color ------------------------------------------------------------------- |
| 718 |
|
| 719 |
|
| 720 |
def test_color_is_off_by_default(hsql: Hsql, duck: list[str]) -> None: |
| 721 |
"""Principle 4: the bytes may not depend on what stdout happens to be.""" |
| 722 |
assert "\x1b[" not in hsql(*duck, "-c", "select 1 as a").stdout |
| 723 |
|
| 724 |
|
| 725 |
def test_color_always(hsql: Hsql, duck: list[str]) -> None: |
| 726 |
assert "\x1b[" in hsql(*duck, "--color", "always", "-c", "select null as a").stdout |
| 727 |
|
| 728 |
|
| 729 |
# --- config, profiles and adapters ------------------------------------------- |
| 730 |
|
| 731 |
|
| 732 |
@pytest.fixture |
| 733 |
def config_file(tmp_path: Path) -> Path: |
| 734 |
path = tmp_path / ".harlequin.toml" |
| 735 |
path.write_text( |
| 736 |
"default_profile = 'duck'\n" |
| 737 |
"\n[profiles.duck]\n" |
| 738 |
"adapter = 'duckdb'\n" |
| 739 |
"conn_str = [ ':memory:' ]\n" |
| 740 |
"no_init = true\n" |
| 741 |
"theme = 'fruity'\n" |
| 742 |
"locale = 'de_DE.UTF-8'\n" |
| 743 |
"viewer_max_rows = 7\n" |
| 744 |
"limit = 3\n" |
| 745 |
"\n[profiles.lite]\n" |
| 746 |
"adapter = 'sqlite'\n" |
| 747 |
"conn_str = [ ':memory:' ]\n" |
| 748 |
) |
| 749 |
return path |
| 750 |
|
| 751 |
|
| 752 |
def test_the_default_profile_applies(hsql: Hsql, config_file: Path) -> None: |
| 753 |
"""And the IDE's own keys are dropped rather than handed to the adapter.""" |
| 754 |
res = hsql("--config-path", str(config_file), "-tA", "-c", TEN_ROWS) |
| 755 |
assert res.exit_code == ExitCode.OK |
| 756 |
# `limit` is the one both commands honor; `viewer_max_rows = 7` is the |
| 757 |
# IDE's cap on its own widget, and means nothing here. |
| 758 |
assert res.stdout == "".join(f"{n}\n" for n in range(1, 4)), "profile limit of 3" |
| 759 |
|
| 760 |
|
| 761 |
def test_a_cli_option_beats_the_profile(hsql: Hsql, config_file: Path) -> None: |
| 762 |
res = hsql("--config-path", str(config_file), "-tA", "--limit", "2", "-c", TEN_ROWS) |
| 763 |
assert res.stdout == "1\n2\n" |
| 764 |
|
| 765 |
|
| 766 |
def test_a_profile_names_its_adapter(hsql: Hsql, config_file: Path) -> None: |
| 767 |
res = hsql( |
| 768 |
"--config-path", str(config_file), "-P", "lite", "-tA", "-c", "select 42" |
| 769 |
) |
| 770 |
assert res.exit_code == ExitCode.OK |
| 771 |
assert res.stdout == "42\n" |
| 772 |
|
| 773 |
|
| 774 |
def test_help_for_the_profiles_adapter(hsql: Hsql, config_file: Path) -> None: |
| 775 |
res = hsql("--config-path", str(config_file), "-P", "lite", "--help") |
| 776 |
assert "Showing sqlite's connection options." in res.output |
| 777 |
|
| 778 |
|
| 779 |
def test_an_unknown_profile_is_a_usage_error(hsql: Hsql, config_file: Path) -> None: |
| 780 |
res = hsql("--config-path", str(config_file), "-P", "nope", "-c", "select 1") |
| 781 |
assert res.exit_code == ExitCode.USAGE |
| 782 |
assert res.stdout == "" |
| 783 |
assert "profile" in res.stderr |
| 784 |
|
| 785 |
|
| 786 |
def test_an_option_the_adapter_never_declared_is_a_usage_error( |
| 787 |
hsql: Hsql, tmp_path: Path |
| 788 |
) -> None: |
| 789 |
"""Before the connection, and before the query it would have run. |
| 790 |
|
| 791 |
The adapter's own constructor takes supersets of what it declares, so this |
| 792 |
is the only place a misspelling can be caught -- and a run that believed it |
| 793 |
was read-only should not reach the database at all. |
| 794 |
""" |
| 795 |
path = tmp_path / ".harlequin.toml" |
| 796 |
path.write_text( |
| 797 |
"[profiles.duck]\n" |
| 798 |
"adapter = 'duckdb'\n" |
| 799 |
"conn_str = [ ':memory:' ]\n" |
| 800 |
"reed_only = true\n" |
| 801 |
) |
| 802 |
res = hsql("--config-path", str(path), "-P", "duck", "-c", "select 1") |
| 803 |
assert res.exit_code == ExitCode.USAGE |
| 804 |
assert res.stdout == "" |
| 805 |
assert "reed_only" in res.stderr |
| 806 |
assert "read_only" in res.stderr |
| 807 |
assert "duckdb" in res.stderr |
| 808 |
|
| 809 |
|
| 810 |
def test_an_unknown_adapter_is_a_usage_error(hsql: Hsql) -> None: |
| 811 |
res = hsql("-a", "nosuchadapter", "-c", "select 1") |
| 812 |
assert res.exit_code == ExitCode.USAGE |
| 813 |
assert res.stdout == "" |
| 814 |
|
| 815 |
|
| 816 |
def test_a_connection_failure_exits_three(hsql: Hsql, tmp_path: Path) -> None: |
| 817 |
res = hsql( |
| 818 |
"-a", |
| 819 |
"duckdb", |
| 820 |
"--no-init", |
| 821 |
str(tmp_path / "nope" / "db.duckdb"), |
| 822 |
"-c", |
| 823 |
"select 1", |
| 824 |
) |
| 825 |
assert res.exit_code == ExitCode.CONNECTION |
| 826 |
assert res.stdout == "" |
| 827 |
|
| 828 |
|
| 829 |
# --- pointing back at the IDE ------------------------------------------------ |
| 830 |
|
| 831 |
|
| 832 |
def test_a_theme_name_after_tuples_only_is_explained( |
| 833 |
hsql: Hsql, duck: list[str], monkeypatch: pytest.MonkeyPatch, tmp_path: Path |
| 834 |
) -> None: |
| 835 |
"""`-t nord` is the one habit the two commands can silently disagree on. |
| 836 |
|
| 837 |
In a tmp cwd because it succeeds: DuckDB creates a database file named |
| 838 |
`nord` rather than refusing, which is the whole reason this is worth a note. |
| 839 |
""" |
| 840 |
monkeypatch.chdir(tmp_path) |
| 841 |
res = hsql("-a", "duckdb", "--no-init", "-t", "nord", "-c", "select 1") |
| 842 |
assert res.exit_code == ExitCode.OK |
| 843 |
assert res.stdout.strip() == "1" |
| 844 |
assert "hsql has no themes" not in res.stdout |
| 845 |
assert "hsql has no themes" in res.stderr |
| 846 |
assert "'nord' was read as a connection string" in res.stderr |
| 847 |
|
| 848 |
|
| 849 |
def test_the_theme_hint_needs_both_halves( |
| 850 |
hsql: Hsql, duck: list[str], monkeypatch: pytest.MonkeyPatch, tmp_path: Path |
| 851 |
) -> None: |
| 852 |
"""A theme name alone is a database, and `-t` alone is just psql's flag.""" |
| 853 |
monkeypatch.chdir(tmp_path) |
| 854 |
without_dash_t = hsql("-a", "duckdb", "--no-init", "nord", "-c", "select 1") |
| 855 |
assert "hsql has no themes" not in without_dash_t.stderr |
| 856 |
|
| 857 |
without_a_theme = hsql(*duck, "-t", "-c", "select 1") |
| 858 |
assert "hsql has no themes" not in without_a_theme.stderr |
| 859 |
|
| 860 |
|
| 861 |
def test_the_theme_names_are_the_ides() -> None: |
| 862 |
"""The copy in `diagnostics` cannot import the original: it is Textual's. |
| 863 |
|
| 864 |
So this is the seam where a Textual upgrade that adds a theme shows up. |
| 865 |
""" |
| 866 |
from harlequin.colors import VALID_THEMES |
| 867 |
|
| 868 |
assert IDE_THEMES == frozenset(VALID_THEMES) |
| 869 |
|
| 870 |
|
| 871 |
# --- the exit-code mapping --------------------------------------------------- |
| 872 |
|
| 873 |
|
| 874 |
@pytest.mark.parametrize( |
| 875 |
"error,code", |
| 876 |
[ |
| 877 |
(HarlequinQueryError("boom"), ExitCode.QUERY), |
| 878 |
(HarlequinConfigError("boom"), ExitCode.USAGE), |
| 879 |
(HarlequinConnectionError("boom"), ExitCode.CONNECTION), |
| 880 |
(HarlequinCopyError("boom"), ExitCode.QUERY), |
| 881 |
(KeyboardInterrupt(), ExitCode.INTERRUPT), |
| 882 |
(RuntimeError("boom"), ExitCode.QUERY), |
| 883 |
], |
| 884 |
) |
| 885 |
def test_exit_code_for(error: BaseException, code: ExitCode) -> None: |
| 886 |
assert exit_code_for(error) == code |
| 887 |
|
| 888 |
|
| 889 |
# --- how the command gets built ---------------------------------------------- |
| 890 |
|
| 891 |
|
| 892 |
def test_the_config_is_read_once( |
| 893 |
hsql: Hsql, duck: list[str], monkeypatch: pytest.MonkeyPatch |
| 894 |
) -> None: |
| 895 |
"""Both phases want the profile; only one of them may go to disk for it.""" |
| 896 |
import harlequin.config |
| 897 |
|
| 898 |
reads: list[object] = [] |
| 899 |
real = harlequin.config.load_profile |
| 900 |
|
| 901 |
def counting(config_path: Any, profile_name: Any) -> Any: |
| 902 |
reads.append(config_path) |
| 903 |
return real(config_path=config_path, profile_name=profile_name) |
| 904 |
|
| 905 |
monkeypatch.setattr("harlequin.first_pass.load_profile", counting) |
| 906 |
res = hsql(*duck, "-c", "select 1") |
| 907 |
assert res.exit_code == ExitCode.OK |
| 908 |
assert len(reads) == 1 |
| 909 |
|
| 910 |
|
| 911 |
def test_hsql_does_not_claim_dash_h() -> None: |
| 912 |
"""`-h` belongs to `--host`. |
| 913 |
|
| 914 |
psql spells it that way, and the postgres and mysql adapters both declare |
| 915 |
it. Taking it for help would silently strip it from them. |
| 916 |
""" |
| 917 |
cmd = build_cli(["--help"]) |
| 918 |
with click.Context(cmd) as ctx: |
| 919 |
opts = {opt for param in cmd.get_params(ctx) for opt in param.opts} |
| 920 |
assert "--help" in opts |
| 921 |
assert "-h" not in opts |
| 922 |
|
| 923 |
|
| 924 |
def test_an_adapter_option_cannot_shadow_an_hsql_flag() -> None: |
| 925 |
from harlequin.adapter import HarlequinAdapter |
| 926 |
from harlequin.first_pass import attach_adapter_options, command_spellings |
| 927 |
from harlequin.options import TextOption |
| 928 |
|
| 929 |
class _Adapter: |
| 930 |
ADAPTER_OPTIONS = [ |
| 931 |
TextOption(name="collides", description="x", short_decls=["-c"]), |
| 932 |
TextOption(name="format", description="x"), |
| 933 |
TextOption(name="fine", description="x", short_decls=["-Z"]), |
| 934 |
] |
| 935 |
|
| 936 |
cmd = build_cli(["--help"]) |
| 937 |
reserved, taken = command_spellings(cmd) |
| 938 |
attach_adapter_options( |
| 939 |
cmd, |
| 940 |
cast("type[HarlequinAdapter]", _Adapter), |
| 941 |
reserved=reserved, |
| 942 |
taken=taken, |
| 943 |
) |
| 944 |
by_name: dict[str | None, list[click.Parameter]] = {} |
| 945 |
for param in cmd.params: |
| 946 |
by_name.setdefault(param.name, []).append(param) |
| 947 |
|
| 948 |
# the colliding short goes; the option survives under its long spelling |
| 949 |
(collides,) = by_name["collides"] |
| 950 |
assert collides.opts == ["--collides"] |
| 951 |
# an option whose only spelling hsql already owns is dropped whole, so the |
| 952 |
# command is left with hsql's own --format and no duplicate |
| 953 |
(fmt,) = by_name["format"] |
| 954 |
assert fmt.opts == ["--format"] |
| 955 |
# anything that doesn't collide arrives untouched |
| 956 |
(fine,) = by_name["fine"] |
| 957 |
assert set(fine.opts) == {"--fine", "-Z"} |
| 958 |
|
| 959 |
|
| 960 |
# --- `--config`, the mode that reports on config files ----------------------- |
| 961 |
|
| 962 |
|
| 963 |
@pytest.fixture |
| 964 |
def config_dirs( |
| 965 |
tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch |
| 966 |
) -> tuple[Path, Path]: |
| 967 |
"""A cwd and a home directory to write config files into, and nothing else. |
| 968 |
|
| 969 |
Returned nearest first, which is the order the files in them are read, and |
| 970 |
so the order everything below asserts about. |
| 971 |
""" |
| 972 |
mock_cwd = tmp_path_factory.mktemp("cwd") |
| 973 |
mock_home = tmp_path_factory.mktemp("home") |
| 974 |
monkeypatch.setattr( |
| 975 |
"harlequin.config._search_directories", |
| 976 |
lambda: [ |
| 977 |
(mock_cwd, (".harlequin.toml",)), |
| 978 |
(mock_home, (".harlequin.toml",)), |
| 979 |
], |
| 980 |
) |
| 981 |
return mock_cwd, mock_home |
| 982 |
|
| 983 |
|
| 984 |
@pytest.fixture |
| 985 |
def two_config_files(config_dirs: tuple[Path, Path]) -> tuple[Path, Path]: |
| 986 |
"""A home file and a project file that disagree about one profile. |
| 987 |
|
| 988 |
The shape every question about the merge is asked in: `shared` is defined |
| 989 |
twice, `personal` and `project` once each, and the default is the home |
| 990 |
file's. |
| 991 |
""" |
| 992 |
cwd, home = config_dirs |
| 993 |
(home / ".harlequin.toml").write_text( |
| 994 |
'default_profile = "personal"\n' |
| 995 |
"[profiles.personal]\n" |
| 996 |
'adapter = "duckdb"\n' |
| 997 |
"limit = 200000\n" |
| 998 |
"[profiles.shared]\n" |
| 999 |
'adapter = "sqlite"\n' |
| 1000 |
) |
| 1001 |
(cwd / ".harlequin.toml").write_text( |
| 1002 |
"[profiles.shared]\n" |
| 1003 |
'adapter = "duckdb"\n' |
| 1004 |
"[profiles.project]\n" |
| 1005 |
'adapter = "sqlite"\n' |
| 1006 |
) |
| 1007 |
return cwd / ".harlequin.toml", home / ".harlequin.toml" |
| 1008 |
|
| 1009 |
|
| 1010 |
def test_config_show_names_the_file_every_value_came_from( |
| 1011 |
hsql: Hsql, two_config_files: tuple[Path, Path] |
| 1012 |
) -> None: |
| 1013 |
"""The single best troubleshooting artifact in the command. |
| 1014 |
|
| 1015 |
Asserted whole rather than by substring: what makes this worth having is |
| 1016 |
that a reader can see the merge, so the arrangement is the contract. |
| 1017 |
""" |
| 1018 |
project, home = two_config_files |
| 1019 |
res = hsql("--config", "show") |
| 1020 |
assert res.exit_code == ExitCode.OK |
| 1021 |
assert res.stdout == ( |
| 1022 |
f'default_profile = "personal" # from {home}\n' |
| 1023 |
"\n" |
| 1024 |
f"[profiles.personal] # from {home}\n" |
| 1025 |
'adapter = "duckdb"\n' |
| 1026 |
"limit = 200000\n" |
| 1027 |
"\n" |
| 1028 |
f"[profiles.project] # from {project}\n" |
| 1029 |
'adapter = "sqlite"\n' |
| 1030 |
"\n" |
| 1031 |
f"[profiles.shared] # from {project}, overriding {home}\n" |
| 1032 |
'adapter = "duckdb"\n' |
| 1033 |
) |
| 1034 |
|
| 1035 |
|
| 1036 |
def test_config_show_writes_toml_a_parser_reads_back( |
| 1037 |
hsql: Hsql, two_config_files: tuple[Path, Path] |
| 1038 |
) -> None: |
| 1039 |
"""What it prints is the language it is about. |
| 1040 |
|
| 1041 |
A document that says `# from ...` and cannot be parsed would be a report |
| 1042 |
about TOML rather than TOML, and the whole point of the spelling is that a |
| 1043 |
reader can paste a table of it into the file they are fixing. |
| 1044 |
""" |
| 1045 |
if sys.version_info >= (3, 11): |
| 1046 |
import tomllib |
| 1047 |
else: |
| 1048 |
import tomli as tomllib |
| 1049 |
|
| 1050 |
res = hsql("--config", "show") |
| 1051 |
assert tomllib.loads(res.stdout) == { |
| 1052 |
"default_profile": "personal", |
| 1053 |
"profiles": { |
| 1054 |
"personal": {"adapter": "duckdb", "limit": 200000}, |
| 1055 |
"project": {"adapter": "sqlite"}, |
| 1056 |
"shared": {"adapter": "duckdb"}, |
| 1057 |
}, |
| 1058 |
} |
| 1059 |
|
| 1060 |
|
| 1061 |
def test_config_show_writes_every_toml_type_back( |
| 1062 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1063 |
) -> None: |
| 1064 |
"""A profile holds whatever TOML holds, and this has to write all of it.""" |
| 1065 |
if sys.version_info >= (3, 11): |
| 1066 |
import tomllib |
| 1067 |
else: |
| 1068 |
import tomli as tomllib |
| 1069 |
|
| 1070 |
cwd, _ = config_dirs |
| 1071 |
written = ( |
| 1072 |
"[profiles.everything]\n" |
| 1073 |
'text = "a \\"quoted\\" \\u00e9"\n' |
| 1074 |
"number = 5432\n" |
| 1075 |
"fraction = 1.5\n" |
| 1076 |
"flag = true\n" |
| 1077 |
'list = ["httpfs", "spatial"]\n' |
| 1078 |
'table = { host = "localhost", port = 5432 }\n' |
| 1079 |
"moment = 2026-08-18T09:30:00\n" |
| 1080 |
'"dotted.key" = "quoted"\n' |
| 1081 |
) |
| 1082 |
(cwd / ".harlequin.toml").write_text(written, encoding="utf-8") |
| 1083 |
|
| 1084 |
res = hsql("--config", "show") |
| 1085 |
assert res.exit_code == ExitCode.OK |
| 1086 |
# the é survives as itself: a config file is UTF-8, and an escape would be |
| 1087 |
# something the reader has to decode to recognize their own value |
| 1088 |
assert "é" in res.stdout |
| 1089 |
assert tomllib.loads(res.stdout)["profiles"] == tomllib.loads(written)["profiles"] |
| 1090 |
|
| 1091 |
|
| 1092 |
def test_config_show_json_carries_the_same_provenance( |
| 1093 |
hsql: Hsql, two_config_files: tuple[Path, Path] |
| 1094 |
) -> None: |
| 1095 |
project, home = two_config_files |
| 1096 |
res = hsql("--config", "show", "--json") |
| 1097 |
assert res.exit_code == ExitCode.OK |
| 1098 |
assert json.loads(res.stdout) == { |
| 1099 |
"default_profile": { |
| 1100 |
"value": "personal", |
| 1101 |
"from": str(home), |
| 1102 |
"overrode": [], |
| 1103 |
}, |
| 1104 |
"profiles": { |
| 1105 |
"personal": { |
| 1106 |
"value": {"adapter": "duckdb", "limit": 200000}, |
| 1107 |
"from": str(home), |
| 1108 |
"overrode": [], |
| 1109 |
}, |
| 1110 |
"project": { |
| 1111 |
"value": {"adapter": "sqlite"}, |
| 1112 |
"from": str(project), |
| 1113 |
"overrode": [], |
| 1114 |
}, |
| 1115 |
"shared": { |
| 1116 |
"value": {"adapter": "duckdb"}, |
| 1117 |
"from": str(project), |
| 1118 |
"overrode": [str(home)], |
| 1119 |
}, |
| 1120 |
}, |
| 1121 |
"keymaps": {}, |
| 1122 |
} |
| 1123 |
|
| 1124 |
|
| 1125 |
def test_config_show_json_keeps_its_shape_with_nothing_to_report( |
| 1126 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1127 |
) -> None: |
| 1128 |
"""A key nothing defines is null, not a key that is missing. |
| 1129 |
|
| 1130 |
A caller that has to branch on whether a key is there is a caller writing |
| 1131 |
the same three lines hsql could have written once. |
| 1132 |
""" |
| 1133 |
res = hsql("--config", "show", "--json") |
| 1134 |
assert res.exit_code == ExitCode.OK |
| 1135 |
assert json.loads(res.stdout) == { |
| 1136 |
"default_profile": None, |
| 1137 |
"profiles": {}, |
| 1138 |
"keymaps": {}, |
| 1139 |
} |
| 1140 |
|
| 1141 |
|
| 1142 |
def test_config_show_says_so_when_there_is_nothing_to_show( |
| 1143 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1144 |
) -> None: |
| 1145 |
res = hsql("--config", "show") |
| 1146 |
assert res.exit_code == ExitCode.OK |
| 1147 |
assert res.stdout == "# No config file defines anything hsql reads.\n" |
| 1148 |
|
| 1149 |
|
| 1150 |
@pytest.mark.parametrize("argv", [["--csv"], ["--format", "markdown"]]) |
| 1151 |
def test_config_show_notes_a_format_it_cannot_reach( |
| 1152 |
hsql: Hsql, two_config_files: tuple[Path, Path], argv: list[str] |
| 1153 |
) -> None: |
| 1154 |
"""A document is not rows, and silence would read as a format that applied.""" |
| 1155 |
res = hsql("--config", "show", *argv) |
| 1156 |
assert res.exit_code == ExitCode.OK |
| 1157 |
assert res.stdout.startswith("default_profile") |
| 1158 |
assert "had no effect" in res.stderr |
| 1159 |
assert "--format json" in res.stderr |
| 1160 |
|
| 1161 |
|
| 1162 |
def test_config_show_writes_nothing_under_format_none( |
| 1163 |
hsql: Hsql, two_config_files: tuple[Path, Path] |
| 1164 |
) -> None: |
| 1165 |
res = hsql("--config", "show", "--format", "none") |
| 1166 |
assert res.exit_code == ExitCode.OK |
| 1167 |
assert res.stdout == "" |
| 1168 |
|
| 1169 |
|
| 1170 |
def test_config_show_goes_to_the_file_dash_o_names( |
| 1171 |
hsql: Hsql, two_config_files: tuple[Path, Path], tmp_path: Path |
| 1172 |
) -> None: |
| 1173 |
destination = tmp_path / "effective.toml" |
| 1174 |
res = hsql("--config", "show", "-o", str(destination)) |
| 1175 |
assert res.exit_code == ExitCode.OK |
| 1176 |
assert res.stdout == "" |
| 1177 |
assert destination.read_text(encoding="utf-8").startswith("default_profile") |
| 1178 |
|
| 1179 |
|
| 1180 |
def test_config_list_profiles_is_rows( |
| 1181 |
hsql: Hsql, two_config_files: tuple[Path, Path] |
| 1182 |
) -> None: |
| 1183 |
"""The question a human asks first: what can I pass to -P. |
| 1184 |
|
| 1185 |
Sorted by name, and the default is a column rather than a decoration on |
| 1186 |
one -- a marker inside the name is a name a shell loop would pass back |
| 1187 |
wrong. |
| 1188 |
""" |
| 1189 |
res = hsql("--config", "list-profiles") |
| 1190 |
assert res.exit_code == ExitCode.OK |
| 1191 |
assert res.stdout == ( |
| 1192 |
" profile | adapter | default\n" |
| 1193 |
"----------+---------+---------\n" |
| 1194 |
" personal | duckdb | true\n" |
| 1195 |
" project | sqlite | false\n" |
| 1196 |
" shared | duckdb | false\n" |
| 1197 |
"(3 rows)\n" |
| 1198 |
) |
| 1199 |
|
| 1200 |
|
| 1201 |
def test_config_list_profiles_under_the_psql_switches( |
| 1202 |
hsql: Hsql, two_config_files: tuple[Path, Path] |
| 1203 |
) -> None: |
| 1204 |
"""A listing is a result set, so every flag that shapes one reaches it.""" |
| 1205 |
res = hsql("--config", "list-profiles", "-tA") |
| 1206 |
assert res.exit_code == ExitCode.OK |
| 1207 |
assert res.stdout == ( |
| 1208 |
"personal|duckdb|true\nproject|sqlite|false\nshared|duckdb|false\n" |
| 1209 |
) |
| 1210 |
|
| 1211 |
|
| 1212 |
def test_config_list_profiles_as_csv( |
| 1213 |
hsql: Hsql, two_config_files: tuple[Path, Path] |
| 1214 |
) -> None: |
| 1215 |
res = hsql("--config", "list-profiles", "--csv", "-t") |
| 1216 |
assert res.exit_code == ExitCode.OK |
| 1217 |
assert res.stdout == ( |
| 1218 |
"personal,duckdb,true\nproject,sqlite,false\nshared,duckdb,false\n" |
| 1219 |
) |
| 1220 |
|
| 1221 |
|
| 1222 |
def test_config_list_profiles_leaves_an_unnamed_adapter_null( |
| 1223 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1224 |
) -> None: |
| 1225 |
"""It reports what the files say. A profile that names no adapter is one |
| 1226 |
`-a` still decides, and printing hsql's default here would claim the file |
| 1227 |
had made a choice it did not make.""" |
| 1228 |
cwd, _ = config_dirs |
| 1229 |
(cwd / ".harlequin.toml").write_text("[profiles.bare]\nlimit = 10\n") |
| 1230 |
res = hsql("--config", "list-profiles", "-tA") |
| 1231 |
assert res.stdout == "bare|NULL|false\n" |
| 1232 |
|
| 1233 |
|
| 1234 |
def test_config_list_profiles_marks_no_default_when_there_is_none( |
| 1235 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1236 |
) -> None: |
| 1237 |
cwd, _ = config_dirs |
| 1238 |
(cwd / ".harlequin.toml").write_text('[profiles.one]\nadapter = "sqlite"\n') |
| 1239 |
res = hsql("--config", "list-profiles", "-tA") |
| 1240 |
assert res.exit_code == ExitCode.OK |
| 1241 |
assert res.stdout == "one|sqlite|false\n" |
| 1242 |
|
| 1243 |
|
| 1244 |
def test_config_list_profiles_reports_a_default_that_names_nothing( |
| 1245 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1246 |
) -> None: |
| 1247 |
"""Not an error, and not silence. |
| 1248 |
|
| 1249 |
A `default_profile` naming nothing only stops an invocation that was going |
| 1250 |
to use it, and this one is not -- but a short list of names is exactly |
| 1251 |
where the mistake is visible, so it is said on stderr and the list still |
| 1252 |
prints. |
| 1253 |
""" |
| 1254 |
cwd, _ = config_dirs |
| 1255 |
(cwd / ".harlequin.toml").write_text( |
| 1256 |
'default_profile = "gone"\n[profiles.here]\nadapter = "sqlite"\n' |
| 1257 |
) |
| 1258 |
res = hsql("--config", "list-profiles", "-tA") |
| 1259 |
assert res.exit_code == ExitCode.OK |
| 1260 |
assert res.stdout == "here|sqlite|false\n" |
| 1261 |
assert "default_profile is 'gone'" in res.stderr |
| 1262 |
|
| 1263 |
|
| 1264 |
def test_config_list_profiles_finds_none( |
| 1265 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1266 |
) -> None: |
| 1267 |
res = hsql("--config", "list-profiles") |
| 1268 |
assert res.exit_code == ExitCode.OK |
| 1269 |
assert res.stdout == ( |
| 1270 |
" profile | adapter | default\n---------+---------+---------\n(0 rows)\n" |
| 1271 |
) |
| 1272 |
|
| 1273 |
|
| 1274 |
def test_config_show_reads_a_profile_it_was_not_asked_about( |
| 1275 |
hsql: Hsql, two_config_files: tuple[Path, Path] |
| 1276 |
) -> None: |
| 1277 |
"""`-P` names a profile to connect with, and this mode connects with none. |
| 1278 |
|
| 1279 |
A `-P` that resolves to nothing is a hard error for a run and irrelevant |
| 1280 |
here, which is the point: the mode that tells you what your profiles are |
| 1281 |
must not refuse to run because one of them is missing. |
| 1282 |
""" |
| 1283 |
res = hsql("--config", "list-profiles", "-P", "no-such-profile", "-tA") |
| 1284 |
assert res.exit_code == ExitCode.OK |
| 1285 |
assert res.stdout.startswith("personal|") |
| 1286 |
|
| 1287 |
|
| 1288 |
def test_config_reports_a_file_it_cannot_read( |
| 1289 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1290 |
) -> None: |
| 1291 |
"""`show` reads every file, so a broken one is fatal to it. |
| 1292 |
|
| 1293 |
`--config validate` is the mode that reports every problem at once; this |
| 1294 |
one stops at the first, and names the file either way. |
| 1295 |
""" |
| 1296 |
cwd, _ = config_dirs |
| 1297 |
(cwd / ".harlequin.toml").write_text("this is not toml\n") |
| 1298 |
res = hsql("--config", "show") |
| 1299 |
assert res.exit_code == ExitCode.USAGE |
| 1300 |
assert res.stdout == "" |
| 1301 |
assert str(cwd / ".harlequin.toml") in res.stderr |
| 1302 |
|
| 1303 |
|
| 1304 |
@pytest.mark.parametrize("sql", [["-c", "select 1"], ["-f", "-"]]) |
| 1305 |
def test_config_refuses_to_also_run_sql( |
| 1306 |
hsql: Hsql, two_config_files: tuple[Path, Path], sql: list[str] |
| 1307 |
) -> None: |
| 1308 |
"""Two questions spelled as one invocation, and neither is the answer. |
| 1309 |
|
| 1310 |
Showing the config and ignoring the SQL would be the worse outcome of the |
| 1311 |
two: a script that thought it ran a query would carry on believing it. |
| 1312 |
""" |
| 1313 |
res = hsql("--config", "show", *sql) |
| 1314 |
assert res.exit_code == ExitCode.USAGE |
| 1315 |
assert res.stdout == "" |
| 1316 |
assert "does not run SQL" in res.stderr |
| 1317 |
|
| 1318 |
|
| 1319 |
def test_an_unknown_config_mode_lists_the_ones_that_work(hsql: Hsql) -> None: |
| 1320 |
res = hsql("--config", "profiles") |
| 1321 |
assert res.exit_code == ExitCode.USAGE |
| 1322 |
for mode in CONFIG_MODES: |
| 1323 |
assert mode in res.stderr |
| 1324 |
|
| 1325 |
|
| 1326 |
def test_config_modes_are_what_the_help_offers(hsql: Hsql) -> None: |
| 1327 |
res = hsql("--help") |
| 1328 |
assert res.exit_code == ExitCode.OK |
| 1329 |
for mode in CONFIG_MODES: |
| 1330 |
assert mode in res.output.replace("\n", "").replace(" ", "") |
| 1331 |
|
| 1332 |
|
| 1333 |
def test_config_show_writes_a_keymap_as_the_array_it_is( |
| 1334 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1335 |
) -> None: |
| 1336 |
"""A keymap is an array of tables, and its provenance is written once. |
| 1337 |
|
| 1338 |
The array comes from one file whole, like a profile, so repeating the |
| 1339 |
comment over every binding in it would say the same thing as many times as |
| 1340 |
the user has key bindings. |
| 1341 |
""" |
| 1342 |
cwd, home = config_dirs |
| 1343 |
(home / ".harlequin.toml").write_text( |
| 1344 |
"[[keymaps.arrows]]\n" |
| 1345 |
'keys = "ctrl+j"\n' |
| 1346 |
'action = "cursor_down"\n' |
| 1347 |
"[[keymaps.arrows]]\n" |
| 1348 |
'keys = "ctrl+k"\n' |
| 1349 |
'action = "cursor_up"\n' |
| 1350 |
) |
| 1351 |
res = hsql("--config", "show") |
| 1352 |
assert res.exit_code == ExitCode.OK |
| 1353 |
assert res.stdout == ( |
| 1354 |
f"[[keymaps.arrows]] # from {home / '.harlequin.toml'}\n" |
| 1355 |
'keys = "ctrl+j"\n' |
| 1356 |
'action = "cursor_down"\n' |
| 1357 |
"\n" |
| 1358 |
"[[keymaps.arrows]]\n" |
| 1359 |
'keys = "ctrl+k"\n' |
| 1360 |
'action = "cursor_up"\n' |
| 1361 |
) |
| 1362 |
|
| 1363 |
|
| 1364 |
# --- `--config validate`, the mode that reports every problem ---------------- |
| 1365 |
|
| 1366 |
|
| 1367 |
def test_config_validate_finds_nothing_wrong_with_a_good_config( |
| 1368 |
hsql: Hsql, two_config_files: tuple[Path, Path] |
| 1369 |
) -> None: |
| 1370 |
"""Zero problems is zero rows, and the code a script actually reads.""" |
| 1371 |
res = hsql("--config", "validate") |
| 1372 |
assert res.exit_code == ExitCode.OK |
| 1373 |
assert res.stdout == ( |
| 1374 |
" file | key | problem | line\n------+-----+---------+------\n(0 rows)\n" |
| 1375 |
) |
| 1376 |
|
| 1377 |
|
| 1378 |
def test_config_validate_exits_two_for_a_config_it_found_a_problem_in( |
| 1379 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1380 |
) -> None: |
| 1381 |
"""The whole mode, for a caller that never reads the rows. |
| 1382 |
|
| 1383 |
`--format none` is the spelling that says so out loud: no stdout at all, |
| 1384 |
and the answer in the exit code. |
| 1385 |
""" |
| 1386 |
cwd, _ = config_dirs |
| 1387 |
(cwd / ".harlequin.toml").write_text( |
| 1388 |
'[profiles.prod]\nadapter = "duckdb"\nreed_only = true\n' |
| 1389 |
) |
| 1390 |
res = hsql("--config", "validate", "--format", "none") |
| 1391 |
assert res.exit_code == ExitCode.USAGE |
| 1392 |
assert res.stdout == "" |
| 1393 |
|
| 1394 |
|
| 1395 |
def test_config_validate_names_the_file_the_key_and_the_option( |
| 1396 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1397 |
) -> None: |
| 1398 |
"""Pass 2, which is the surface nothing else in the stack validates. |
| 1399 |
|
| 1400 |
`reed_only = true` reaches the adapter's constructor and is dropped there |
| 1401 |
in silence, leaving a caller who believes they are connected read-only. |
| 1402 |
""" |
| 1403 |
cwd, _ = config_dirs |
| 1404 |
(cwd / ".harlequin.toml").write_text( |
| 1405 |
'[profiles.prod]\nadapter = "duckdb"\nreed_only = true\n' |
| 1406 |
) |
| 1407 |
res = hsql("--config", "validate", "-tA") |
| 1408 |
assert res.exit_code == ExitCode.USAGE |
| 1409 |
file, key, problem, line = res.stdout.strip().split("|") |
| 1410 |
assert file == str(cwd / ".harlequin.toml") |
| 1411 |
assert key == "profiles.prod.reed_only" |
| 1412 |
assert "duckdb" in problem |
| 1413 |
assert "read_only" in problem # the spelling it was probably meant to be |
| 1414 |
assert line == "NULL" |
| 1415 |
|
| 1416 |
|
| 1417 |
def test_config_validate_reports_every_file_and_keeps_reading( |
| 1418 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1419 |
) -> None: |
| 1420 |
"""The mode's whole reason to exist, in the shape it is worst at. |
| 1421 |
|
| 1422 |
A file it cannot parse stops `show` dead. Here it is one row, and the file |
| 1423 |
behind it is read, validated and reported on anyway -- which is what the |
| 1424 |
per-file validation in front of the merge buys. |
| 1425 |
""" |
| 1426 |
cwd, home = config_dirs |
| 1427 |
(cwd / ".harlequin.toml").write_text("this is not toml\n") |
| 1428 |
(home / ".harlequin.toml").write_text( |
| 1429 |
'[profiles.prod]\nadapter = "sqlite"\nreed_only = true\n' |
| 1430 |
) |
| 1431 |
res = hsql("--config", "validate", "-tA") |
| 1432 |
assert res.exit_code == ExitCode.USAGE |
| 1433 |
first, second = res.stdout.splitlines() |
| 1434 |
assert first.startswith(str(cwd / ".harlequin.toml")) |
| 1435 |
assert second.startswith(str(home / ".harlequin.toml")) |
| 1436 |
|
| 1437 |
|
| 1438 |
def test_config_validate_names_the_line_when_the_parser_named_one( |
| 1439 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1440 |
) -> None: |
| 1441 |
"""Where the parser gives a position, and nowhere else. |
| 1442 |
|
| 1443 |
A key we merely dislike has no position anywhere, and a number that was not |
| 1444 |
read out of a parser would send a reader to a line with nothing on it. |
| 1445 |
""" |
| 1446 |
cwd, _ = config_dirs |
| 1447 |
(cwd / ".harlequin.toml").write_text('[profiles.prod]\nadapter = "duckdb"\noops\n') |
| 1448 |
res = hsql("--config", "validate", "-tA") |
| 1449 |
assert res.exit_code == ExitCode.USAGE |
| 1450 |
file, key, _, line = res.stdout.strip().split("|") |
| 1451 |
assert file == str(cwd / ".harlequin.toml") |
| 1452 |
assert key == "NULL" # the problem is the file, not something in it |
| 1453 |
assert line == "3" |
| 1454 |
|
| 1455 |
|
| 1456 |
def test_config_validate_reports_a_profile_the_merge_hides( |
| 1457 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1458 |
) -> None: |
| 1459 |
"""One entry per file per problem, which is what validating first buys. |
| 1460 |
|
| 1461 |
The nearer file supplies `shared` whole, so no invocation runs the home |
| 1462 |
file's copy of it -- and its author will still open that file to fix it. |
| 1463 |
""" |
| 1464 |
cwd, home = config_dirs |
| 1465 |
(home / ".harlequin.toml").write_text("[profiles.shared]\nreed_only = true\n") |
| 1466 |
(cwd / ".harlequin.toml").write_text("[profiles.shared]\nread_only = true\n") |
| 1467 |
res = hsql("--config", "validate", "-tA") |
| 1468 |
assert res.exit_code == ExitCode.USAGE |
| 1469 |
assert res.stdout.startswith( |
| 1470 |
f"{home / '.harlequin.toml'}|profiles.shared.reed_only" |
| 1471 |
) |
| 1472 |
|
| 1473 |
|
| 1474 |
def test_config_validate_reports_a_default_that_names_nothing( |
| 1475 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1476 |
) -> None: |
| 1477 |
"""Where `list-profiles` notes it, this one fails on it. |
| 1478 |
|
| 1479 |
Nothing about the key is more wrong here -- it is the same broken default. |
| 1480 |
The difference is what each mode was asked: one for a list of names, and |
| 1481 |
this one for whether the config is any good. |
| 1482 |
""" |
| 1483 |
cwd, _ = config_dirs |
| 1484 |
(cwd / ".harlequin.toml").write_text( |
| 1485 |
'default_profile = "gone"\n[profiles.here]\nadapter = "sqlite"\n' |
| 1486 |
) |
| 1487 |
res = hsql("--config", "validate", "-tA") |
| 1488 |
assert res.exit_code == ExitCode.USAGE |
| 1489 |
file, key, problem, _ = res.stdout.strip().split("|") |
| 1490 |
assert file == str(cwd / ".harlequin.toml") |
| 1491 |
assert key == "default_profile" |
| 1492 |
assert "gone" in problem |
| 1493 |
|
| 1494 |
|
| 1495 |
def test_config_validate_accepts_a_profile_written_for_the_ide( |
| 1496 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1497 |
) -> None: |
| 1498 |
"""Valid is a union of three sets, and getting it wrong breaks working configs. |
| 1499 |
|
| 1500 |
One profile serves both commands, so the IDE's keys are as legal here as |
| 1501 |
hsql's own and the adapter's -- and a value may arrive uncast, because the |
| 1502 |
adapter contract says it may: `port = 5432` and `port = "5432"` are the |
| 1503 |
same option written two ways a TOML file invites. |
| 1504 |
""" |
| 1505 |
cwd, _ = config_dirs |
| 1506 |
(cwd / ".harlequin.toml").write_text( |
| 1507 |
"[profiles.ide]\n" |
| 1508 |
'adapter = "sqlite"\n' # the adapter's own |
| 1509 |
"read_only = true\n" |
| 1510 |
"limit = 100\n" # a key both commands read |
| 1511 |
'theme = "nord"\n' # a key only the IDE reads |
| 1512 |
'keymap_name = ["vscode"]\n' |
| 1513 |
"[profiles.uncast]\n" |
| 1514 |
'adapter = "postgres"\n' |
| 1515 |
"port = 5432\n" |
| 1516 |
) |
| 1517 |
res = hsql("--config", "validate", "-tA") |
| 1518 |
assert res.exit_code == ExitCode.OK |
| 1519 |
assert res.stdout == "" |
| 1520 |
|
| 1521 |
|
| 1522 |
def test_config_validate_reports_an_adapter_nothing_installs( |
| 1523 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1524 |
) -> None: |
| 1525 |
"""A profile whose adapter cannot be loaded is one profile's problem. |
| 1526 |
|
| 1527 |
It cannot be checked any further -- there are no declared options to check |
| 1528 |
it against -- and the file's other profiles still can be. |
| 1529 |
""" |
| 1530 |
cwd, _ = config_dirs |
| 1531 |
(cwd / ".harlequin.toml").write_text( |
| 1532 |
'[profiles.gone]\nadapter = "no-such-adapter"\n' |
| 1533 |
'[profiles.fine]\nadapter = "sqlite"\nread_only = true\n' |
| 1534 |
) |
| 1535 |
res = hsql("--config", "validate", "-tA") |
| 1536 |
assert res.exit_code == ExitCode.USAGE |
| 1537 |
(row,) = res.stdout.splitlines() |
| 1538 |
assert row.split("|")[1] == "profiles.gone.adapter" |
| 1539 |
assert "no-such-adapter" in row |
| 1540 |
|
| 1541 |
|
| 1542 |
def test_config_validate_reports_a_keymap_the_ide_would_refuse( |
| 1543 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1544 |
) -> None: |
| 1545 |
"""A keymap is checked here rather than when the IDE next starts.""" |
| 1546 |
cwd, _ = config_dirs |
| 1547 |
(cwd / ".harlequin.toml").write_text( |
| 1548 |
'[[keymaps.mine]]\nkeys = "ctrl+j"\naction = "cursor_down"\noops = 1\n' |
| 1549 |
) |
| 1550 |
res = hsql("--config", "validate", "-tA") |
| 1551 |
assert res.exit_code == ExitCode.USAGE |
| 1552 |
assert res.stdout.split("|")[1] == "keymaps.mine" |
| 1553 |
|
| 1554 |
|
| 1555 |
def test_config_validate_writes_one_line_per_problem( |
| 1556 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1557 |
) -> None: |
| 1558 |
"""A problem is a row, and a row is a line. |
| 1559 |
|
| 1560 |
Some of these messages are written over two lines when they are raised at a |
| 1561 |
caller; folded into a cell they would arrive as two rows in every format |
| 1562 |
that does not quote its cells. |
| 1563 |
""" |
| 1564 |
cwd, _ = config_dirs |
| 1565 |
(cwd / ".harlequin.toml").write_text( |
| 1566 |
'[profiles.prod]\nadapter = "sqlite"\nmode = "reed-only"\n' |
| 1567 |
) |
| 1568 |
res = hsql("--config", "validate", "-tA") |
| 1569 |
assert res.exit_code == ExitCode.USAGE |
| 1570 |
(row,) = res.stdout.splitlines() |
| 1571 |
assert "Allowed values" in row |
| 1572 |
|
| 1573 |
|
| 1574 |
def test_config_validate_is_json_for_a_caller( |
| 1575 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1576 |
) -> None: |
| 1577 |
"""Four facts per problem, under the same --json as everywhere else.""" |
| 1578 |
cwd, _ = config_dirs |
| 1579 |
(cwd / ".harlequin.toml").write_text( |
| 1580 |
'[profiles.prod]\nadapter = "duckdb"\nreed_only = true\n' |
| 1581 |
) |
| 1582 |
res = hsql("--config", "validate", "--json") |
| 1583 |
assert res.exit_code == ExitCode.USAGE |
| 1584 |
(problem,) = json.loads(res.stdout) |
| 1585 |
assert problem["file"] == str(cwd / ".harlequin.toml") |
| 1586 |
assert problem["key"] == "profiles.prod.reed_only" |
| 1587 |
assert problem["line"] is None |
| 1588 |
assert "duckdb" in problem["problem"] |
| 1589 |
|
| 1590 |
|
| 1591 |
def test_config_validate_says_when_there_was_nothing_to_check( |
| 1592 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1593 |
) -> None: |
| 1594 |
"""A clean config and no config at all read the same on stdout. |
| 1595 |
|
| 1596 |
They are not the same answer, and the one that found nothing to check is |
| 1597 |
the one a caller would otherwise mistake for a passing check. |
| 1598 |
""" |
| 1599 |
res = hsql("--config", "validate") |
| 1600 |
assert res.exit_code == ExitCode.OK |
| 1601 |
assert "No config file defines anything" in res.stderr |
| 1602 |
|
| 1603 |
|
| 1604 |
def test_config_validate_does_not_connect( |
| 1605 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1606 |
) -> None: |
| 1607 |
"""It reads a declaration, not a database. |
| 1608 |
|
| 1609 |
A profile pointing at a file that is not there is exactly the config a |
| 1610 |
caller runs this mode on, and needing the database to check the config |
| 1611 |
would make the mode useless where it is most wanted. |
| 1612 |
""" |
| 1613 |
cwd, _ = config_dirs |
| 1614 |
(cwd / ".harlequin.toml").write_text( |
| 1615 |
'[profiles.prod]\nadapter = "sqlite"\nconn_str = ["/no/such/dir/db.sqlite"]\n' |
| 1616 |
) |
| 1617 |
res = hsql("--config", "validate", "-tA") |
| 1618 |
assert res.exit_code == ExitCode.OK |
| 1619 |
assert res.stdout == "" |
| 1620 |
|
| 1621 |
|
| 1622 |
# --- `--config schema`, the mode that reports what may be in a config file --- |
| 1623 |
|
| 1624 |
|
| 1625 |
def schema_of(res: Result) -> dict[str, Any]: |
| 1626 |
assert res.exit_code == ExitCode.OK |
| 1627 |
return cast("dict[str, Any]", json.loads(res.stdout)) |
| 1628 |
|
| 1629 |
|
| 1630 |
def test_config_schema_is_a_json_schema(hsql: Hsql) -> None: |
| 1631 |
schema = schema_of(hsql("--config", "schema")) |
| 1632 |
assert schema["$schema"] == "https://json-schema.org/draft/2020-12/schema" |
| 1633 |
assert set(schema["properties"]) == {"default_profile", "profiles", "keymaps"} |
| 1634 |
assert schema["$defs"]["profile"]["properties"]["limit"]["type"] == "integer" |
| 1635 |
|
| 1636 |
|
| 1637 |
def test_config_schema_describes_the_adapters_installed_here(hsql: Hsql) -> None: |
| 1638 |
"""The reason to generate it rather than ship one: it knows what is here.""" |
| 1639 |
schema = schema_of(hsql("--config", "schema")) |
| 1640 |
installed = schema["$defs"]["profile"]["properties"]["adapter"]["enum"] |
| 1641 |
assert {"duckdb", "sqlite"} <= set(installed) |
| 1642 |
for name in installed: |
| 1643 |
assert f"{name}_options" in schema["$defs"] |
| 1644 |
|
| 1645 |
|
| 1646 |
def test_config_schema_describes_an_adapters_own_options(hsql: Hsql) -> None: |
| 1647 |
options = schema_of(hsql("--config", "schema"))["$defs"]["duckdb_options"] |
| 1648 |
assert options["properties"]["no_init"]["type"] == "boolean" |
| 1649 |
assert options["properties"]["extension"]["type"] == "array" |
| 1650 |
|
| 1651 |
|
| 1652 |
def test_config_schema_does_not_claim_the_published_id(hsql: Hsql) -> None: |
| 1653 |
"""The document published at that URL is the one that names no adapter.""" |
| 1654 |
assert "$id" not in schema_of(hsql("--config", "schema")) |
| 1655 |
|
| 1656 |
|
| 1657 |
def test_config_schema_reads_no_config_file( |
| 1658 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 1659 |
) -> None: |
| 1660 |
"""It describes what a config file may say, not what one says. |
| 1661 |
|
| 1662 |
So it answers over a file that cannot be parsed -- which is a config a |
| 1663 |
caller might well be reaching for a schema to fix. |
| 1664 |
""" |
| 1665 |
cwd, _ = config_dirs |
| 1666 |
(cwd / ".harlequin.toml").write_text("[profiles.prod\nadapter = 'duckdb'\n") |
| 1667 |
assert schema_of(hsql("--config", "schema"))["title"] == "Harlequin config" |
| 1668 |
|
| 1669 |
|
| 1670 |
def test_config_schema_does_not_connect(hsql: Hsql) -> None: |
| 1671 |
res = hsql("--config", "schema", ":memory:") |
| 1672 |
assert res.exit_code == ExitCode.OK |
| 1673 |
assert json.loads(res.stdout) |
| 1674 |
|
| 1675 |
|
| 1676 |
def test_config_schema_does_not_run_sql(hsql: Hsql) -> None: |
| 1677 |
res = hsql("--config", "schema", ":memory:", "-c", "select 1") |
| 1678 |
assert res.exit_code == ExitCode.USAGE |
| 1679 |
assert "does not run SQL" in res.stderr |
| 1680 |
|
| 1681 |
|
| 1682 |
def test_config_schema_writes_nothing_under_format_none(hsql: Hsql) -> None: |
| 1683 |
res = hsql("--config", "schema", "--format", "none") |
| 1684 |
assert res.exit_code == ExitCode.OK |
| 1685 |
assert res.stdout == "" |
| 1686 |
|
| 1687 |
|
| 1688 |
@pytest.mark.parametrize("argv", [["--csv"], ["--format", "markdown"]]) |
| 1689 |
def test_config_schema_notes_a_format_it_cannot_reach( |
| 1690 |
hsql: Hsql, argv: list[str] |
| 1691 |
) -> None: |
| 1692 |
res = hsql("--config", "schema", *argv) |
| 1693 |
assert res.exit_code == ExitCode.OK |
| 1694 |
assert json.loads(res.stdout) |
| 1695 |
assert "--config schema" in res.stderr |
| 1696 |
|
| 1697 |
|
| 1698 |
def test_config_schema_json_is_not_a_format_it_declines(hsql: Hsql) -> None: |
| 1699 |
res = hsql("--config", "schema", "--json") |
| 1700 |
assert res.exit_code == ExitCode.OK |
| 1701 |
assert res.stderr == "" |
| 1702 |
|
| 1703 |
|
| 1704 |
def test_config_schema_goes_to_the_file_dash_o_names( |
| 1705 |
hsql: Hsql, tmp_path: Path |
| 1706 |
) -> None: |
| 1707 |
destination = tmp_path / "config-schema.json" |
| 1708 |
res = hsql("--config", "schema", "-o", str(destination)) |
| 1709 |
assert res.exit_code == ExitCode.OK |
| 1710 |
assert res.stdout == "" |
| 1711 |
assert json.loads(destination.read_text())["title"] == "Harlequin config" |
| 1712 |
|
| 1713 |
|
| 1714 |
# --- `--config init`, the mode that writes one ------------------------------- |
| 1715 |
|
| 1716 |
|
| 1717 |
@pytest.fixture |
| 1718 |
def init_dirs( |
| 1719 |
config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch |
| 1720 |
) -> tuple[Path, Path]: |
| 1721 |
"""`config_dirs`, with the mock cwd as the process's working directory too. |
| 1722 |
|
| 1723 |
With no config file anywhere, `--config init` writes one beside the project |
| 1724 |
it is configuring, and that fallback is `Path.cwd()` -- which patching the |
| 1725 |
search path does not reach. |
| 1726 |
""" |
| 1727 |
monkeypatch.chdir(config_dirs[0]) |
| 1728 |
return config_dirs |
| 1729 |
|
| 1730 |
|
| 1731 |
def written(path: Path) -> dict[str, Any]: |
| 1732 |
"""A config file as the loader reads it, to assert on what init wrote.""" |
| 1733 |
from harlequin.config import ConfigFile |
| 1734 |
|
| 1735 |
return ConfigFile(path).relevant_config |
| 1736 |
|
| 1737 |
|
| 1738 |
def test_config_init_writes_a_profile_where_there_was_no_config_file( |
| 1739 |
hsql: Hsql, init_dirs: tuple[Path, Path] |
| 1740 |
) -> None: |
| 1741 |
"""The first config file a caller has, in the directory they are in. |
| 1742 |
|
| 1743 |
Not the home directory: a caller who has said nothing about where their |
| 1744 |
config lives gets it beside the project they were configuring, which is |
| 1745 |
also the file the next command discovers first. |
| 1746 |
""" |
| 1747 |
cwd, home = init_dirs |
| 1748 |
res = hsql("--config", "init", "-P", "prod", "-a", "sqlite", "./my.db") |
| 1749 |
assert res.exit_code == ExitCode.OK |
| 1750 |
assert res.stdout == "" |
| 1751 |
assert not (home / ".harlequin.toml").exists() |
| 1752 |
assert written(cwd / ".harlequin.toml") == { |
| 1753 |
"profiles": {"prod": {"adapter": "sqlite", "conn_str": ["./my.db"]}} |
| 1754 |
} |
| 1755 |
|
| 1756 |
|
| 1757 |
def test_config_init_says_what_it_wrote_and_where( |
| 1758 |
hsql: Hsql, init_dirs: tuple[Path, Path] |
| 1759 |
) -> None: |
| 1760 |
"""A mode that writes a file produces no data, so this is the whole answer.""" |
| 1761 |
cwd, _ = init_dirs |
| 1762 |
res = hsql("--config", "init", "-P", "prod") |
| 1763 |
assert res.exit_code == ExitCode.OK |
| 1764 |
assert "prod" in res.stderr |
| 1765 |
assert str(cwd / ".harlequin.toml") in res.stderr |
| 1766 |
|
| 1767 |
|
| 1768 |
def test_config_init_writes_what_was_typed_and_nothing_else( |
| 1769 |
hsql: Hsql, init_dirs: tuple[Path, Path] |
| 1770 |
) -> None: |
| 1771 |
"""An option left at its default carries no intent, so it is not a key. |
| 1772 |
|
| 1773 |
The same rule `merge_profile_with_cli()` reads the other way round: a |
| 1774 |
profile full of the command's own defaults would pin every one of them |
| 1775 |
against the day one changes. |
| 1776 |
""" |
| 1777 |
cwd, _ = init_dirs |
| 1778 |
res = hsql("--config", "init", "-P", "prod", "--limit", "10") |
| 1779 |
assert res.exit_code == ExitCode.OK |
| 1780 |
profile = written(cwd / ".harlequin.toml")["profiles"]["prod"] |
| 1781 |
assert profile == {"adapter": "duckdb", "limit": 10} |
| 1782 |
|
| 1783 |
|
| 1784 |
def test_config_init_writes_an_adapters_own_options( |
| 1785 |
hsql: Hsql, init_dirs: tuple[Path, Path] |
| 1786 |
) -> None: |
| 1787 |
"""The half of a profile only the adapter declares. |
| 1788 |
|
| 1789 |
Which is why this is the one mode that imports an adapter to write a file: |
| 1790 |
`--no-init` is not a flag hsql has until sqlite's options are on it. |
| 1791 |
""" |
| 1792 |
cwd, _ = init_dirs |
| 1793 |
res = hsql("--config", "init", "-P", "prod", "-a", "sqlite", "--no-init") |
| 1794 |
assert res.exit_code == ExitCode.OK |
| 1795 |
profile = written(cwd / ".harlequin.toml")["profiles"]["prod"] |
| 1796 |
assert profile == {"adapter": "sqlite", "no_init": True} |
| 1797 |
|
| 1798 |
|
| 1799 |
def test_config_init_writes_a_shorthand_as_the_format_it_stands_for( |
| 1800 |
hsql: Hsql, init_dirs: tuple[Path, Path] |
| 1801 |
) -> None: |
| 1802 |
"""`--csv` is a way of spelling `--format csv`, and a profile has the key.""" |
| 1803 |
cwd, _ = init_dirs |
| 1804 |
res = hsql("--config", "init", "-P", "prod", "--csv") |
| 1805 |
assert res.exit_code == ExitCode.OK |
| 1806 |
profile = written(cwd / ".harlequin.toml")["profiles"]["prod"] |
| 1807 |
assert profile == {"adapter": "duckdb", "format": "csv"} |
| 1808 |
|
| 1809 |
|
| 1810 |
def test_config_init_names_the_adapter_even_when_nothing_did( |
| 1811 |
hsql: Hsql, init_dirs: tuple[Path, Path] |
| 1812 |
) -> None: |
| 1813 |
"""A profile that names no adapter is one the default could move under.""" |
| 1814 |
cwd, _ = init_dirs |
| 1815 |
res = hsql("--config", "init", "-P", "prod") |
| 1816 |
assert res.exit_code == ExitCode.OK |
| 1817 |
assert written(cwd / ".harlequin.toml")["profiles"]["prod"]["adapter"] == "duckdb" |
| 1818 |
|
| 1819 |
|
| 1820 |
def test_config_init_keeps_everything_it_was_not_asked_to_write( |
| 1821 |
hsql: Hsql, init_dirs: tuple[Path, Path] |
| 1822 |
) -> None: |
| 1823 |
"""The reason it writes through tomlkit rather than dumping a document. |
| 1824 |
|
| 1825 |
A caller's comments, key order and the profiles beside the one being |
| 1826 |
written all survive, because a config file is a file a person wrote. |
| 1827 |
""" |
| 1828 |
cwd, _ = init_dirs |
| 1829 |
path = cwd / ".harlequin.toml" |
| 1830 |
path.write_text( |
| 1831 |
'default_profile = "dev"\n' |
| 1832 |
"\n" |
| 1833 |
"# the one I use every day\n" |
| 1834 |
"[profiles.dev]\n" |
| 1835 |
'adapter = "duckdb"\n' |
| 1836 |
"# a big limit, because the laptop can take it\n" |
| 1837 |
"limit = 500000\n" |
| 1838 |
) |
| 1839 |
res = hsql("--config", "init", "-P", "prod", "-a", "sqlite") |
| 1840 |
assert res.exit_code == ExitCode.OK |
| 1841 |
|
| 1842 |
after = path.read_text() |
| 1843 |
assert "# the one I use every day" in after |
| 1844 |
assert "# a big limit, because the laptop can take it" in after |
| 1845 |
assert written(path) == { |
| 1846 |
"default_profile": "dev", |
| 1847 |
"profiles": { |
| 1848 |
"dev": {"adapter": "duckdb", "limit": 500000}, |
| 1849 |
"prod": {"adapter": "sqlite"}, |
| 1850 |
}, |
| 1851 |
} |
| 1852 |
|
| 1853 |
|
| 1854 |
def test_config_init_replaces_the_profile_it_names( |
| 1855 |
hsql: Hsql, init_dirs: tuple[Path, Path] |
| 1856 |
) -> None: |
| 1857 |
"""A profile is written whole, and says so. |
| 1858 |
|
| 1859 |
The alternative -- merging into what is there -- leaves a caller unable to |
| 1860 |
remove a key without editing the file by hand, and unable to tell from the |
| 1861 |
command what the profile now says. |
| 1862 |
""" |
| 1863 |
cwd, _ = init_dirs |
| 1864 |
path = cwd / ".harlequin.toml" |
| 1865 |
path.write_text('[profiles.prod]\nadapter = "sqlite"\nread_only = true\n') |
| 1866 |
res = hsql("--config", "init", "-P", "prod", "-a", "sqlite") |
| 1867 |
assert res.exit_code == ExitCode.OK |
| 1868 |
assert "replaced" in res.stderr |
| 1869 |
assert written(path)["profiles"]["prod"] == {"adapter": "sqlite"} |
| 1870 |
|
| 1871 |
|
| 1872 |
def test_config_init_writes_the_file_config_path_names( |
| 1873 |
hsql: Hsql, init_dirs: tuple[Path, Path], tmp_path: Path |
| 1874 |
) -> None: |
| 1875 |
"""A path that is not there yet, which is the file this mode exists to make.""" |
| 1876 |
cwd, _ = init_dirs |
| 1877 |
destination = tmp_path / "nested" / "harlequin.toml" |
| 1878 |
res = hsql("--config", "init", "-P", "prod", "--config-path", str(destination)) |
| 1879 |
assert res.exit_code == ExitCode.OK |
| 1880 |
assert written(destination)["profiles"]["prod"] == {"adapter": "duckdb"} |
| 1881 |
assert not (cwd / ".harlequin.toml").exists() |
| 1882 |
|
| 1883 |
|
| 1884 |
def test_config_init_writes_the_nearest_config_file_that_exists( |
| 1885 |
hsql: Hsql, two_config_files: tuple[Path, Path] |
| 1886 |
) -> None: |
| 1887 |
"""Where the wizard starts, for the same reason: it is the file that wins.""" |
| 1888 |
project, home = two_config_files |
| 1889 |
before = home.read_text() |
| 1890 |
res = hsql("--config", "init", "-P", "new", "-a", "sqlite") |
| 1891 |
assert res.exit_code == ExitCode.OK |
| 1892 |
assert "new" in written(project)["profiles"] |
| 1893 |
assert home.read_text() == before |
| 1894 |
|
| 1895 |
|
| 1896 |
def test_config_init_reads_no_profile_at_all( |
| 1897 |
hsql: Hsql, init_dirs: tuple[Path, Path] |
| 1898 |
) -> None: |
| 1899 |
"""The profile `-P` names is the one being written, not one to run under. |
| 1900 |
|
| 1901 |
So a name no file defines is the point rather than an error -- and a config |
| 1902 |
that would refuse a run for a `default_profile` naming nothing still gets |
| 1903 |
written to. |
| 1904 |
""" |
| 1905 |
cwd, _ = init_dirs |
| 1906 |
path = cwd / ".harlequin.toml" |
| 1907 |
path.write_text('default_profile = "gone"\n') |
| 1908 |
res = hsql("--config", "init", "-P", "prod", "-a", "sqlite") |
| 1909 |
assert res.exit_code == ExitCode.OK |
| 1910 |
assert written(path)["profiles"]["prod"] == {"adapter": "sqlite"} |
| 1911 |
|
| 1912 |
|
| 1913 |
def test_config_init_writes_a_profile_the_next_invocation_runs_under( |
| 1914 |
hsql: Hsql, init_dirs: tuple[Path, Path] |
| 1915 |
) -> None: |
| 1916 |
"""The whole of what this mode is for, in two invocations. |
| 1917 |
|
| 1918 |
Nothing else asserts that what init writes is what the run path reads: the |
| 1919 |
keys are hsql's own spellings on the way in and a profile's on the way out, |
| 1920 |
and this is where those two agree. |
| 1921 |
""" |
| 1922 |
res = hsql("--config", "init", "-P", "lite", "-a", "sqlite", ":memory:", "-tA") |
| 1923 |
assert res.exit_code == ExitCode.OK |
| 1924 |
|
| 1925 |
res = hsql("-P", "lite", "-c", "select 42") |
| 1926 |
assert res.exit_code == ExitCode.OK |
| 1927 |
assert res.stdout == "42\n" |
| 1928 |
|
| 1929 |
|
| 1930 |
def test_config_init_needs_a_name_for_the_profile_it_writes(hsql: Hsql) -> None: |
| 1931 |
res = hsql("--config", "init") |
| 1932 |
assert res.exit_code == ExitCode.USAGE |
| 1933 |
assert "-P" in res.stderr |
| 1934 |
|
| 1935 |
|
| 1936 |
def test_config_init_refuses_the_name_that_means_no_profile(hsql: Hsql) -> None: |
| 1937 |
"""`-P None` asks for Harlequin's defaults, so it names nothing to write.""" |
| 1938 |
res = hsql("--config", "init", "-P", "None") |
| 1939 |
assert res.exit_code == ExitCode.USAGE |
| 1940 |
assert "None" in res.stderr |
| 1941 |
|
| 1942 |
|
| 1943 |
def test_config_init_refuses_a_destination_that_is_not_toml( |
| 1944 |
hsql: Hsql, tmp_path: Path |
| 1945 |
) -> None: |
| 1946 |
destination = tmp_path / "harlequin.ini" |
| 1947 |
res = hsql("--config", "init", "-P", "prod", "--config-path", str(destination)) |
| 1948 |
assert res.exit_code == ExitCode.USAGE |
| 1949 |
assert not destination.exists() |
| 1950 |
|
| 1951 |
|
| 1952 |
def test_config_init_refuses_a_file_it_cannot_parse( |
| 1953 |
hsql: Hsql, init_dirs: tuple[Path, Path] |
| 1954 |
) -> None: |
| 1955 |
"""Half-understanding a file is the one way this could destroy one.""" |
| 1956 |
cwd, _ = init_dirs |
| 1957 |
path = cwd / ".harlequin.toml" |
| 1958 |
path.write_text("[profiles.prod\nadapter = 'duckdb'\n") |
| 1959 |
res = hsql("--config", "init", "-P", "other") |
| 1960 |
assert res.exit_code == ExitCode.USAGE |
| 1961 |
assert path.read_text() == "[profiles.prod\nadapter = 'duckdb'\n" |
| 1962 |
|
| 1963 |
|
| 1964 |
def test_config_init_refuses_a_file_whose_profiles_are_not_profiles( |
| 1965 |
hsql: Hsql, init_dirs: tuple[Path, Path] |
| 1966 |
) -> None: |
| 1967 |
"""The write path reads a file raw, so this is the shape it cannot assume.""" |
| 1968 |
cwd, _ = init_dirs |
| 1969 |
path = cwd / ".harlequin.toml" |
| 1970 |
path.write_text("profiles = 3\n") |
| 1971 |
res = hsql("--config", "init", "-P", "prod") |
| 1972 |
assert res.exit_code == ExitCode.USAGE |
| 1973 |
assert path.read_text() == "profiles = 3\n" |
| 1974 |
|
| 1975 |
|
| 1976 |
def test_config_init_does_not_run_sql(hsql: Hsql, init_dirs: tuple[Path, Path]) -> None: |
| 1977 |
cwd, _ = init_dirs |
| 1978 |
res = hsql("--config", "init", "-P", "prod", "-c", "select 1") |
| 1979 |
assert res.exit_code == ExitCode.USAGE |
| 1980 |
assert "does not run SQL" in res.stderr |
| 1981 |
assert not (cwd / ".harlequin.toml").exists() |
| 1982 |
|
| 1983 |
|
| 1984 |
# --- `--spec`, the mode that reports on the command itself ------------------- |
| 1985 |
|
| 1986 |
|
| 1987 |
def spec_of(res: Result) -> dict[str, Any]: |
| 1988 |
assert res.exit_code == ExitCode.OK |
| 1989 |
return cast("dict[str, Any]", json.loads(res.stdout)) |
| 1990 |
|
| 1991 |
|
| 1992 |
def option_named(spec: dict[str, Any], name: str) -> dict[str, Any]: |
| 1993 |
(option,) = [o for o in spec["options"] if o["name"] == name] |
| 1994 |
return cast("dict[str, Any]", option) |
| 1995 |
|
| 1996 |
|
| 1997 |
def test_spec_is_json(hsql: Hsql) -> None: |
| 1998 |
spec = spec_of(hsql("--spec")) |
| 1999 |
assert spec["program"] == "hsql" |
| 2000 |
assert spec["version"] |
| 2001 |
assert spec["options"] |
| 2002 |
assert spec["adapters"] |
| 2003 |
|
| 2004 |
|
| 2005 |
def test_spec_describes_an_option_a_caller_would_otherwise_guess_at( |
| 2006 |
hsql: Hsql, |
| 2007 |
) -> None: |
| 2008 |
"""What `--help` says in prose, as the four facts a caller needs. |
| 2009 |
|
| 2010 |
Whether it takes a value, what kind, what happens without it, and how to |
| 2011 |
spell it -- an agent that reads this does not have to try `--limit` twice |
| 2012 |
to find out it is not a flag. |
| 2013 |
""" |
| 2014 |
limit = option_named(spec_of(hsql("--spec")), "limit") |
| 2015 |
assert limit["decls"] == ["--limit"] |
| 2016 |
assert limit["type"] == "integer" |
| 2017 |
assert limit["default"] == 500 |
| 2018 |
assert limit["is_flag"] is False |
| 2019 |
assert limit["multiple"] is False |
| 2020 |
assert limit["choices"] is None |
| 2021 |
assert "rows fetched" in limit["help"] |
| 2022 |
|
| 2023 |
|
| 2024 |
def test_spec_names_the_values_a_choice_takes(hsql: Hsql) -> None: |
| 2025 |
"""The list `--format` will accept, so nobody has to parse it out of the |
| 2026 |
epilog.""" |
| 2027 |
from harlequin.hsql import output |
| 2028 |
|
| 2029 |
fmt = option_named(spec_of(hsql("--spec")), "format") |
| 2030 |
assert fmt["type"] == "choice" |
| 2031 |
assert fmt["choices"] == list(output.format_names()) |
| 2032 |
assert fmt["default"] == "table" |
| 2033 |
|
| 2034 |
|
| 2035 |
def test_spec_reports_every_option_in_one_vocabulary(hsql: Hsql) -> None: |
| 2036 |
"""Which is the point of the document: `float range` and `file` are click's |
| 2037 |
own words for a number and a path, and a caller reading a spec should not |
| 2038 |
have to learn click to know which is which.""" |
| 2039 |
from harlequin.hsql.modes.spec import TYPES |
| 2040 |
|
| 2041 |
spec = spec_of(hsql("--spec")) |
| 2042 |
reported = {option["type"] for option in spec["options"]} |
| 2043 |
reported |= {argument["type"] for argument in spec["arguments"]} |
| 2044 |
reported |= { |
| 2045 |
option["type"] |
| 2046 |
for adapter in spec["adapters"].values() |
| 2047 |
for option in adapter["options"] |
| 2048 |
} |
| 2049 |
assert reported <= set(TYPES.values()) |
| 2050 |
|
| 2051 |
|
| 2052 |
def test_spec_reports_the_types_behind_seconds_and_a_config_path( |
| 2053 |
hsql: Hsql, |
| 2054 |
) -> None: |
| 2055 |
spec = spec_of(hsql("--spec")) |
| 2056 |
assert option_named(spec, "timeout")["type"] == "number" |
| 2057 |
assert option_named(spec, "config_path")["type"] == "path" |
| 2058 |
|
| 2059 |
|
| 2060 |
def test_spec_reports_no_default_as_null(hsql: Hsql) -> None: |
| 2061 |
"""An option with no default has none, spelled the way JSON spells nothing. |
| 2062 |
|
| 2063 |
click holds "no default" as a sentinel object, and a document that let one |
| 2064 |
through would say `--profile` defaults to the string `Sentinel.UNSET`. |
| 2065 |
""" |
| 2066 |
spec = spec_of(hsql("--spec")) |
| 2067 |
assert option_named(spec, "profile")["default"] is None |
| 2068 |
assert option_named(spec, "display_rows")["default"] is None |
| 2069 |
for option in spec["options"]: |
| 2070 |
assert option["default"] is None or isinstance( |
| 2071 |
option["default"], (str, int, float, bool, list) |
| 2072 |
) |
| 2073 |
|
| 2074 |
|
| 2075 |
def test_spec_reports_every_spelling_of_an_option(hsql: Hsql) -> None: |
| 2076 |
tuples_only = option_named(spec_of(hsql("--spec")), "tuples_only") |
| 2077 |
assert sorted(tuples_only["decls"]) == ["--tuples-only", "-t"] |
| 2078 |
assert tuples_only["is_flag"] is True |
| 2079 |
assert tuples_only["default"] is False |
| 2080 |
|
| 2081 |
|
| 2082 |
def test_spec_reports_a_repeatable_option_as_one(hsql: Hsql) -> None: |
| 2083 |
assert option_named(spec_of(hsql("--spec")), "command")["multiple"] is True |
| 2084 |
|
| 2085 |
|
| 2086 |
def test_spec_reports_an_environment_variable(hsql: Hsql) -> None: |
| 2087 |
"""A flag that reads the environment reads it whether or not it was typed, |
| 2088 |
which makes it exactly the kind of thing a caller wants told rather than |
| 2089 |
discovered.""" |
| 2090 |
config_path = option_named(spec_of(hsql("--spec")), "config_path") |
| 2091 |
assert config_path["envvar"] == "HARLEQUIN_CONFIG_PATH" |
| 2092 |
|
| 2093 |
|
| 2094 |
def test_spec_reports_an_envvar_for_every_option_that_reads_one(hsql: Hsql) -> None: |
| 2095 |
"""Null for the rest, because there is nothing behind them to report. |
| 2096 |
|
| 2097 |
hsql declares one `envvar=` and sets no `auto_envvar_prefix`, so click |
| 2098 |
derives nothing: `HSQL_LIMIT` is not read, and a spec that implied it was |
| 2099 |
would be worse than one that says null. This is the assertion that fails if |
| 2100 |
a prefix is ever set, or an option grows an `envvar=` this does not carry. |
| 2101 |
""" |
| 2102 |
spec = spec_of(hsql("--spec")) |
| 2103 |
named = {o["name"]: o["envvar"] for o in spec["options"] if o["envvar"]} |
| 2104 |
assert named == {"config_path": "HARLEQUIN_CONFIG_PATH"} |
| 2105 |
# `to_click()` passes no `envvar=`, so an adapter option cannot have one |
| 2106 |
for adapter in spec["adapters"].values(): |
| 2107 |
assert all(o["envvar"] is None for o in adapter["options"]) |
| 2108 |
|
| 2109 |
|
| 2110 |
def test_hsql_reads_no_environment_variable_it_did_not_declare( |
| 2111 |
hsql: Hsql, monkeypatch: pytest.MonkeyPatch |
| 2112 |
) -> None: |
| 2113 |
"""The other half: click reads a variable only where one was declared. |
| 2114 |
|
| 2115 |
Setting `auto_envvar_prefix` would make every flag configurable through the |
| 2116 |
environment, which is a surface `--spec` would then have to report -- so |
| 2117 |
assert the surface is the one the document describes. |
| 2118 |
""" |
| 2119 |
monkeypatch.setenv("HSQL_LIMIT", "3") |
| 2120 |
monkeypatch.setenv("HARLEQUIN_LIMIT", "3") |
| 2121 |
res = hsql("-a", "duckdb", "--no-init", ":memory:", "-tA", "-c", TEN_ROWS) |
| 2122 |
assert res.exit_code == ExitCode.OK |
| 2123 |
assert len(res.stdout.splitlines()) == 10 |
| 2124 |
|
| 2125 |
|
| 2126 |
def test_spec_names_the_positional(hsql: Hsql) -> None: |
| 2127 |
"""`CONN_STR` is where the database goes, and it has no flag to find it by. |
| 2128 |
|
| 2129 |
`nargs` of -1 is the half a caller cannot see any other way: one connection |
| 2130 |
string or five are both this argument. |
| 2131 |
""" |
| 2132 |
(conn_str,) = spec_of(hsql("--spec"))["arguments"] |
| 2133 |
assert conn_str["name"] == "conn_str" |
| 2134 |
assert conn_str["metavar"] == "CONN_STR" |
| 2135 |
assert conn_str["nargs"] == -1 |
| 2136 |
assert conn_str["required"] is False |
| 2137 |
|
| 2138 |
|
| 2139 |
def test_spec_covers_every_installed_adapter(hsql: Hsql) -> None: |
| 2140 |
from harlequin.plugins import adapter_names |
| 2141 |
|
| 2142 |
spec = spec_of(hsql("--spec")) |
| 2143 |
assert sorted(spec["adapters"]) == sorted(adapter_names()) |
| 2144 |
for adapter in spec["adapters"].values(): |
| 2145 |
assert adapter["error"] is None |
| 2146 |
assert adapter["options"] |
| 2147 |
assert adapter["version"] |
| 2148 |
|
| 2149 |
|
| 2150 |
def test_spec_reports_an_adapter_option_the_way_it_is_passed(hsql: Hsql) -> None: |
| 2151 |
"""The two spellings an adapter option has, and both are needed. |
| 2152 |
|
| 2153 |
`--no-init` is what a command line takes; `no_init` is what a profile |
| 2154 |
writes, and what the adapter's constructor is handed. A caller that had |
| 2155 |
only one of them would write the other wrong. |
| 2156 |
""" |
| 2157 |
duckdb = spec_of(hsql("--spec"))["adapters"]["duckdb"] |
| 2158 |
(no_init,) = [o for o in duckdb["options"] if o["name"] == "no_init"] |
| 2159 |
assert no_init["decls"] == ["--no-init"] |
| 2160 |
assert no_init["type"] == "boolean" |
| 2161 |
assert no_init["is_flag"] is True |
| 2162 |
assert no_init["default"] is False |
| 2163 |
assert no_init["help"] |
| 2164 |
|
| 2165 |
|
| 2166 |
def test_spec_reports_an_adapters_repeatable_and_chosen_options(hsql: Hsql) -> None: |
| 2167 |
"""One option of each shape, named off the lists both adapters always declare. |
| 2168 |
|
| 2169 |
sqlite's `--extension` and `--isolation-level` are appended only where the |
| 2170 |
interpreter's sqlite3 supports them, so neither is a name a test may assume |
| 2171 |
-- duckdb's `--extension` is in its list unconditionally, and is the |
| 2172 |
repeatable one here for that reason. |
| 2173 |
""" |
| 2174 |
spec = spec_of(hsql("--spec")) |
| 2175 |
duckdb = {o["name"]: o for o in spec["adapters"]["duckdb"]["options"]} |
| 2176 |
sqlite = {o["name"]: o for o in spec["adapters"]["sqlite"]["options"]} |
| 2177 |
assert duckdb["extension"]["multiple"] is True |
| 2178 |
assert sqlite["mode"]["type"] == "choice" |
| 2179 |
assert sqlite["mode"]["choices"] |
| 2180 |
assert sqlite["init_path"]["type"] == "path" |
| 2181 |
|
| 2182 |
|
| 2183 |
@pytest.mark.parametrize("name", ["duckdb", "sqlite"]) |
| 2184 |
def test_spec_reports_what_the_adapter_declares_now(hsql: Hsql, name: str) -> None: |
| 2185 |
"""The document is built from the declarations, not from a list of names. |
| 2186 |
|
| 2187 |
An adapter may declare a different set on a different interpreter -- sqlite |
| 2188 |
appends `--extension` only where `enable_load_extension` exists, which is |
| 2189 |
not on macOS -- so what `--spec` reports has to follow that, and a test that |
| 2190 |
pins names cannot tell the difference between the two. |
| 2191 |
""" |
| 2192 |
from harlequin.config import sluggify_option_name |
| 2193 |
from harlequin.plugins import load_adapter |
| 2194 |
|
| 2195 |
declared = { |
| 2196 |
sluggify_option_name(option.name) |
| 2197 |
for option in load_adapter(name).ADAPTER_OPTIONS or [] |
| 2198 |
} |
| 2199 |
reported = { |
| 2200 |
o["name"] |
| 2201 |
for o in spec_of(hsql("--spec", "-a", name))["adapters"][name]["options"] |
| 2202 |
} |
| 2203 |
# equal today, because neither in-tree adapter declares a spelling hsql's |
| 2204 |
# own flags take; a name that goes missing here is one hsql has claimed |
| 2205 |
assert reported == declared |
| 2206 |
|
| 2207 |
|
| 2208 |
def test_spec_narrows_to_one_adapter(hsql: Hsql) -> None: |
| 2209 |
"""`-a` is the only thing that changes the document, and it changes one |
| 2210 |
half of it: hsql's own options are hsql's own whatever adapter is named.""" |
| 2211 |
everything = spec_of(hsql("--spec")) |
| 2212 |
one = spec_of(hsql("--spec", "-a", "sqlite")) |
| 2213 |
assert list(one["adapters"]) == ["sqlite"] |
| 2214 |
assert one["adapters"]["sqlite"] == everything["adapters"]["sqlite"] |
| 2215 |
assert one["options"] == everything["options"] |
| 2216 |
|
| 2217 |
|
| 2218 |
def test_spec_says_what_it_does_not_cover(hsql: Hsql) -> None: |
| 2219 |
"""It cannot describe the IDE's flags -- reading them means importing the |
| 2220 |
command that builds them, which hsql may not do -- so it says where it |
| 2221 |
stops rather than reading as an exhaustive list that is not one.""" |
| 2222 |
scope = spec_of(hsql("--spec"))["scope"] |
| 2223 |
assert "harlequin" in scope |
| 2224 |
assert "not here" in scope |
| 2225 |
|
| 2226 |
|
| 2227 |
def test_spec_options_are_sorted_by_name(hsql: Hsql) -> None: |
| 2228 |
"""A document a caller diffs between two machines, or two releases.""" |
| 2229 |
spec = spec_of(hsql("--spec")) |
| 2230 |
assert [o["name"] for o in spec["options"]] == sorted( |
| 2231 |
o["name"] for o in spec["options"] |
| 2232 |
) |
| 2233 |
for adapter in spec["adapters"].values(): |
| 2234 |
assert [o["name"] for o in adapter["options"]] == sorted( |
| 2235 |
o["name"] for o in adapter["options"] |
| 2236 |
) |
| 2237 |
|
| 2238 |
|
| 2239 |
def test_spec_does_not_run_sql(hsql: Hsql) -> None: |
| 2240 |
res = hsql("--spec", ":memory:", "-c", "select 1") |
| 2241 |
assert res.exit_code == ExitCode.USAGE |
| 2242 |
assert res.stdout == "" |
| 2243 |
assert "does not run SQL" in res.stderr |
| 2244 |
|
| 2245 |
|
| 2246 |
def test_spec_carries_no_adapters_options(hsql: Hsql) -> None: |
| 2247 |
"""It describes the connection options rather than accepting them. |
| 2248 |
|
| 2249 |
A mode that connects to nothing has nothing to do with `--no-init`, and |
| 2250 |
taking it would be a flag that silently did nothing. |
| 2251 |
""" |
| 2252 |
res = hsql("--spec", "-a", "duckdb", "--no-init") |
| 2253 |
assert res.exit_code == ExitCode.USAGE |
| 2254 |
assert "--no-init" in res.stderr |
| 2255 |
|
| 2256 |
|
| 2257 |
def test_two_modes_is_a_usage_error_naming_both(hsql: Hsql) -> None: |
| 2258 |
"""Modes are options, so nothing about the parse stops a caller passing two |
| 2259 |
-- and two questions in one invocation have no answer that is not a guess |
| 2260 |
about which was meant.""" |
| 2261 |
res = hsql("--spec", "--config", "show") |
| 2262 |
assert res.exit_code == ExitCode.USAGE |
| 2263 |
assert res.stdout == "" |
| 2264 |
assert "--config show" in res.stderr |
| 2265 |
assert "--spec" in res.stderr |
| 2266 |
|
| 2267 |
|
| 2268 |
def test_spec_writes_nothing_under_format_none(hsql: Hsql) -> None: |
| 2269 |
res = hsql("--spec", "--format", "none") |
| 2270 |
assert res.exit_code == ExitCode.OK |
| 2271 |
assert res.stdout == "" |
| 2272 |
|
| 2273 |
|
| 2274 |
@pytest.mark.parametrize("argv", [["--csv"], ["--format", "markdown"]]) |
| 2275 |
def test_spec_notes_a_format_it_cannot_reach(hsql: Hsql, argv: list[str]) -> None: |
| 2276 |
"""A document is not rows, and silence would read as a format that applied.""" |
| 2277 |
res = hsql("--spec", *argv) |
| 2278 |
assert res.exit_code == ExitCode.OK |
| 2279 |
assert json.loads(res.stdout)["program"] == "hsql" |
| 2280 |
assert "had no effect" in res.stderr |
| 2281 |
assert "--format json" in res.stderr |
| 2282 |
|
| 2283 |
|
| 2284 |
def test_spec_json_is_not_a_format_it_declines(hsql: Hsql) -> None: |
| 2285 |
res = hsql("--spec", "--json") |
| 2286 |
assert res.exit_code == ExitCode.OK |
| 2287 |
assert json.loads(res.stdout)["program"] == "hsql" |
| 2288 |
assert res.stderr == "" |
| 2289 |
|
| 2290 |
|
| 2291 |
def test_spec_goes_to_the_file_dash_o_names(hsql: Hsql, tmp_path: Path) -> None: |
| 2292 |
destination = tmp_path / "spec.json" |
| 2293 |
res = hsql("--spec", "-o", str(destination)) |
| 2294 |
assert res.exit_code == ExitCode.OK |
| 2295 |
assert res.stdout == "" |
| 2296 |
assert json.loads(destination.read_text(encoding="utf-8"))["program"] == "hsql" |
| 2297 |
|
| 2298 |
|
| 2299 |
def test_spec_answers_over_a_config_it_could_not_read( |
| 2300 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 2301 |
) -> None: |
| 2302 |
"""The mode that describes the command does not depend on the config. |
| 2303 |
|
| 2304 |
A caller whose config file is broken is one of the callers most likely to |
| 2305 |
be reading this, and a spec that refused over a file it never needed would |
| 2306 |
be useless exactly there. |
| 2307 |
""" |
| 2308 |
cwd, _ = config_dirs |
| 2309 |
(cwd / ".harlequin.toml").write_text("this is not toml\n") |
| 2310 |
assert spec_of(hsql("--spec"))["program"] == "hsql" |
| 2311 |
|
| 2312 |
|
| 2313 |
def test_spec_ignores_a_profile_that_is_not_there( |
| 2314 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 2315 |
) -> None: |
| 2316 |
"""`-P` names a profile to connect with, and this mode connects with none.""" |
| 2317 |
assert spec_of(hsql("--spec", "-P", "no-such-profile"))["program"] == "hsql" |
| 2318 |
|
| 2319 |
|
| 2320 |
def test_spec_reports_an_adapter_it_could_not_import( |
| 2321 |
hsql: Hsql, monkeypatch: pytest.MonkeyPatch |
| 2322 |
) -> None: |
| 2323 |
"""An adapter that is installed and will not import is a fact about the |
| 2324 |
installation, not a reason to answer nothing about the rest of it.""" |
| 2325 |
from harlequin.exception import HarlequinConfigError |
| 2326 |
from harlequin.plugins import load_adapter as real_load_adapter |
| 2327 |
|
| 2328 |
def fake_load_adapter(name: str) -> Any: |
| 2329 |
if name == "duckdb": |
| 2330 |
raise HarlequinConfigError("No module named 'duckdb'", title="nope") |
| 2331 |
return real_load_adapter(name) |
| 2332 |
|
| 2333 |
monkeypatch.setattr("harlequin.plugins.load_adapter", fake_load_adapter) |
| 2334 |
res = hsql("--spec") |
| 2335 |
spec = spec_of(res) |
| 2336 |
assert spec["adapters"]["duckdb"]["options"] is None |
| 2337 |
assert "duckdb" in spec["adapters"]["duckdb"]["error"] |
| 2338 |
assert spec["adapters"]["sqlite"]["options"] |
| 2339 |
assert "could not be imported" in res.stderr |
| 2340 |
|
| 2341 |
|
| 2342 |
@pytest.mark.parametrize("argv", [["--help"], ["--help", "-a", "duckdb"]]) |
| 2343 |
def test_the_help_points_at_the_machine_readable_one( |
| 2344 |
hsql: Hsql, argv: list[str] |
| 2345 |
) -> None: |
| 2346 |
"""`--help` names adapters and `--spec` fills their options in. |
| 2347 |
|
| 2348 |
That is the trade the epilog makes -- a list of names rather than four |
| 2349 |
option tables -- so the end of the help is where a reader who wanted the |
| 2350 |
tables should be told where they are. Both spellings of the help say it: |
| 2351 |
`-a duckdb` answers for one adapter, and the JSON is still how you get all |
| 2352 |
of them. |
| 2353 |
""" |
| 2354 |
res = hsql(*argv) |
| 2355 |
assert res.exit_code == ExitCode.OK |
| 2356 |
assert f"{PROGRAM} --spec" in res.output |
| 2357 |
assert "Machine-readable:" in res.output |
| 2358 |
|
| 2359 |
|
| 2360 |
def test_spec_is_in_the_help(hsql: Hsql) -> None: |
| 2361 |
res = hsql("--help") |
| 2362 |
assert res.exit_code == ExitCode.OK |
| 2363 |
assert "--spec" in res.output |
| 2364 |
|
| 2365 |
|
| 2366 |
def test_spec_lists_the_flag_that_would_have_shown_the_help(hsql: Hsql) -> None: |
| 2367 |
"""click keeps `--help` out of a command's params and adds it at parse |
| 2368 |
time, so a document built from the params alone would omit the one flag |
| 2369 |
every caller already knows.""" |
| 2370 |
assert option_named(spec_of(hsql("--spec")), "help")["decls"] == ["--help"] |
| 2371 |
|
| 2372 |
|
| 2373 |
def test_spec_drops_a_spelling_an_hsql_flag_already_owns( |
| 2374 |
hsql: Hsql, monkeypatch: pytest.MonkeyPatch |
| 2375 |
) -> None: |
| 2376 |
"""It reports the surface a caller can type, not the one an adapter wanted. |
| 2377 |
|
| 2378 |
hsql's own flags win a collision (`_attach_adapter_options`), so an adapter |
| 2379 |
option declaring `-c` does not get it — and a spec that listed it anyway |
| 2380 |
would send a caller to write `hsql -c` and mean something else. |
| 2381 |
""" |
| 2382 |
from harlequin.options import FlagOption, TextOption |
| 2383 |
from harlequin.plugins import load_adapter as real_load_adapter |
| 2384 |
|
| 2385 |
shadowed = TextOption(name="command", description="Shadowed by hsql's -c.") |
| 2386 |
partly = FlagOption( |
| 2387 |
name="cautious", description="Keeps its long name.", short_decls=["-c", "-w"] |
| 2388 |
) |
| 2389 |
|
| 2390 |
def fake_load_adapter(name: str) -> Any: |
| 2391 |
adapter = real_load_adapter(name) |
| 2392 |
if name != "sqlite": |
| 2393 |
return adapter |
| 2394 |
return type("Faked", (adapter,), {"ADAPTER_OPTIONS": [shadowed, partly]}) |
| 2395 |
|
| 2396 |
monkeypatch.setattr("harlequin.plugins.load_adapter", fake_load_adapter) |
| 2397 |
options = spec_of(hsql("--spec", "-a", "sqlite"))["adapters"]["sqlite"]["options"] |
| 2398 |
# `command` is gone whole: hsql already has a parameter by that name |
| 2399 |
assert [o["name"] for o in options] == ["cautious"] |
| 2400 |
# and `-c` is gone from the one that kept its other spellings |
| 2401 |
assert options[0]["decls"] == ["--cautious", "-w"] |
| 2402 |
|
| 2403 |
|
| 2404 |
# --- `--info`, the mode that reports on the installation --------------------- |
| 2405 |
|
| 2406 |
|
| 2407 |
def info_of(res: Result) -> dict[str, Any]: |
| 2408 |
assert res.exit_code == ExitCode.OK |
| 2409 |
return cast("dict[str, Any]", json.loads(res.stdout)) |
| 2410 |
|
| 2411 |
|
| 2412 |
def test_info_is_json(hsql: Hsql) -> None: |
| 2413 |
info = info_of(hsql("--info")) |
| 2414 |
assert info["program"] == "hsql" |
| 2415 |
assert info["version"] |
| 2416 |
assert info["python"]["version"] |
| 2417 |
assert info["python"]["implementation"] |
| 2418 |
assert info["python"]["executable"] |
| 2419 |
assert info["platform"]["system"] |
| 2420 |
assert info["adapters"] |
| 2421 |
|
| 2422 |
|
| 2423 |
def test_info_reports_the_interpreter_it_is_running_under(hsql: Hsql) -> None: |
| 2424 |
"""The half of a bug report nobody remembers to include.""" |
| 2425 |
import platform |
| 2426 |
|
| 2427 |
info = info_of(hsql("--info")) |
| 2428 |
assert info["python"]["version"] == platform.python_version() |
| 2429 |
assert info["python"]["executable"] == sys.executable |
| 2430 |
assert info["platform"]["machine"] == platform.machine() |
| 2431 |
|
| 2432 |
|
| 2433 |
def test_info_lists_config_files_in_precedence_order( |
| 2434 |
hsql: Hsql, two_config_files: tuple[Path, Path] |
| 2435 |
) -> None: |
| 2436 |
"""Nearest first, which is the order that decides which file wins.""" |
| 2437 |
project, home = two_config_files |
| 2438 |
info = info_of(hsql("--info")) |
| 2439 |
assert info["config"] == { |
| 2440 |
"path": None, |
| 2441 |
"files": [str(project), str(home)], |
| 2442 |
} |
| 2443 |
|
| 2444 |
|
| 2445 |
def test_info_lists_no_config_files_when_there_are_none( |
| 2446 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 2447 |
) -> None: |
| 2448 |
assert info_of(hsql("--info"))["config"]["files"] == [] |
| 2449 |
|
| 2450 |
|
| 2451 |
def test_info_names_the_file_config_path_pointed_at(hsql: Hsql, tmp_path: Path) -> None: |
| 2452 |
"""An explicit file is the only one read, and it is the one to report.""" |
| 2453 |
path = tmp_path / "explicit.toml" |
| 2454 |
path.write_text('[profiles.here]\nadapter = "sqlite"\n') |
| 2455 |
config = info_of(hsql("--info", "--config-path", str(path)))["config"] |
| 2456 |
assert config["path"] == str(path) |
| 2457 |
assert config["files"] == [str(path)] |
| 2458 |
|
| 2459 |
|
| 2460 |
def test_info_names_the_active_profile_and_what_chose_the_adapter( |
| 2461 |
hsql: Hsql, two_config_files: tuple[Path, Path] |
| 2462 |
) -> None: |
| 2463 |
"""Which profile a run would use, and why it would connect where it does.""" |
| 2464 |
info = info_of(hsql("--info")) |
| 2465 |
assert info["profile"] == { |
| 2466 |
"name": "personal", |
| 2467 |
"options": {"adapter": "duckdb", "limit": 200000}, |
| 2468 |
"error": None, |
| 2469 |
} |
| 2470 |
assert info["adapter"] == {"name": "duckdb", "from": "profile"} |
| 2471 |
|
| 2472 |
|
| 2473 |
def test_info_reports_the_profile_dash_p_asked_for( |
| 2474 |
hsql: Hsql, two_config_files: tuple[Path, Path] |
| 2475 |
) -> None: |
| 2476 |
info = info_of(hsql("--info", "-P", "project")) |
| 2477 |
assert info["profile"]["name"] == "project" |
| 2478 |
assert info["adapter"] == {"name": "sqlite", "from": "profile"} |
| 2479 |
|
| 2480 |
|
| 2481 |
def test_info_says_dash_a_beat_the_profile( |
| 2482 |
hsql: Hsql, two_config_files: tuple[Path, Path] |
| 2483 |
) -> None: |
| 2484 |
"""`-a` wins over the profile, and a report that did not say so would send |
| 2485 |
a reader to the wrong file to change it.""" |
| 2486 |
assert info_of(hsql("--info", "-a", "sqlite"))["adapter"] == { |
| 2487 |
"name": "sqlite", |
| 2488 |
"from": "-a", |
| 2489 |
} |
| 2490 |
|
| 2491 |
|
| 2492 |
def test_info_falls_back_to_the_default_adapter( |
| 2493 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 2494 |
) -> None: |
| 2495 |
from harlequin.config import DEFAULT_ADAPTER |
| 2496 |
|
| 2497 |
assert info_of(hsql("--info"))["adapter"] == { |
| 2498 |
"name": DEFAULT_ADAPTER, |
| 2499 |
"from": "default", |
| 2500 |
} |
| 2501 |
|
| 2502 |
|
| 2503 |
def test_info_reports_a_profile_no_file_defines( |
| 2504 |
hsql: Hsql, two_config_files: tuple[Path, Path] |
| 2505 |
) -> None: |
| 2506 |
"""A `-P` typo is what this mode is most often run to find, so it is an |
| 2507 |
answer rather than a refusal -- and the answer a run would have refused |
| 2508 |
with.""" |
| 2509 |
info = info_of(hsql("--info", "-P", "prod")) |
| 2510 |
assert info["profile"]["name"] == "prod" |
| 2511 |
assert info["profile"]["options"] is None |
| 2512 |
assert "prod" in info["profile"]["error"] |
| 2513 |
# the same message a run gives, because it comes from the same resolution |
| 2514 |
res = hsql("-P", "prod", "-c", "select 1") |
| 2515 |
assert res.exit_code == ExitCode.USAGE |
| 2516 |
assert info["profile"]["error"] in res.stderr |
| 2517 |
|
| 2518 |
|
| 2519 |
def test_info_reports_a_default_profile_that_names_nothing( |
| 2520 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 2521 |
) -> None: |
| 2522 |
cwd, _ = config_dirs |
| 2523 |
(cwd / ".harlequin.toml").write_text( |
| 2524 |
'default_profile = "gone"\n[profiles.here]\nadapter = "sqlite"\n' |
| 2525 |
) |
| 2526 |
info = info_of(hsql("--info")) |
| 2527 |
assert info["profile"]["options"] is None |
| 2528 |
assert "default_profile" in info["profile"]["error"] |
| 2529 |
assert "gone" in info["profile"]["error"] |
| 2530 |
|
| 2531 |
|
| 2532 |
def test_info_reads_no_further_than_a_run_would( |
| 2533 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 2534 |
) -> None: |
| 2535 |
"""It reports the profile a run would use, so it stops where a run stops. |
| 2536 |
|
| 2537 |
A file behind the one that defines the profile is never opened, so its |
| 2538 |
contents cannot turn this into a report about a problem no run would meet. |
| 2539 |
`--config validate` is the mode that reads every file. |
| 2540 |
""" |
| 2541 |
cwd, home = config_dirs |
| 2542 |
(cwd / ".harlequin.toml").write_text( |
| 2543 |
'default_profile = "near"\n[profiles.near]\nadapter = "sqlite"\n' |
| 2544 |
) |
| 2545 |
(home / ".harlequin.toml").write_text("this is not toml\n") |
| 2546 |
|
| 2547 |
info = info_of(hsql("--info")) |
| 2548 |
assert info["profile"] == { |
| 2549 |
"name": "near", |
| 2550 |
"options": {"adapter": "sqlite"}, |
| 2551 |
"error": None, |
| 2552 |
} |
| 2553 |
# discovery still names it: it is a file on disk that a run may yet read |
| 2554 |
assert info["config"]["files"] == [ |
| 2555 |
str(cwd / ".harlequin.toml"), |
| 2556 |
str(home / ".harlequin.toml"), |
| 2557 |
] |
| 2558 |
|
| 2559 |
|
| 2560 |
def test_info_reports_the_profile_named_none_as_the_defaults( |
| 2561 |
hsql: Hsql, two_config_files: tuple[Path, Path] |
| 2562 |
) -> None: |
| 2563 |
info = info_of(hsql("--info", "-P", "None")) |
| 2564 |
assert info["profile"] == {"name": "None", "options": {}, "error": None} |
| 2565 |
|
| 2566 |
|
| 2567 |
def test_info_answers_over_a_config_it_could_not_read( |
| 2568 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 2569 |
) -> None: |
| 2570 |
"""A caller whose config file is broken is the caller most likely to be |
| 2571 |
running this, so the parse error is part of the answer.""" |
| 2572 |
cwd, _ = config_dirs |
| 2573 |
(cwd / ".harlequin.toml").write_text("this is not toml\n") |
| 2574 |
info = info_of(hsql("--info")) |
| 2575 |
assert info["config"]["files"] == [str(cwd / ".harlequin.toml")] |
| 2576 |
assert info["profile"]["options"] is None |
| 2577 |
assert "line 1" in info["profile"]["error"] |
| 2578 |
assert info["adapters"] |
| 2579 |
|
| 2580 |
|
| 2581 |
def test_info_reports_declared_capabilities_for_every_installed_adapter( |
| 2582 |
hsql: Hsql, |
| 2583 |
) -> None: |
| 2584 |
from importlib.metadata import version |
| 2585 |
|
| 2586 |
from harlequin.plugins import adapter_names |
| 2587 |
|
| 2588 |
info = info_of(hsql("--info")) |
| 2589 |
assert sorted(info["adapters"]) == sorted(adapter_names()) |
| 2590 |
for entry in info["adapters"].values(): |
| 2591 |
assert entry["error"] is None |
| 2592 |
assert entry["capabilities"]["implements_cancel"] in (True, False) |
| 2593 |
duckdb = info["adapters"]["duckdb"] |
| 2594 |
assert duckdb["distribution"] == "harlequin" |
| 2595 |
assert duckdb["version"] == version("harlequin") |
| 2596 |
|
| 2597 |
|
| 2598 |
def test_info_reads_the_capability_names_off_the_contract(hsql: Hsql) -> None: |
| 2599 |
"""A capability added to `HarlequinAdapter` is reported without this mode |
| 2600 |
keeping a second list of them.""" |
| 2601 |
from harlequin.adapter import HarlequinAdapter |
| 2602 |
|
| 2603 |
declared = sorted( |
| 2604 |
name.lower() |
| 2605 |
for name in vars(HarlequinAdapter) |
| 2606 |
if name.startswith("IMPLEMENTS_") |
| 2607 |
) |
| 2608 |
assert declared # the contract declares at least one |
| 2609 |
capabilities = info_of(hsql("--info"))["adapters"]["duckdb"]["capabilities"] |
| 2610 |
assert sorted(capabilities) == declared |
| 2611 |
|
| 2612 |
|
| 2613 |
def test_info_narrows_to_one_adapter(hsql: Hsql) -> None: |
| 2614 |
assert list(info_of(hsql("--info", "-a", "sqlite"))["adapters"]) == ["sqlite"] |
| 2615 |
|
| 2616 |
|
| 2617 |
def test_info_reports_an_adapter_it_could_not_import_as_unknown( |
| 2618 |
hsql: Hsql, monkeypatch: pytest.MonkeyPatch |
| 2619 |
) -> None: |
| 2620 |
"""Never `false`: guessing false about what an adapter implements is the |
| 2621 |
direction that gets someone hurt.""" |
| 2622 |
from harlequin.plugins import load_adapter as real_load_adapter |
| 2623 |
|
| 2624 |
def fake_load_adapter(name: str) -> Any: |
| 2625 |
if name == "duckdb": |
| 2626 |
raise HarlequinConfigError("No module named 'duckdb'", title="nope") |
| 2627 |
return real_load_adapter(name) |
| 2628 |
|
| 2629 |
monkeypatch.setattr("harlequin.plugins.load_adapter", fake_load_adapter) |
| 2630 |
res = hsql("--info") |
| 2631 |
info = info_of(res) |
| 2632 |
assert info["adapters"]["duckdb"]["capabilities"] == "unknown" |
| 2633 |
assert "duckdb" in info["adapters"]["duckdb"]["error"] |
| 2634 |
# and the rest of the installation is still reported |
| 2635 |
assert info["adapters"]["sqlite"]["capabilities"]["implements_cancel"] is True |
| 2636 |
assert "could not be imported" in res.stderr |
| 2637 |
|
| 2638 |
|
| 2639 |
def test_info_opens_no_connection(hsql: Hsql, monkeypatch: pytest.MonkeyPatch) -> None: |
| 2640 |
"""The design decision this mode exists on: the diagnostic a caller runs |
| 2641 |
when the database is unreachable must not itself require the database.""" |
| 2642 |
from harlequin.plugins import load_adapter as real_load_adapter |
| 2643 |
|
| 2644 |
def refuse(self: Any) -> Any: |
| 2645 |
raise AssertionError("--info opened a connection") |
| 2646 |
|
| 2647 |
def fake_load_adapter(name: str) -> Any: |
| 2648 |
return type("Faked", (real_load_adapter(name),), {"connect": refuse}) |
| 2649 |
|
| 2650 |
monkeypatch.setattr("harlequin.plugins.load_adapter", fake_load_adapter) |
| 2651 |
assert info_of(hsql("--info"))["adapters"]["duckdb"]["capabilities"] |
| 2652 |
|
| 2653 |
|
| 2654 |
def test_info_does_not_run_sql(hsql: Hsql) -> None: |
| 2655 |
res = hsql("--info", ":memory:", "-c", "select 1") |
| 2656 |
assert res.exit_code == ExitCode.USAGE |
| 2657 |
assert res.stdout == "" |
| 2658 |
assert "does not run SQL" in res.stderr |
| 2659 |
|
| 2660 |
|
| 2661 |
def test_info_carries_no_adapters_options(hsql: Hsql) -> None: |
| 2662 |
"""It reports what an adapter declares rather than taking its options.""" |
| 2663 |
res = hsql("--info", "-a", "duckdb", "--no-init") |
| 2664 |
assert res.exit_code == ExitCode.USAGE |
| 2665 |
assert "--no-init" in res.stderr |
| 2666 |
|
| 2667 |
|
| 2668 |
@pytest.mark.parametrize("other", [["--spec"], ["--config", "show"]]) |
| 2669 |
def test_info_beside_another_mode_is_a_usage_error( |
| 2670 |
hsql: Hsql, other: list[str] |
| 2671 |
) -> None: |
| 2672 |
res = hsql("--info", *other) |
| 2673 |
assert res.exit_code == ExitCode.USAGE |
| 2674 |
assert res.stdout == "" |
| 2675 |
assert "--info" in res.stderr |
| 2676 |
|
| 2677 |
|
| 2678 |
def test_info_writes_nothing_under_format_none(hsql: Hsql) -> None: |
| 2679 |
res = hsql("--info", "--format", "none") |
| 2680 |
assert res.exit_code == ExitCode.OK |
| 2681 |
assert res.stdout == "" |
| 2682 |
|
| 2683 |
|
| 2684 |
@pytest.mark.parametrize("argv", [["--csv"], ["--format", "markdown"]]) |
| 2685 |
def test_info_notes_a_format_it_cannot_reach(hsql: Hsql, argv: list[str]) -> None: |
| 2686 |
res = hsql("--info", *argv) |
| 2687 |
assert res.exit_code == ExitCode.OK |
| 2688 |
assert json.loads(res.stdout)["program"] == "hsql" |
| 2689 |
assert "had no effect" in res.stderr |
| 2690 |
assert "--format json" in res.stderr |
| 2691 |
|
| 2692 |
|
| 2693 |
def test_info_json_is_not_a_format_it_declines(hsql: Hsql) -> None: |
| 2694 |
res = hsql("--info", "--json") |
| 2695 |
assert res.exit_code == ExitCode.OK |
| 2696 |
assert json.loads(res.stdout)["program"] == "hsql" |
| 2697 |
assert res.stderr == "" |
| 2698 |
|
| 2699 |
|
| 2700 |
def test_info_goes_to_the_file_dash_o_names(hsql: Hsql, tmp_path: Path) -> None: |
| 2701 |
destination = tmp_path / "info.json" |
| 2702 |
res = hsql("--info", "-o", str(destination)) |
| 2703 |
assert res.exit_code == ExitCode.OK |
| 2704 |
assert res.stdout == "" |
| 2705 |
assert json.loads(destination.read_text(encoding="utf-8"))["program"] == "hsql" |
| 2706 |
|
| 2707 |
|
| 2708 |
def test_info_is_in_the_help(hsql: Hsql) -> None: |
| 2709 |
res = hsql("--help") |
| 2710 |
assert res.exit_code == ExitCode.OK |
| 2711 |
assert "--info" in res.output |
| 2712 |
assert f"{PROGRAM} --info" in res.output |
| 2713 |
|
| 2714 |
|
| 2715 |
# --- `--catalog`, the mode that lists one level of the catalog ---------------- |
| 2716 |
|
| 2717 |
CATALOG_DDL = ( |
| 2718 |
"create schema analytics; " |
| 2719 |
"create table analytics.orders " |
| 2720 |
"(id bigint, customer_id bigint, total decimal(18,2)); " |
| 2721 |
"create view analytics.order_summary as select 1 as n; " |
| 2722 |
'create schema "empty schema"; ' |
| 2723 |
'create schema "my.schema"; ' |
| 2724 |
'create table "my.schema"."t" (n bigint); ' |
| 2725 |
"create schema \u5206\u6790" |
| 2726 |
) |
| 2727 |
"""Two levels below the database, a node with no children, and two labels a path |
| 2728 |
cannot spell without quoting one and measuring the other in terminal cells.""" |
| 2729 |
|
| 2730 |
|
| 2731 |
def cells(stdout: str) -> list[list[str]]: |
| 2732 |
"""One `-tA` listing, as rows of cells.""" |
| 2733 |
return [row.split("|") for row in stdout.splitlines()] |
| 2734 |
|
| 2735 |
|
| 2736 |
def path_of(stdout: str, name: str) -> str: |
| 2737 |
"""The path cell of the row named `name`, which lists that item's children.""" |
| 2738 |
return next(row[0] for row in cells(stdout) if row[1] == name) |
| 2739 |
|
| 2740 |
|
| 2741 |
@pytest.fixture |
| 2742 |
def catalog_db(hsql: Hsql, tmp_path: Path) -> list[str]: |
| 2743 |
"""The arguments that reach a DuckDB file with a known catalog in it.""" |
| 2744 |
argv = ["-a", "duckdb", "--no-init", str(tmp_path / "cat.db")] |
| 2745 |
res = hsql(*argv, "--format", "none", "-c", CATALOG_DDL) |
| 2746 |
assert res.exit_code == ExitCode.OK |
| 2747 |
return argv |
| 2748 |
|
| 2749 |
|
| 2750 |
def test_catalog_lists_the_top_level(hsql: Hsql, catalog_db: list[str]) -> None: |
| 2751 |
res = hsql(*catalog_db, "--catalog", "-tA") |
| 2752 |
assert res.exit_code == ExitCode.OK |
| 2753 |
assert res.stdout == 'cat|cat|"cat"|database|db\n' |
| 2754 |
|
| 2755 |
|
| 2756 |
def test_catalog_lists_one_level_below_path(hsql: Hsql, catalog_db: list[str]) -> None: |
| 2757 |
res = hsql(*catalog_db, "--catalog", "--path", "cat", "-tA") |
| 2758 |
assert res.exit_code == ExitCode.OK |
| 2759 |
assert [row[1] for row in cells(res.stdout)] == [ |
| 2760 |
"analytics", |
| 2761 |
"empty schema", |
| 2762 |
"main", |
| 2763 |
"my.schema", |
| 2764 |
"\u5206\u6790", |
| 2765 |
] |
| 2766 |
|
| 2767 |
|
| 2768 |
def test_catalog_describes_a_relation_by_listing_it( |
| 2769 |
hsql: Hsql, catalog_db: list[str] |
| 2770 |
) -> None: |
| 2771 |
"""There is no second mode for describing: a relation's children are its |
| 2772 |
columns, with their types and their quoted identifiers.""" |
| 2773 |
res = hsql(*catalog_db, "--catalog", "--path", "cat.analytics.orders", "-tA") |
| 2774 |
assert res.exit_code == ExitCode.OK |
| 2775 |
assert cells(res.stdout) == [ |
| 2776 |
[ |
| 2777 |
"cat.analytics.orders.customer_id", |
| 2778 |
"customer_id", |
| 2779 |
'"customer_id"', |
| 2780 |
"BIGINT", |
| 2781 |
"##", |
| 2782 |
], |
| 2783 |
["cat.analytics.orders.id", "id", '"id"', "BIGINT", "##"], |
| 2784 |
["cat.analytics.orders.total", "total", '"total"', "DECIMAL(18,2)", "#.#"], |
| 2785 |
] |
| 2786 |
|
| 2787 |
|
| 2788 |
def test_every_level_reports_the_type_its_database_calls_it( |
| 2789 |
hsql: Hsql, catalog_db: list[str] |
| 2790 |
) -> None: |
| 2791 |
"""`type` is the adapter's own vocabulary, not one core invented for it.""" |
| 2792 |
res = hsql(*catalog_db, "--catalog", "--path", "cat.analytics", "-tA") |
| 2793 |
assert res.exit_code == ExitCode.OK |
| 2794 |
assert [(row[1], row[3]) for row in cells(res.stdout)] == [ |
| 2795 |
("order_summary", "VIEW"), |
| 2796 |
("orders", "BASE TABLE"), |
| 2797 |
] |
| 2798 |
|
| 2799 |
res = hsql(*catalog_db, "--catalog", "--path", "cat", "-tA") |
| 2800 |
assert res.exit_code == ExitCode.OK |
| 2801 |
assert {row[3] for row in cells(res.stdout)} == {"schema"} |
| 2802 |
|
| 2803 |
|
| 2804 |
def test_an_item_with_no_type_keeps_its_short_label(tmp_path: Path) -> None: |
| 2805 |
"""The degradation path, which no in-tree adapter takes: `type` is beside |
| 2806 |
`type_label` rather than instead of it, so a listing still says what these |
| 2807 |
things are.""" |
| 2808 |
from harlequin.adapter import HarlequinConnection |
| 2809 |
from harlequin.catalog import Catalog, CatalogItem |
| 2810 |
from harlequin.hsql.modes import catalog as catalog_mode |
| 2811 |
from harlequin.layout import LayoutOptions |
| 2812 |
from harlequin.navigate import CatalogPath |
| 2813 |
|
| 2814 |
class UntypedConnection: |
| 2815 |
def get_catalog(self) -> Catalog: |
| 2816 |
return Catalog( |
| 2817 |
items=[ |
| 2818 |
CatalogItem( |
| 2819 |
qualified_identifier='"t"', |
| 2820 |
query_name='"t"', |
| 2821 |
label="t", |
| 2822 |
type_label="t", |
| 2823 |
) |
| 2824 |
] |
| 2825 |
) |
| 2826 |
|
| 2827 |
destination = tmp_path / "listing.csv" |
| 2828 |
with destination.open("wb") as out: |
| 2829 |
catalog_mode.report( |
| 2830 |
out, |
| 2831 |
connection=cast("HarlequinConnection", UntypedConnection()), |
| 2832 |
path=CatalogPath(), |
| 2833 |
format_name="csv", |
| 2834 |
layout_options=LayoutOptions(), |
| 2835 |
file_options={}, |
| 2836 |
) |
| 2837 |
assert destination.read_text(encoding="utf-8").splitlines() == [ |
| 2838 |
"path,name,query_name,type,type_label", |
| 2839 |
't,t,"""t""",,t', |
| 2840 |
] |
| 2841 |
|
| 2842 |
|
| 2843 |
@pytest.mark.parametrize( |
| 2844 |
("adapter", "levels", "type_names"), |
| 2845 |
[ |
| 2846 |
("duckdb", ["main", "t"], ["BIGINT", "VARCHAR"]), |
| 2847 |
("sqlite", ["t"], ["bigint", "varchar"]), |
| 2848 |
], |
| 2849 |
) |
| 2850 |
def test_type_answers_for_every_bundled_adapter( |
| 2851 |
hsql: Hsql, |
| 2852 |
tmp_path: Path, |
| 2853 |
adapter: str, |
| 2854 |
levels: list[str], |
| 2855 |
type_names: list[str], |
| 2856 |
) -> None: |
| 2857 |
"""Both in-tree adapters populate it, out of introspection they already do. |
| 2858 |
|
| 2859 |
Each spells a type its own way, which is the point of carrying the |
| 2860 |
database's own name for it rather than a normalized one. |
| 2861 |
""" |
| 2862 |
argv = ["-a", adapter, "--no-init", str(tmp_path / f"{adapter}.db")] |
| 2863 |
res = hsql(*argv, "--format", "none", "-c", "create table t (n bigint, s varchar)") |
| 2864 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 2865 |
|
| 2866 |
res = hsql(*argv, "--catalog", "-tA") |
| 2867 |
assert res.exit_code == ExitCode.OK |
| 2868 |
database_path = cells(res.stdout)[0][0] |
| 2869 |
|
| 2870 |
res = hsql(*argv, "--catalog", "--path", ".".join([database_path, *levels]), "-tA") |
| 2871 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 2872 |
assert [(row[1], row[3]) for row in cells(res.stdout)] == [ |
| 2873 |
("n", type_names[0]), |
| 2874 |
("s", type_names[1]), |
| 2875 |
] |
| 2876 |
|
| 2877 |
|
| 2878 |
def test_the_path_column_is_what_lists_that_items_children( |
| 2879 |
hsql: Hsql, catalog_db: list[str] |
| 2880 |
) -> None: |
| 2881 |
"""Walking a catalog is copying a cell out of the last answer. |
| 2882 |
|
| 2883 |
A path an agent has to spell for itself is one it will spell wrong for a |
| 2884 |
label with a dot in it, which is the case this walks through. |
| 2885 |
""" |
| 2886 |
path = "" |
| 2887 |
for name in ("cat", "my.schema", "t"): |
| 2888 |
argv = ["--catalog", *(["--path", path] if path else [])] |
| 2889 |
res = hsql(*catalog_db, *argv, "-tA") |
| 2890 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 2891 |
path = path_of(res.stdout, name) |
| 2892 |
assert path == 'cat."my.schema".t' |
| 2893 |
|
| 2894 |
res = hsql(*catalog_db, "--catalog", "--path", path, "-tA") |
| 2895 |
assert res.exit_code == ExitCode.OK |
| 2896 |
assert [row[1] for row in cells(res.stdout)] == ["n"] |
| 2897 |
|
| 2898 |
|
| 2899 |
def test_catalog_measures_a_label_in_terminal_cells( |
| 2900 |
hsql: Hsql, catalog_db: list[str] |
| 2901 |
) -> None: |
| 2902 |
"""A listing is laid out like any other result set: two ideographs are four |
| 2903 |
cells, where `len()` would call them two.""" |
| 2904 |
res = hsql(*catalog_db, "--catalog", "--path", "cat") |
| 2905 |
assert res.exit_code == ExitCode.OK |
| 2906 |
# the path column is as wide as `cat.empty schema` and the name column as |
| 2907 |
# wide as `empty schema`; measured with len() these would be two cells short |
| 2908 |
assert " cat.\u5206\u6790 | \u5206\u6790 |" in res.stdout |
| 2909 |
|
| 2910 |
|
| 2911 |
def test_catalog_query_name_is_the_adapters_own_quoting( |
| 2912 |
hsql: Hsql, catalog_db: list[str] |
| 2913 |
) -> None: |
| 2914 |
"""The reason it is a column: the agent never guesses at a spelling.""" |
| 2915 |
res = hsql(*catalog_db, "--catalog", "--path", "cat.analytics", "-tA") |
| 2916 |
assert res.exit_code == ExitCode.OK |
| 2917 |
assert '"analytics"."orders"' in res.stdout |
| 2918 |
|
| 2919 |
|
| 2920 |
def test_a_trailing_wildcard_filters_one_level( |
| 2921 |
hsql: Hsql, catalog_db: list[str] |
| 2922 |
) -> None: |
| 2923 |
res = hsql(*catalog_db, "--catalog", "--path", "cat.analytics.order_s*", "-tA") |
| 2924 |
assert res.exit_code == ExitCode.OK |
| 2925 |
assert [row[1] for row in cells(res.stdout)] == ["order_summary"] |
| 2926 |
|
| 2927 |
|
| 2928 |
def test_an_interior_wildcard_is_a_usage_error( |
| 2929 |
hsql: Hsql, catalog_db: list[str] |
| 2930 |
) -> None: |
| 2931 |
"""It cannot be answered in one round trip, so it is refused rather than |
| 2932 |
quietly walked.""" |
| 2933 |
res = hsql(*catalog_db, "--catalog", "--path", "cat.*.orders") |
| 2934 |
assert res.exit_code == ExitCode.USAGE |
| 2935 |
assert res.stdout == "" |
| 2936 |
assert "wildcard" in res.stderr |
| 2937 |
|
| 2938 |
|
| 2939 |
def test_a_path_that_names_nothing_says_what_is_there( |
| 2940 |
hsql: Hsql, catalog_db: list[str] |
| 2941 |
) -> None: |
| 2942 |
res = hsql(*catalog_db, "--catalog", "--path", "cat.analytic") |
| 2943 |
assert res.exit_code == ExitCode.USAGE |
| 2944 |
assert res.stdout == "" |
| 2945 |
assert "Did you mean analytics?" in res.stderr |
| 2946 |
|
| 2947 |
|
| 2948 |
def test_a_node_with_no_children_is_zero_rows( |
| 2949 |
hsql: Hsql, catalog_db: list[str] |
| 2950 |
) -> None: |
| 2951 |
"""Not an error: an empty schema is an answer, and the footer says so.""" |
| 2952 |
res = hsql(*catalog_db, "--catalog", "--path", 'cat."empty schema"') |
| 2953 |
assert res.exit_code == ExitCode.OK |
| 2954 |
assert res.stdout.endswith("(0 rows)\n") |
| 2955 |
|
| 2956 |
|
| 2957 |
def test_catalog_takes_every_format_a_result_set_does( |
| 2958 |
hsql: Hsql, catalog_db: list[str] |
| 2959 |
) -> None: |
| 2960 |
"""A listing is rows, so it inherits the output layer rather than adding one.""" |
| 2961 |
res = hsql(*catalog_db, "--catalog", "--path", "cat.analytics", "--csv") |
| 2962 |
assert res.exit_code == ExitCode.OK |
| 2963 |
assert res.stdout.splitlines()[0] == "path,name,query_name,type,type_label" |
| 2964 |
|
| 2965 |
res = hsql(*catalog_db, "--catalog", "--path", "cat.analytics", "--json") |
| 2966 |
assert res.exit_code == ExitCode.OK |
| 2967 |
assert [row["name"] for row in json.loads(res.stdout)] == [ |
| 2968 |
"order_summary", |
| 2969 |
"orders", |
| 2970 |
] |
| 2971 |
|
| 2972 |
|
| 2973 |
def test_catalog_goes_to_the_file_dash_o_names( |
| 2974 |
hsql: Hsql, catalog_db: list[str], tmp_path: Path |
| 2975 |
) -> None: |
| 2976 |
destination = tmp_path / "catalog.csv" |
| 2977 |
res = hsql(*catalog_db, "--catalog", "-o", str(destination), "--csv") |
| 2978 |
assert res.exit_code == ExitCode.OK |
| 2979 |
assert res.stdout == "" |
| 2980 |
assert destination.read_text(encoding="utf-8").splitlines()[1].startswith("cat,cat") |
| 2981 |
|
| 2982 |
|
| 2983 |
def test_catalog_writes_nothing_under_format_none( |
| 2984 |
hsql: Hsql, catalog_db: list[str] |
| 2985 |
) -> None: |
| 2986 |
res = hsql(*catalog_db, "--catalog", "--format", "none") |
| 2987 |
assert res.exit_code == ExitCode.OK |
| 2988 |
assert res.stdout == "" |
| 2989 |
|
| 2990 |
|
| 2991 |
def test_display_rows_caps_a_listing(hsql: Hsql, catalog_db: list[str]) -> None: |
| 2992 |
"""A listing with four hundred rows in it is a display problem, and the |
| 2993 |
layouts already solved it.""" |
| 2994 |
res = hsql(*catalog_db, "--catalog", "--path", "cat", "--display-rows", "2") |
| 2995 |
assert res.exit_code == ExitCode.OK |
| 2996 |
assert res.stdout.endswith("(2 of 5 rows)\n") |
| 2997 |
|
| 2998 |
|
| 2999 |
def test_display_rows_says_on_stderr_what_the_footer_cannot( |
| 3000 |
hsql: Hsql, catalog_db: list[str] |
| 3001 |
) -> None: |
| 3002 |
res = hsql(*catalog_db, "--catalog", "--path", "cat", "--display-rows", "2", "-t") |
| 3003 |
assert res.exit_code == ExitCode.OK |
| 3004 |
assert len(res.stdout.splitlines()) == 2 |
| 3005 |
assert "printed 2 of 5 rows" in res.stderr |
| 3006 |
|
| 3007 |
|
| 3008 |
def test_limit_says_it_did_not_reach_the_listing( |
| 3009 |
hsql: Hsql, catalog_db: list[str] |
| 3010 |
) -> None: |
| 3011 |
"""It is the hard fetch limit, and a listing is however many objects the |
| 3012 |
adapter reported. Silence would read as a limit that was applied.""" |
| 3013 |
res = hsql(*catalog_db, "--catalog", "--path", "cat", "--limit", "1", "-tA") |
| 3014 |
assert res.exit_code == ExitCode.OK |
| 3015 |
assert len(res.stdout.splitlines()) == 5 |
| 3016 |
assert "--limit" in res.stderr and "no effect" in res.stderr |
| 3017 |
|
| 3018 |
|
| 3019 |
def test_limit_left_at_its_default_says_nothing( |
| 3020 |
hsql: Hsql, catalog_db: list[str] |
| 3021 |
) -> None: |
| 3022 |
res = hsql(*catalog_db, "--catalog", "-tA") |
| 3023 |
assert res.exit_code == ExitCode.OK |
| 3024 |
assert res.stderr == "" |
| 3025 |
|
| 3026 |
|
| 3027 |
def test_catalog_does_not_run_sql(hsql: Hsql, catalog_db: list[str]) -> None: |
| 3028 |
res = hsql(*catalog_db, "--catalog", "-c", "select 1") |
| 3029 |
assert res.exit_code == ExitCode.USAGE |
| 3030 |
assert res.stdout == "" |
| 3031 |
assert "does not run SQL" in res.stderr |
| 3032 |
|
| 3033 |
|
| 3034 |
@pytest.mark.parametrize("other", [["--info"], ["--spec"], ["--config", "show"]]) |
| 3035 |
def test_catalog_beside_another_mode_is_a_usage_error( |
| 3036 |
hsql: Hsql, other: list[str] |
| 3037 |
) -> None: |
| 3038 |
res = hsql("--catalog", *other) |
| 3039 |
assert res.exit_code == ExitCode.USAGE |
| 3040 |
assert res.stdout == "" |
| 3041 |
assert "--catalog" in res.stderr |
| 3042 |
|
| 3043 |
|
| 3044 |
def test_path_without_catalog_is_a_usage_error(hsql: Hsql, duck: list[str]) -> None: |
| 3045 |
"""A flag that silently did nothing is the thing this command does not have.""" |
| 3046 |
res = hsql(*duck, "--path", "main", "-c", "select 1") |
| 3047 |
assert res.exit_code == ExitCode.USAGE |
| 3048 |
assert res.stdout == "" |
| 3049 |
assert "--path must be used with --catalog" in res.stderr |
| 3050 |
|
| 3051 |
|
| 3052 |
def test_catalog_carries_the_adapters_options( |
| 3053 |
hsql: Hsql, catalog_db: list[str] |
| 3054 |
) -> None: |
| 3055 |
"""It connects, so unlike the other modes it takes what a connection takes. |
| 3056 |
|
| 3057 |
`--force-install-extensions` because it reaches the adapter and changes |
| 3058 |
nothing on the way: with no `--extension` beside it there is nothing to |
| 3059 |
install. |
| 3060 |
""" |
| 3061 |
res = hsql(*catalog_db, "--catalog", "--force-install-extensions", "-tA") |
| 3062 |
assert res.exit_code == ExitCode.OK |
| 3063 |
assert res.stdout == 'cat|cat|"cat"|database|db\n' |
| 3064 |
|
| 3065 |
|
| 3066 |
def test_catalog_reads_the_profile_a_run_would( |
| 3067 |
hsql: Hsql, catalog_db: list[str], tmp_path: Path |
| 3068 |
) -> None: |
| 3069 |
"""It connects like a run, so it is configured like one.""" |
| 3070 |
config_file = tmp_path / "profile.toml" |
| 3071 |
# json.dumps, not an f-string: TOML reads a backslash in a basic string as |
| 3072 |
# an escape, so a Windows path would be a parse error rather than a path. |
| 3073 |
config_file.write_text( |
| 3074 |
f'[profiles.cat]\nadapter = "duckdb"\n' |
| 3075 |
f"conn_str = [{json.dumps(catalog_db[-1])}]\n" |
| 3076 |
"no_init = true\n" |
| 3077 |
) |
| 3078 |
res = hsql("--config-path", str(config_file), "-P", "cat", "--catalog", "-tA") |
| 3079 |
assert res.exit_code == ExitCode.OK |
| 3080 |
assert res.stdout == 'cat|cat|"cat"|database|db\n' |
| 3081 |
|
| 3082 |
|
| 3083 |
def test_catalog_answers_for_every_bundled_adapter( |
| 3084 |
hsql: Hsql, both_adapters: list[str] |
| 3085 |
) -> None: |
| 3086 |
"""Every adapter names its levels differently, and every one has a top.""" |
| 3087 |
res = hsql(*both_adapters, "--catalog", "-tA") |
| 3088 |
assert res.exit_code == ExitCode.OK |
| 3089 |
assert [row[4] for row in cells(res.stdout)] == ["db"] |
| 3090 |
|
| 3091 |
|
| 3092 |
def test_catalog_is_in_the_help(hsql: Hsql) -> None: |
| 3093 |
res = hsql("--help") |
| 3094 |
assert res.exit_code == ExitCode.OK |
| 3095 |
assert "--catalog" in res.output |
| 3096 |
assert "--path" in res.output |
| 3097 |
assert f"{PROGRAM} --catalog --path" in res.output |
| 3098 |
|
| 3099 |
|
| 3100 |
# --- `--catalog-search`, which searches a catalog instead of walking it ----- |
| 3101 |
|
| 3102 |
|
| 3103 |
def test_catalog_search_reaches_every_level_in_one_ask( |
| 3104 |
hsql: Hsql, catalog_db: list[str] |
| 3105 |
) -> None: |
| 3106 |
"""The question a walk cannot answer: where the thing named that lives, |
| 3107 |
whatever level it is on.""" |
| 3108 |
res = hsql(*catalog_db, "--catalog-search", "order", "-tA") |
| 3109 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 3110 |
assert [(row[0], row[3]) for row in cells(res.stdout)] == [ |
| 3111 |
("cat.analytics.order_summary", "VIEW"), |
| 3112 |
("cat.analytics.orders", "BASE TABLE"), |
| 3113 |
] |
| 3114 |
|
| 3115 |
|
| 3116 |
def test_catalog_search_matches_a_column_wherever_it_is( |
| 3117 |
hsql: Hsql, catalog_db: list[str] |
| 3118 |
) -> None: |
| 3119 |
res = hsql(*catalog_db, "--catalog-search", "CUSTOMER_ID", "-tA") |
| 3120 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 3121 |
assert cells(res.stdout) == [ |
| 3122 |
[ |
| 3123 |
"cat.analytics.orders.customer_id", |
| 3124 |
"customer_id", |
| 3125 |
'"customer_id"', |
| 3126 |
"BIGINT", |
| 3127 |
"##", |
| 3128 |
] |
| 3129 |
] |
| 3130 |
|
| 3131 |
|
| 3132 |
def test_catalog_search_matches_the_levels_above_a_relation_too( |
| 3133 |
hsql: Hsql, catalog_db: list[str] |
| 3134 |
) -> None: |
| 3135 |
"""A caller searching a catalog does not know its shape, so zero rows has |
| 3136 |
to mean nothing is named that -- not that the level was not looked at.""" |
| 3137 |
res = hsql(*catalog_db, "--catalog-search", "analytics", "-tA") |
| 3138 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 3139 |
assert [(row[0], row[4]) for row in cells(res.stdout)] == [("cat.analytics", "sch")] |
| 3140 |
|
| 3141 |
|
| 3142 |
def test_a_found_path_is_a_path_catalog_walks( |
| 3143 |
hsql: Hsql, catalog_db: list[str] |
| 3144 |
) -> None: |
| 3145 |
"""The two modes build their rows the same way, so a cell copied out of one |
| 3146 |
is an argument to the other -- including for a label with a dot in it.""" |
| 3147 |
res = hsql(*catalog_db, "--catalog-search", "t", "-tA") |
| 3148 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 3149 |
found = path_of(res.stdout, "t") |
| 3150 |
assert found == 'cat."my.schema".t' |
| 3151 |
|
| 3152 |
res = hsql(*catalog_db, "--catalog", "--path", found, "-tA") |
| 3153 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 3154 |
assert [row[1] for row in cells(res.stdout)] == ["n"] |
| 3155 |
|
| 3156 |
|
| 3157 |
def test_path_scopes_a_find(hsql: Hsql, catalog_db: list[str]) -> None: |
| 3158 |
res = hsql(*catalog_db, "--catalog-search", "n", "--path", 'cat."my.schema"', "-tA") |
| 3159 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 3160 |
assert [row[0] for row in cells(res.stdout)] == ['cat."my.schema".t.n'] |
| 3161 |
|
| 3162 |
|
| 3163 |
def test_a_scope_that_names_nothing_says_what_is_there( |
| 3164 |
hsql: Hsql, catalog_db: list[str] |
| 3165 |
) -> None: |
| 3166 |
res = hsql(*catalog_db, "--catalog-search", "orders", "--path", "cat.analytic") |
| 3167 |
assert res.exit_code == ExitCode.USAGE |
| 3168 |
assert res.stdout == "" |
| 3169 |
assert "Did you mean analytics?" in res.stderr |
| 3170 |
|
| 3171 |
|
| 3172 |
def test_a_wildcard_scope_is_a_usage_error(hsql: Hsql, catalog_db: list[str]) -> None: |
| 3173 |
"""`--catalog-search` already matches on a term; a second filter over the |
| 3174 |
same names is the same question asked twice.""" |
| 3175 |
res = hsql(*catalog_db, "--catalog-search", "orders", "--path", "cat.analytic*") |
| 3176 |
assert res.exit_code == ExitCode.USAGE |
| 3177 |
assert res.stdout == "" |
| 3178 |
assert "wildcard" in res.stderr |
| 3179 |
|
| 3180 |
|
| 3181 |
def test_a_term_that_matches_nothing_is_zero_rows( |
| 3182 |
hsql: Hsql, catalog_db: list[str] |
| 3183 |
) -> None: |
| 3184 |
res = hsql(*catalog_db, "--catalog-search", "nothing-is-called-this") |
| 3185 |
assert res.exit_code == ExitCode.OK |
| 3186 |
assert res.stdout.endswith("(0 rows)\n") |
| 3187 |
|
| 3188 |
|
| 3189 |
def test_a_blank_term_is_a_usage_error(hsql: Hsql, catalog_db: list[str]) -> None: |
| 3190 |
"""`--catalog-search "$NAME"` with nothing in NAME is a mistake, not a |
| 3191 |
request for the whole catalog.""" |
| 3192 |
res = hsql(*catalog_db, "--catalog-search", "") |
| 3193 |
assert res.exit_code == ExitCode.USAGE |
| 3194 |
assert res.stdout == "" |
| 3195 |
assert "--catalog-search needs a term" in res.stderr |
| 3196 |
|
| 3197 |
|
| 3198 |
def test_catalog_search_refuses_an_adapter_that_does_not_declare_it( |
| 3199 |
hsql: Hsql, monkeypatch: pytest.MonkeyPatch |
| 3200 |
) -> None: |
| 3201 |
"""Refused before it connects: an adapter that cannot search is one whose |
| 3202 |
catalog would have to be walked, and a `--catalog-search` that quietly |
| 3203 |
walked it is the round-trip cliff this mode exists to avoid.""" |
| 3204 |
from harlequin.adapter import HarlequinAdapter, HarlequinConnection |
| 3205 |
|
| 3206 |
class Unsearchable(HarlequinAdapter): |
| 3207 |
ADAPTER_OPTIONS = None |
| 3208 |
|
| 3209 |
def __init__(self, conn_str: Sequence[str], **options: Any) -> None: |
| 3210 |
pass |
| 3211 |
|
| 3212 |
def connect(self) -> HarlequinConnection: |
| 3213 |
raise AssertionError("connected before checking the declaration") |
| 3214 |
|
| 3215 |
entry_point = MagicMock() |
| 3216 |
entry_point.name = "unsearchable" |
| 3217 |
entry_point.load.return_value = Unsearchable |
| 3218 |
monkeypatch.setattr("harlequin.plugins.entry_points", lambda group: [entry_point]) |
| 3219 |
|
| 3220 |
res = hsql("-a", "unsearchable", "--catalog-search", "orders") |
| 3221 |
assert res.exit_code == ExitCode.USAGE |
| 3222 |
assert res.stdout == "" |
| 3223 |
assert "unsearchable" in res.stderr |
| 3224 |
assert "--catalog" in res.stderr and "--info" in res.stderr |
| 3225 |
|
| 3226 |
|
| 3227 |
def test_catalog_search_takes_every_format_a_result_set_does( |
| 3228 |
hsql: Hsql, catalog_db: list[str] |
| 3229 |
) -> None: |
| 3230 |
res = hsql(*catalog_db, "--catalog-search", "order", "--csv") |
| 3231 |
assert res.exit_code == ExitCode.OK |
| 3232 |
assert res.stdout.splitlines()[0] == "path,name,query_name,type,type_label" |
| 3233 |
|
| 3234 |
res = hsql(*catalog_db, "--catalog-search", "order", "--json") |
| 3235 |
assert res.exit_code == ExitCode.OK |
| 3236 |
assert [row["name"] for row in json.loads(res.stdout)] == [ |
| 3237 |
"order_summary", |
| 3238 |
"orders", |
| 3239 |
] |
| 3240 |
|
| 3241 |
|
| 3242 |
def test_catalog_search_goes_to_the_file_dash_o_names( |
| 3243 |
hsql: Hsql, catalog_db: list[str], tmp_path: Path |
| 3244 |
) -> None: |
| 3245 |
destination = tmp_path / "found.csv" |
| 3246 |
res = hsql( |
| 3247 |
*catalog_db, "--catalog-search", "orders", "-o", str(destination), "--csv" |
| 3248 |
) |
| 3249 |
assert res.exit_code == ExitCode.OK |
| 3250 |
assert res.stdout == "" |
| 3251 |
assert ( |
| 3252 |
destination.read_text(encoding="utf-8") |
| 3253 |
.splitlines()[1] |
| 3254 |
.startswith("cat.analytics.orders,orders") |
| 3255 |
) |
| 3256 |
|
| 3257 |
|
| 3258 |
def test_display_rows_caps_a_find(hsql: Hsql, catalog_db: list[str]) -> None: |
| 3259 |
res = hsql(*catalog_db, "--catalog-search", "order", "--display-rows", "1") |
| 3260 |
assert res.exit_code == ExitCode.OK |
| 3261 |
assert res.stdout.endswith("(1 of 2 rows)\n") |
| 3262 |
|
| 3263 |
|
| 3264 |
def test_limit_says_it_did_not_reach_the_find( |
| 3265 |
hsql: Hsql, catalog_db: list[str] |
| 3266 |
) -> None: |
| 3267 |
"""It is the hard fetch limit, and a search is however many objects the |
| 3268 |
adapter reported. Silence would read as a limit that was applied.""" |
| 3269 |
res = hsql(*catalog_db, "--catalog-search", "order", "--limit", "1", "-tA") |
| 3270 |
assert res.exit_code == ExitCode.OK |
| 3271 |
assert len(res.stdout.splitlines()) == 2 |
| 3272 |
assert "--limit" in res.stderr and "no effect" in res.stderr |
| 3273 |
|
| 3274 |
|
| 3275 |
def test_catalog_search_does_not_run_sql(hsql: Hsql, catalog_db: list[str]) -> None: |
| 3276 |
res = hsql(*catalog_db, "--catalog-search", "orders", "-c", "select 1") |
| 3277 |
assert res.exit_code == ExitCode.USAGE |
| 3278 |
assert res.stdout == "" |
| 3279 |
assert "does not run SQL" in res.stderr |
| 3280 |
|
| 3281 |
|
| 3282 |
@pytest.mark.parametrize( |
| 3283 |
"other", [["--catalog"], ["--info"], ["--spec"], ["--config", "show"]] |
| 3284 |
) |
| 3285 |
def test_catalog_search_beside_another_mode_is_a_usage_error( |
| 3286 |
hsql: Hsql, other: list[str] |
| 3287 |
) -> None: |
| 3288 |
res = hsql("--catalog-search", "orders", *other) |
| 3289 |
assert res.exit_code == ExitCode.USAGE |
| 3290 |
assert res.stdout == "" |
| 3291 |
assert "--catalog-search" in res.stderr |
| 3292 |
|
| 3293 |
|
| 3294 |
@pytest.mark.parametrize("adapter", ["duckdb", "sqlite"]) |
| 3295 |
def test_catalog_search_answers_for_every_bundled_adapter( |
| 3296 |
hsql: Hsql, tmp_path: Path, adapter: str |
| 3297 |
) -> None: |
| 3298 |
"""Both in-tree adapters implement the search, rather than declaring the |
| 3299 |
capability and leaving it to the ecosystem. Each spells the path to what it |
| 3300 |
found its own way, and each spells one `--catalog --path` walks.""" |
| 3301 |
argv = ["-a", adapter, "--no-init", str(tmp_path / f"{adapter}.db")] |
| 3302 |
res = hsql( |
| 3303 |
*argv, "--format", "none", "-c", "create table orders (customer_id bigint)" |
| 3304 |
) |
| 3305 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 3306 |
|
| 3307 |
res = hsql(*argv, "--catalog-search", "customer_id", "-tA") |
| 3308 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 3309 |
assert [row[1] for row in cells(res.stdout)] == ["customer_id"] |
| 3310 |
assert path_of(res.stdout, "customer_id").endswith("orders.customer_id") |
| 3311 |
|
| 3312 |
|
| 3313 |
def test_every_bundled_adapter_declares_catalog_search(hsql: Hsql) -> None: |
| 3314 |
"""`--info` is where a caller learns which adapters can search.""" |
| 3315 |
res = hsql("--info") |
| 3316 |
assert res.exit_code == ExitCode.OK |
| 3317 |
adapters = json.loads(res.stdout)["adapters"] |
| 3318 |
assert all( |
| 3319 |
adapters[name]["capabilities"]["implements_catalog_search"] |
| 3320 |
for name in ("duckdb", "sqlite") |
| 3321 |
) |
| 3322 |
|
| 3323 |
|
| 3324 |
def test_catalog_search_is_in_the_help(hsql: Hsql) -> None: |
| 3325 |
res = hsql("--help") |
| 3326 |
assert res.exit_code == ExitCode.OK |
| 3327 |
assert "--catalog-search" in res.output |
| 3328 |
assert f"{PROGRAM} --catalog-search" in res.output |
| 3329 |
|
| 3330 |
|
| 3331 |
# --- `--read-only`, and the capability it needs ------------------------------- |
| 3332 |
|
| 3333 |
|
| 3334 |
@pytest.fixture |
| 3335 |
def declares_nothing(monkeypatch: pytest.MonkeyPatch) -> str: |
| 3336 |
"""The name of an installed adapter that declares no capability at all. |
| 3337 |
|
| 3338 |
Which is every adapter the day before it adds a declaration, so this is |
| 3339 |
what a refusal has to be right about -- and `connect()` raising is what |
| 3340 |
proves the refusal came first. |
| 3341 |
""" |
| 3342 |
from harlequin.adapter import HarlequinAdapter, HarlequinConnection |
| 3343 |
|
| 3344 |
class DeclaresNothing(HarlequinAdapter): |
| 3345 |
ADAPTER_OPTIONS = None |
| 3346 |
|
| 3347 |
def __init__(self, conn_str: Sequence[str], **options: Any) -> None: |
| 3348 |
pass |
| 3349 |
|
| 3350 |
def connect(self) -> HarlequinConnection: |
| 3351 |
raise AssertionError("connected before checking the declaration") |
| 3352 |
|
| 3353 |
entry_point = MagicMock() |
| 3354 |
entry_point.name = "undeclared" |
| 3355 |
entry_point.load.return_value = DeclaresNothing |
| 3356 |
monkeypatch.setattr("harlequin.plugins.entry_points", lambda group: [entry_point]) |
| 3357 |
return "undeclared" |
| 3358 |
|
| 3359 |
|
| 3360 |
def test_read_only_refuses_an_adapter_that_does_not_declare_it( |
| 3361 |
hsql: Hsql, declares_nothing: str |
| 3362 |
) -> None: |
| 3363 |
"""A flag that no-ops is worse than one that is absent. |
| 3364 |
|
| 3365 |
An adapter drops an option it does not recognize, so a run that believed it |
| 3366 |
was read-only would write. Refused before it connects, which is the whole |
| 3367 |
of what the flag promises. |
| 3368 |
""" |
| 3369 |
res = hsql("-a", declares_nothing, "--read-only", "-c", "select 1") |
| 3370 |
assert res.exit_code == ExitCode.USAGE |
| 3371 |
assert res.stdout == "" |
| 3372 |
assert declares_nothing in res.stderr |
| 3373 |
assert "--read-only" in res.stderr and "--info" in res.stderr |
| 3374 |
|
| 3375 |
|
| 3376 |
def test_read_only_from_a_profile_is_refused_the_same_way( |
| 3377 |
hsql: Hsql, declares_nothing: str, tmp_path: Path |
| 3378 |
) -> None: |
| 3379 |
"""The spelling a human is likelier to have used, and to trust. |
| 3380 |
|
| 3381 |
`read_only = true` in a profile is a promise made once and relied on by |
| 3382 |
every invocation that loads it, so it is refused where the flag is. |
| 3383 |
""" |
| 3384 |
path = tmp_path / ".harlequin.toml" |
| 3385 |
path.write_text("[profiles.prod]\nread_only = true\n") |
| 3386 |
res = hsql( |
| 3387 |
"--config-path", |
| 3388 |
str(path), |
| 3389 |
"-P", |
| 3390 |
"prod", |
| 3391 |
"-a", |
| 3392 |
declares_nothing, |
| 3393 |
"-c", |
| 3394 |
"select 1", |
| 3395 |
) |
| 3396 |
assert res.exit_code == ExitCode.USAGE |
| 3397 |
assert res.stdout == "" |
| 3398 |
assert declares_nothing in res.stderr |
| 3399 |
assert "profile" in res.stderr |
| 3400 |
|
| 3401 |
|
| 3402 |
def test_read_only_is_refused_ahead_of_the_mode_that_would_connect( |
| 3403 |
hsql: Hsql, declares_nothing: str |
| 3404 |
) -> None: |
| 3405 |
"""`--catalog` connects too, so it meets the same refusal.""" |
| 3406 |
res = hsql("-a", declares_nothing, "--read-only", "--catalog") |
| 3407 |
assert res.exit_code == ExitCode.USAGE |
| 3408 |
assert res.stdout == "" |
| 3409 |
assert declares_nothing in res.stderr |
| 3410 |
|
| 3411 |
|
| 3412 |
def test_read_only_is_refused_before_it_is_written_into_a_profile( |
| 3413 |
hsql: Hsql, declares_nothing: str, init_dirs: tuple[Path, Path] |
| 3414 |
) -> None: |
| 3415 |
"""`--config init` imports the adapter to write the options it declares, so |
| 3416 |
it can refuse a profile that names one and a read-only it cannot honor -- |
| 3417 |
which is a profile no run would start under.""" |
| 3418 |
cwd, _ = init_dirs |
| 3419 |
res = hsql("--config", "init", "-P", "prod", "-a", declares_nothing, "--read-only") |
| 3420 |
assert res.exit_code == ExitCode.USAGE |
| 3421 |
assert declares_nothing in res.stderr |
| 3422 |
assert not (cwd / ".harlequin.toml").exists() |
| 3423 |
|
| 3424 |
|
| 3425 |
def test_config_validate_reports_a_read_only_the_adapter_cannot_do( |
| 3426 |
hsql: Hsql, declares_nothing: str, config_dirs: tuple[Path, Path] |
| 3427 |
) -> None: |
| 3428 |
"""`--config validate` imports an adapter per profile already, so it can |
| 3429 |
say that a profile pairs one with a read-only it cannot honor.""" |
| 3430 |
cwd, _ = config_dirs |
| 3431 |
(cwd / ".harlequin.toml").write_text( |
| 3432 |
f"[profiles.prod]\nadapter = '{declares_nothing}'\nread_only = true\n" |
| 3433 |
) |
| 3434 |
|
| 3435 |
# `-a` only to satisfy the choice of installed adapters; the mode reads the |
| 3436 |
# adapter each profile names |
| 3437 |
res = hsql("--config", "validate", "-a", declares_nothing, "-tA") |
| 3438 |
assert res.exit_code == ExitCode.USAGE |
| 3439 |
file, key, problem, _ = res.stdout.strip().split("|") |
| 3440 |
assert file == str(cwd / ".harlequin.toml") |
| 3441 |
assert key == "profiles.prod.read_only" |
| 3442 |
assert declares_nothing in problem |
| 3443 |
|
| 3444 |
|
| 3445 |
@pytest.mark.parametrize( |
| 3446 |
"mode", [["--info"], ["--spec"], ["--config", "show"], ["--config", "validate"]] |
| 3447 |
) |
| 3448 |
def test_read_only_does_not_refuse_a_mode_that_reads_no_database( |
| 3449 |
hsql: Hsql, declares_nothing: str, mode: list[str], config_dirs: tuple[Path, Path] |
| 3450 |
) -> None: |
| 3451 |
"""None of them can write whatever they are told -- and two of them are |
| 3452 |
where a caller finds out which adapter they are on and where its read-only |
| 3453 |
came from, which is no use if the flag refuses them.""" |
| 3454 |
res = hsql(*mode, "-a", declares_nothing, "--read-only") |
| 3455 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 3456 |
|
| 3457 |
|
| 3458 |
def test_info_reports_an_adapter_that_cannot_be_read_only( |
| 3459 |
hsql: Hsql, declares_nothing: str |
| 3460 |
) -> None: |
| 3461 |
"""`--info` is where the refusal points, so it answers rather than joining |
| 3462 |
in.""" |
| 3463 |
res = hsql("--info", "-a", declares_nothing, "--read-only") |
| 3464 |
assert res.exit_code == ExitCode.OK |
| 3465 |
capabilities = info_of(res)["adapters"][declares_nothing]["capabilities"] |
| 3466 |
assert capabilities["implements_read_only"] is False |
| 3467 |
|
| 3468 |
|
| 3469 |
def test_every_bundled_adapter_declares_read_only(hsql: Hsql) -> None: |
| 3470 |
"""`--info` is where a caller learns which adapters can be read-only.""" |
| 3471 |
adapters = info_of(hsql("--info"))["adapters"] |
| 3472 |
assert all( |
| 3473 |
adapters[name]["capabilities"]["implements_read_only"] |
| 3474 |
for name in ("duckdb", "sqlite") |
| 3475 |
) |
| 3476 |
|
| 3477 |
|
| 3478 |
def one_row_db(adapter: str, path: Path) -> list[str]: |
| 3479 |
"""A database with a table in it, written by the driver itself. |
| 3480 |
|
| 3481 |
Built outside hsql because a connection this process still holds is one |
| 3482 |
duckdb will not reopen under a different configuration -- and read-only is |
| 3483 |
a different configuration. |
| 3484 |
""" |
| 3485 |
if adapter == "duckdb": |
| 3486 |
import duckdb |
| 3487 |
|
| 3488 |
duck = duckdb.connect(str(path)) |
| 3489 |
duck.execute("create table t as select 1 as n") |
| 3490 |
duck.close() |
| 3491 |
else: |
| 3492 |
import sqlite3 |
| 3493 |
|
| 3494 |
lite = sqlite3.connect(str(path)) |
| 3495 |
lite.execute("create table t as select 1 as n") |
| 3496 |
lite.commit() |
| 3497 |
lite.close() |
| 3498 |
return ["-a", adapter, "--no-init", str(path)] |
| 3499 |
|
| 3500 |
|
| 3501 |
@pytest.mark.parametrize("adapter", ["duckdb", "sqlite"]) |
| 3502 |
def test_read_only_stops_a_write_on_every_bundled_adapter( |
| 3503 |
hsql: Hsql, tmp_path: Path, adapter: str |
| 3504 |
) -> None: |
| 3505 |
"""The flag's whole job, end to end: reads answer, writes fail.""" |
| 3506 |
argv = one_row_db(adapter, tmp_path / f"{adapter}.db") |
| 3507 |
|
| 3508 |
res = hsql(*argv, "--read-only", "-c", "select n from t", "-tA") |
| 3509 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 3510 |
assert res.stdout == "1\n" |
| 3511 |
|
| 3512 |
res = hsql(*argv, "--read-only", "-c", "insert into t values (2)") |
| 3513 |
assert res.exit_code == ExitCode.QUERY |
| 3514 |
assert res.stdout == "" |
| 3515 |
assert res.stderr |
| 3516 |
|
| 3517 |
|
| 3518 |
@pytest.mark.parametrize("spelling", ["-r", "--read-only"]) |
| 3519 |
def test_read_only_means_the_same_thing_however_it_is_spelled( |
| 3520 |
hsql: Hsql, tmp_path: Path, spelling: str |
| 3521 |
) -> None: |
| 3522 |
argv = one_row_db("sqlite", tmp_path / "one.db") |
| 3523 |
|
| 3524 |
res = hsql(*argv, spelling, "-c", "insert into t values (2)") |
| 3525 |
assert res.exit_code == ExitCode.QUERY |
| 3526 |
assert res.stdout == "" |
| 3527 |
|
| 3528 |
|
| 3529 |
def test_the_single_dash_long_spelling_is_not_one(hsql: Hsql, tmp_path: Path) -> None: |
| 3530 |
"""`-readonly` is two spellings' worth of nothing: `-r` and `--read-only` |
| 3531 |
are what a caller has, on both commands and for every adapter.""" |
| 3532 |
argv = one_row_db("sqlite", tmp_path / "one.db") |
| 3533 |
|
| 3534 |
res = hsql(*argv, "-readonly", "-c", "insert into t values (2)") |
| 3535 |
assert res.exit_code == ExitCode.USAGE |
| 3536 |
assert res.stdout == "" |
| 3537 |
|
| 3538 |
|
| 3539 |
def test_read_only_is_in_the_help(hsql: Hsql) -> None: |
| 3540 |
"""On the adapter-agnostic surface, because the refusal is too.""" |
| 3541 |
res = hsql("--help") |
| 3542 |
assert res.exit_code == ExitCode.OK |
| 3543 |
assert "--read-only" in res.output |
| 3544 |
|
| 3545 |
|
| 3546 |
# --- secrets, and the promise that none of them is printed ------------------- |
| 3547 |
|
| 3548 |
SECRET = "hunter2-and-then-some" |
| 3549 |
"""One value, in a profile and in a connection string, asserted for negatively. |
| 3550 |
|
| 3551 |
Long enough that finding it in the output is unambiguous, and distinctive |
| 3552 |
enough that a substring search over every byte written means what it says. |
| 3553 |
""" |
| 3554 |
|
| 3555 |
|
| 3556 |
@pytest.fixture |
| 3557 |
def secret_config(config_dirs: tuple[Path, Path]) -> Path: |
| 3558 |
"""A profile with a secret in an option *and* in a connection string. |
| 3559 |
|
| 3560 |
Both halves, because they are hidden by two different mechanisms: |
| 3561 |
`md_token` is masked because the DuckDB adapter declares it secret, and the |
| 3562 |
token in the connection string because `redact_conn_str` reads the DSN. |
| 3563 |
""" |
| 3564 |
cwd, _ = config_dirs |
| 3565 |
path = cwd / ".harlequin.toml" |
| 3566 |
path.write_text( |
| 3567 |
'default_profile = "md"\n' |
| 3568 |
"[profiles.md]\n" |
| 3569 |
'adapter = "duckdb"\n' |
| 3570 |
f'conn_str = [ "md:my_db?motherduck_token={SECRET}" ]\n' |
| 3571 |
f'md_token = "{SECRET}"\n' |
| 3572 |
"limit = 500\n" |
| 3573 |
) |
| 3574 |
return path |
| 3575 |
|
| 3576 |
|
| 3577 |
def test_info_prints_no_secret(hsql: Hsql, secret_config: Path) -> None: |
| 3578 |
"""The document a caller pastes into an issue.""" |
| 3579 |
res = hsql("--info") |
| 3580 |
assert res.exit_code == ExitCode.OK |
| 3581 |
assert SECRET not in res.output |
| 3582 |
options = json.loads(res.stdout)["profile"]["options"] |
| 3583 |
assert options["md_token"] == "********" |
| 3584 |
assert options["conn_str"] == ["md:my_db?motherduck_token=********"] |
| 3585 |
# and still the document it was: what a reader needs is all still there |
| 3586 |
assert options["limit"] == 500 |
| 3587 |
assert options["adapter"] == "duckdb" |
| 3588 |
|
| 3589 |
|
| 3590 |
def test_config_show_prints_no_secret(hsql: Hsql, secret_config: Path) -> None: |
| 3591 |
"""Masked without importing an adapter to ask, which is why the fallback to |
| 3592 |
the key's name exists.""" |
| 3593 |
res = hsql("--config", "show") |
| 3594 |
assert res.exit_code == ExitCode.OK |
| 3595 |
assert SECRET not in res.output |
| 3596 |
assert 'md_token = "********"' in res.stdout |
| 3597 |
assert "motherduck_token=********" in res.stdout |
| 3598 |
# the provenance is the whole point of the mode, and survives |
| 3599 |
assert f"# from {secret_config}" in res.stdout |
| 3600 |
|
| 3601 |
|
| 3602 |
def test_config_show_masks_a_secret_the_key_name_does_not_give_away( |
| 3603 |
hsql: Hsql, config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch |
| 3604 |
) -> None: |
| 3605 |
"""The reason this mode imports the adapters its profiles name. |
| 3606 |
|
| 3607 |
A key called `hush` is not one core could have guessed at, and guessing is |
| 3608 |
what the fallback does. Only the adapter knows, so the mode asks it. |
| 3609 |
""" |
| 3610 |
from harlequin.options import TextOption |
| 3611 |
|
| 3612 |
monkeypatch.setattr( |
| 3613 |
"harlequin_duckdb.DuckDbAdapter.ADAPTER_OPTIONS", |
| 3614 |
[TextOption(name="hush", description="x", secret=True)], |
| 3615 |
) |
| 3616 |
cwd, _ = config_dirs |
| 3617 |
(cwd / ".harlequin.toml").write_text( |
| 3618 |
f'[profiles.one]\nadapter = "duckdb"\nhush = "{SECRET}"\n' |
| 3619 |
) |
| 3620 |
res = hsql("--config", "show") |
| 3621 |
assert res.exit_code == ExitCode.OK |
| 3622 |
assert SECRET not in res.output |
| 3623 |
assert 'hush = "********"' in res.stdout |
| 3624 |
|
| 3625 |
|
| 3626 |
def test_config_show_asks_the_default_adapter_for_a_profile_that_names_none( |
| 3627 |
hsql: Hsql, config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch |
| 3628 |
) -> None: |
| 3629 |
"""A profile with no `adapter` connects with the default, so that is the |
| 3630 |
one whose declarations decide what it is hiding.""" |
| 3631 |
from harlequin.options import TextOption |
| 3632 |
|
| 3633 |
monkeypatch.setattr( |
| 3634 |
"harlequin_duckdb.DuckDbAdapter.ADAPTER_OPTIONS", |
| 3635 |
[TextOption(name="hush", description="x", secret=True)], |
| 3636 |
) |
| 3637 |
cwd, _ = config_dirs |
| 3638 |
(cwd / ".harlequin.toml").write_text(f'[profiles.one]\nhush = "{SECRET}"\n') |
| 3639 |
res = hsql("--config", "show") |
| 3640 |
assert res.exit_code == ExitCode.OK |
| 3641 |
assert SECRET not in res.output |
| 3642 |
assert 'hush = "********"' in res.stdout |
| 3643 |
|
| 3644 |
|
| 3645 |
def test_config_show_says_when_it_masked_by_name_alone( |
| 3646 |
hsql: Hsql, config_dirs: tuple[Path, Path] |
| 3647 |
) -> None: |
| 3648 |
"""The one path where a value this would have masked might print, so it is |
| 3649 |
said out loud rather than left for a reader to notice.""" |
| 3650 |
cwd, _ = config_dirs |
| 3651 |
(cwd / ".harlequin.toml").write_text( |
| 3652 |
f'[profiles.one]\nadapter = "nonesuch"\npassword = "{SECRET}"\n' |
| 3653 |
) |
| 3654 |
res = hsql("--config", "show") |
| 3655 |
assert res.exit_code == ExitCode.OK |
| 3656 |
assert SECRET not in res.output |
| 3657 |
assert 'password = "********"' in res.stdout |
| 3658 |
assert "could not import nonesuch" in res.stderr |
| 3659 |
|
| 3660 |
|
| 3661 |
def test_config_show_json_prints_no_secret(hsql: Hsql, secret_config: Path) -> None: |
| 3662 |
res = hsql("--config", "show", "--json") |
| 3663 |
assert res.exit_code == ExitCode.OK |
| 3664 |
assert SECRET not in res.output |
| 3665 |
profile = json.loads(res.stdout)["profiles"]["md"]["value"] |
| 3666 |
assert profile["md_token"] == "********" |
| 3667 |
|
| 3668 |
|
| 3669 |
def test_config_list_profiles_prints_no_secret(hsql: Hsql, secret_config: Path) -> None: |
| 3670 |
"""It prints names rather than values, and this is what says so.""" |
| 3671 |
res = hsql("--config", "list-profiles") |
| 3672 |
assert res.exit_code == ExitCode.OK |
| 3673 |
assert SECRET not in res.output |
| 3674 |
assert "md" in res.stdout |
| 3675 |
|
| 3676 |
|
| 3677 |
def test_config_validate_prints_no_secret(hsql: Hsql, secret_config: Path) -> None: |
| 3678 |
res = hsql("--config", "validate") |
| 3679 |
assert SECRET not in res.output |
| 3680 |
|
| 3681 |
|
| 3682 |
def test_spec_prints_no_secret_and_says_which_options_are( |
| 3683 |
hsql: Hsql, secret_config: Path |
| 3684 |
) -> None: |
| 3685 |
"""`--spec` publishes no values, and publishes which options hold one. |
| 3686 |
|
| 3687 |
That key is what teaches an agent not to construct `hsql --md_token |
| 3688 |
hunter2`, where `ps` and a shell history can read it. |
| 3689 |
""" |
| 3690 |
res = hsql("--spec", "-a", "duckdb") |
| 3691 |
assert res.exit_code == ExitCode.OK |
| 3692 |
assert SECRET not in res.output |
| 3693 |
options = { |
| 3694 |
entry["name"]: entry |
| 3695 |
for entry in json.loads(res.stdout)["adapters"]["duckdb"]["options"] |
| 3696 |
} |
| 3697 |
assert options["md_token"]["secret"] is True |
| 3698 |
assert options["no_init"]["secret"] is False |
| 3699 |
# both halves of the document answer with the same keys |
| 3700 |
assert all("secret" in entry for entry in json.loads(res.stdout)["options"]) |
| 3701 |
|
| 3702 |
|
| 3703 |
def test_spec_masks_a_default_an_adapter_shipped_for_a_secret( |
| 3704 |
hsql: Hsql, monkeypatch: pytest.MonkeyPatch |
| 3705 |
) -> None: |
| 3706 |
"""An adapter that ships a default for a secret has shipped the secret, and |
| 3707 |
this document would otherwise write it down for every installation.""" |
| 3708 |
from harlequin.options import TextOption |
| 3709 |
|
| 3710 |
monkeypatch.setattr( |
| 3711 |
"harlequin_duckdb.DuckDbAdapter.ADAPTER_OPTIONS", |
| 3712 |
[TextOption(name="md_token", description="x", default=SECRET, secret=True)], |
| 3713 |
) |
| 3714 |
res = hsql("--spec", "-a", "duckdb") |
| 3715 |
assert res.exit_code == ExitCode.OK |
| 3716 |
assert SECRET not in res.output |
| 3717 |
(option,) = json.loads(res.stdout)["adapters"]["duckdb"]["options"] |
| 3718 |
assert option["default"] == "********" |
| 3719 |
|
| 3720 |
|
| 3721 |
def test_an_error_that_echoes_the_connection_string_prints_no_secret( |
| 3722 |
hsql: Hsql, secret_config: Path, monkeypatch: pytest.MonkeyPatch |
| 3723 |
) -> None: |
| 3724 |
"""The backstop, and the case the option layer cannot reach: a driver that |
| 3725 |
quotes back the DSN it was handed.""" |
| 3726 |
|
| 3727 |
def exploding_connect(self: Any) -> Any: |
| 3728 |
raise HarlequinConnectionError(f"could not connect to {self.conn_str[0]}") |
| 3729 |
|
| 3730 |
monkeypatch.setattr( |
| 3731 |
"harlequin_duckdb.DuckDbAdapter.connect", exploding_connect, raising=True |
| 3732 |
) |
| 3733 |
res = hsql("-c", "select 1") |
| 3734 |
assert res.exit_code == ExitCode.CONNECTION |
| 3735 |
assert SECRET not in res.output |
| 3736 |
assert "could not connect to md:my_db?motherduck_token=********" in res.stderr |
| 3737 |
|
| 3738 |
|
| 3739 |
class _RefusingConnection: |
| 3740 |
"""A connection that refuses every statement, quoting the DSN as it does. |
| 3741 |
|
| 3742 |
Which is the shape of the failure that matters here: the message comes from |
| 3743 |
the driver, so nothing in the option layer has had a chance to shape it. |
| 3744 |
""" |
| 3745 |
|
| 3746 |
def execute(self, query: str) -> Any: |
| 3747 |
raise HarlequinQueryError(f"rejected: md:my_db?motherduck_token={SECRET}") |
| 3748 |
|
| 3749 |
|
| 3750 |
def test_stats_prints_no_secret( |
| 3751 |
hsql: Hsql, secret_config: Path, monkeypatch: pytest.MonkeyPatch |
| 3752 |
) -> None: |
| 3753 |
"""`--stats` carries the failure's message, so it carries this promise too. |
| 3754 |
|
| 3755 |
It is a second channel rather than the same one twice: the error goes to |
| 3756 |
stderr as prose, and this goes to stderr as JSON a script parses. |
| 3757 |
""" |
| 3758 |
monkeypatch.setattr( |
| 3759 |
"harlequin_duckdb.DuckDbAdapter.connect", lambda self: _RefusingConnection() |
| 3760 |
) |
| 3761 |
res = hsql("--stats", "-c", "select 1") |
| 3762 |
assert res.exit_code == ExitCode.QUERY |
| 3763 |
assert SECRET not in res.output |
| 3764 |
stats = json.loads(res.stderr.strip().splitlines()[-1]) |
| 3765 |
assert stats["status"] == "error" |
| 3766 |
assert "motherduck_token=********" in stats["error"] |
| 3767 |
|
| 3768 |
|
| 3769 |
def test_a_secret_typed_on_the_command_line_is_still_hidden_in_errors( |
| 3770 |
hsql: Hsql, monkeypatch: pytest.MonkeyPatch, tmp_path: Path |
| 3771 |
) -> None: |
| 3772 |
"""Typing one there is the thing `--spec` teaches a caller not to do, and |
| 3773 |
it is not a reason to print it back.""" |
| 3774 |
monkeypatch.chdir(tmp_path) |
| 3775 |
|
| 3776 |
def exploding_connect(self: Any) -> Any: |
| 3777 |
raise HarlequinConnectionError(f"token {self.md_token} rejected") |
| 3778 |
|
| 3779 |
monkeypatch.setattr("harlequin_duckdb.DuckDbAdapter.connect", exploding_connect) |
| 3780 |
res = hsql( |
| 3781 |
"-a", "duckdb", "--no-init", ":memory:", "--md_token", SECRET, "-c", "select 1" |
| 3782 |
) |
| 3783 |
assert res.exit_code == ExitCode.CONNECTION |
| 3784 |
assert SECRET not in res.output |
| 3785 |
assert "token ******** rejected" in res.stderr |
| 3786 |
|
| 3787 |
|
| 3788 |
def test_nothing_is_hidden_from_a_run_with_no_secrets( |
| 3789 |
hsql: Hsql, duck: list[str] |
| 3790 |
) -> None: |
| 3791 |
"""The other half: a message with nothing to hide is printed as it is.""" |
| 3792 |
res = hsql(*duck, "-c", "select nope") |
| 3793 |
assert res.exit_code == ExitCode.QUERY |
| 3794 |
assert "********" not in res.output |
| 3795 |
assert "nope" in res.stderr |
| 3796 |
|
| 3797 |
|
| 3798 |
def test_the_secret_still_reaches_the_adapter( |
| 3799 |
hsql: Hsql, secret_config: Path, monkeypatch: pytest.MonkeyPatch |
| 3800 |
) -> None: |
| 3801 |
"""Redaction is for output. A run that connected with asterisks would be a |
| 3802 |
worse bug than the one this is fixing.""" |
| 3803 |
seen: dict[str, Any] = {} |
| 3804 |
|
| 3805 |
def recording_connect(self: Any) -> Any: |
| 3806 |
seen["md_token"] = self.md_token |
| 3807 |
seen["conn_str"] = self.conn_str |
| 3808 |
raise HarlequinConnectionError("stop here") |
| 3809 |
|
| 3810 |
monkeypatch.setattr("harlequin_duckdb.DuckDbAdapter.connect", recording_connect) |
| 3811 |
hsql("-c", "select 1") |
| 3812 |
assert seen["md_token"] == SECRET |
| 3813 |
assert list(seen["conn_str"]) == [f"md:my_db?motherduck_token={SECRET}"] |
| 3814 |
|
| 3815 |
|
| 3816 |
# --- `${VAR}`, the environment a config file reads ---------------------------- |
| 3817 |
|
| 3818 |
|
| 3819 |
def test_a_profile_reads_a_variable_from_the_environment( |
| 3820 |
hsql: Hsql, config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch |
| 3821 |
) -> None: |
| 3822 |
"""End to end: a config file that names a variable, and a query that runs. |
| 3823 |
|
| 3824 |
Which is what the feature is for -- a profile a team shares, and a |
| 3825 |
credential each of them keeps in their own environment. |
| 3826 |
""" |
| 3827 |
monkeypatch.setenv("HARLEQUIN_TEST_DB", ":memory:") |
| 3828 |
cwd, _ = config_dirs |
| 3829 |
(cwd / ".harlequin.toml").write_text( |
| 3830 |
'default_profile = "prod"\n' |
| 3831 |
"[profiles.prod]\n" |
| 3832 |
'adapter = "duckdb"\n' |
| 3833 |
'conn_str = ["${HARLEQUIN_TEST_DB}"]\n' |
| 3834 |
"no_init = true\n" |
| 3835 |
) |
| 3836 |
res = hsql("-tA", "-c", "select 42") |
| 3837 |
assert res.exit_code == ExitCode.OK |
| 3838 |
assert res.stdout == "42\n" |
| 3839 |
|
| 3840 |
|
| 3841 |
def test_an_unset_variable_is_a_usage_error_that_names_it( |
| 3842 |
hsql: Hsql, config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch |
| 3843 |
) -> None: |
| 3844 |
"""Exit 2 before the connection, rather than an empty string three layers in.""" |
| 3845 |
monkeypatch.delenv("HARLEQUIN_TEST_TOKEN", raising=False) |
| 3846 |
cwd, _ = config_dirs |
| 3847 |
(cwd / ".harlequin.toml").write_text( |
| 3848 |
'default_profile = "prod"\n' |
| 3849 |
"[profiles.prod]\n" |
| 3850 |
'adapter = "duckdb"\n' |
| 3851 |
'md_token = "${HARLEQUIN_TEST_TOKEN}"\n' |
| 3852 |
) |
| 3853 |
res = hsql("-c", "select 1") |
| 3854 |
assert res.exit_code == ExitCode.USAGE |
| 3855 |
assert res.stdout == "" |
| 3856 |
assert "HARLEQUIN_TEST_TOKEN" in res.stderr |
| 3857 |
assert str(cwd / ".harlequin.toml") in res.stderr |
| 3858 |
|
| 3859 |
|
| 3860 |
def test_info_reports_an_unset_variable_rather_than_refusing( |
| 3861 |
hsql: Hsql, config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch |
| 3862 |
) -> None: |
| 3863 |
"""A caller whose config is broken is one of the likeliest to run `--info`, |
| 3864 |
so the variable it could not read is part of the answer.""" |
| 3865 |
monkeypatch.delenv("HARLEQUIN_TEST_TOKEN", raising=False) |
| 3866 |
cwd, _ = config_dirs |
| 3867 |
(cwd / ".harlequin.toml").write_text( |
| 3868 |
'default_profile = "prod"\n' |
| 3869 |
"[profiles.prod]\n" |
| 3870 |
'adapter = "duckdb"\n' |
| 3871 |
'md_token = "${HARLEQUIN_TEST_TOKEN}"\n' |
| 3872 |
) |
| 3873 |
res = hsql("--info") |
| 3874 |
assert res.exit_code == ExitCode.OK |
| 3875 |
profile = json.loads(res.stdout)["profile"] |
| 3876 |
assert profile["options"] is None |
| 3877 |
assert "HARLEQUIN_TEST_TOKEN" in profile["error"] |
| 3878 |
|
| 3879 |
|
| 3880 |
def test_config_validate_reports_an_unset_variable( |
| 3881 |
hsql: Hsql, config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch |
| 3882 |
) -> None: |
| 3883 |
"""The mode that reads every file reports this like any other problem.""" |
| 3884 |
monkeypatch.delenv("HARLEQUIN_TEST_TOKEN", raising=False) |
| 3885 |
cwd, _ = config_dirs |
| 3886 |
(cwd / ".harlequin.toml").write_text( |
| 3887 |
'[profiles.prod]\nadapter = "duckdb"\nmd_token = "${HARLEQUIN_TEST_TOKEN}"\n' |
| 3888 |
) |
| 3889 |
res = hsql("--config", "validate", "-tA") |
| 3890 |
assert res.exit_code == ExitCode.USAGE |
| 3891 |
file, key, problem, _ = res.stdout.strip().split("|") |
| 3892 |
assert file == str(cwd / ".harlequin.toml") |
| 3893 |
assert key == "profiles.prod.md_token" |
| 3894 |
assert "HARLEQUIN_TEST_TOKEN" in problem |
| 3895 |
|
| 3896 |
|
| 3897 |
def test_config_show_prints_the_variable_rather_than_what_it_resolves_to( |
| 3898 |
hsql: Hsql, config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch |
| 3899 |
) -> None: |
| 3900 |
"""The mode reports on config files, so it reports what they say. |
| 3901 |
|
| 3902 |
Which is also the answer a reader wants: `${HARLEQUIN_TEST_TOKEN}` says |
| 3903 |
where the value comes from, where the value itself would not -- and an |
| 3904 |
unset variable is not a reason to refuse a report about the file naming it. |
| 3905 |
""" |
| 3906 |
monkeypatch.delenv("HARLEQUIN_TEST_TOKEN", raising=False) |
| 3907 |
cwd, _ = config_dirs |
| 3908 |
(cwd / ".harlequin.toml").write_text( |
| 3909 |
'[profiles.md]\nadapter = "duckdb"\nconn_str = ["${HARLEQUIN_TEST_TOKEN}"]\n' |
| 3910 |
) |
| 3911 |
res = hsql("--config", "show") |
| 3912 |
assert res.exit_code == ExitCode.OK |
| 3913 |
assert 'conn_str = ["${HARLEQUIN_TEST_TOKEN}"]' in res.stdout |
| 3914 |
|
| 3915 |
|
| 3916 |
def test_info_masks_a_secret_read_from_the_environment( |
| 3917 |
hsql: Hsql, config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch |
| 3918 |
) -> None: |
| 3919 |
"""Interpolation resolves a value; it does not make one printable. |
| 3920 |
|
| 3921 |
Both mechanisms, over a value that was never written in the file: the |
| 3922 |
option DuckDB declares secret, and the credential inside the DSN. |
| 3923 |
""" |
| 3924 |
monkeypatch.setenv("HARLEQUIN_TEST_TOKEN", SECRET) |
| 3925 |
cwd, _ = config_dirs |
| 3926 |
(cwd / ".harlequin.toml").write_text( |
| 3927 |
'default_profile = "md"\n' |
| 3928 |
"[profiles.md]\n" |
| 3929 |
'adapter = "duckdb"\n' |
| 3930 |
'conn_str = ["md:my_db?motherduck_token=${HARLEQUIN_TEST_TOKEN}"]\n' |
| 3931 |
'md_token = "${HARLEQUIN_TEST_TOKEN}"\n' |
| 3932 |
) |
| 3933 |
res = hsql("--info") |
| 3934 |
assert res.exit_code == ExitCode.OK |
| 3935 |
assert SECRET not in res.output |
| 3936 |
options = json.loads(res.stdout)["profile"]["options"] |
| 3937 |
assert options["md_token"] == "********" |
| 3938 |
assert options["conn_str"] == ["md:my_db?motherduck_token=********"] |
| 3939 |
|
| 3940 |
|
| 3941 |
def test_config_init_writes_the_variable_rather_than_what_it_resolves_to( |
| 3942 |
hsql: Hsql, init_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch |
| 3943 |
) -> None: |
| 3944 |
"""Writing is the other side of reading, and it writes what it was given. |
| 3945 |
|
| 3946 |
`--config init` is how a caller puts `${MD_TOKEN}` in a config file from a |
| 3947 |
script, so what lands in the file has to be the six characters they typed. |
| 3948 |
""" |
| 3949 |
monkeypatch.setenv("HARLEQUIN_TEST_TOKEN", SECRET) |
| 3950 |
cwd, _ = init_dirs |
| 3951 |
res = hsql( |
| 3952 |
"--config", |
| 3953 |
"init", |
| 3954 |
"-P", |
| 3955 |
"md", |
| 3956 |
"-a", |
| 3957 |
"duckdb", |
| 3958 |
"--md_token", |
| 3959 |
"${HARLEQUIN_TEST_TOKEN}", |
| 3960 |
"md:my_db", |
| 3961 |
) |
| 3962 |
assert res.exit_code == ExitCode.OK |
| 3963 |
assert SECRET not in (cwd / ".harlequin.toml").read_text() |
| 3964 |
assert written(cwd / ".harlequin.toml")["profiles"]["md"]["md_token"] == ( |
| 3965 |
"${HARLEQUIN_TEST_TOKEN}" |
| 3966 |
) |
| 3967 |
|
| 3968 |
|
| 3969 |
def test_a_secret_read_from_the_environment_is_hidden_in_an_error( |
| 3970 |
hsql: Hsql, config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch |
| 3971 |
) -> None: |
| 3972 |
"""The backstop reaches a value that was never in a config file either.""" |
| 3973 |
monkeypatch.setenv("HARLEQUIN_TEST_TOKEN", SECRET) |
| 3974 |
cwd, _ = config_dirs |
| 3975 |
(cwd / ".harlequin.toml").write_text( |
| 3976 |
'default_profile = "md"\n' |
| 3977 |
"[profiles.md]\n" |
| 3978 |
'adapter = "duckdb"\n' |
| 3979 |
'md_token = "${HARLEQUIN_TEST_TOKEN}"\n' |
| 3980 |
) |
| 3981 |
|
| 3982 |
def exploding_connect(self: Any) -> Any: |
| 3983 |
raise HarlequinConnectionError(f"token {self.md_token} rejected") |
| 3984 |
|
| 3985 |
monkeypatch.setattr("harlequin_duckdb.DuckDbAdapter.connect", exploding_connect) |
| 3986 |
res = hsql("-c", "select 1") |
| 3987 |
assert res.exit_code == ExitCode.CONNECTION |
| 3988 |
assert SECRET not in res.output |
| 3989 |
assert "token ******** rejected" in res.stderr |
| 3990 |
|
| 3991 |
|
| 3992 |
# --- `--timeout`, and the cancellation it has to attribute -------------------- |
| 3993 |
|
| 3994 |
|
| 3995 |
class _StuckCursor: |
| 3996 |
"""A cursor whose fetch blocks until the connection is cancelled. |
| 3997 |
|
| 3998 |
What a cancelled DuckDB cursor does when it comes back: swallows the |
| 3999 |
interrupt and returns no rows, which is also what a query that matched |
| 4000 |
nothing returns. Nothing downstream can tell the two apart, which is why |
| 4001 |
hsql attributes the timeout itself. |
| 4002 |
""" |
| 4003 |
|
| 4004 |
def __init__(self, released: threading.Event) -> None: |
| 4005 |
self.released = released |
| 4006 |
|
| 4007 |
def columns(self) -> list[tuple[str, str]]: |
| 4008 |
return [("n", "##")] |
| 4009 |
|
| 4010 |
def set_limit(self, limit: int) -> "_StuckCursor": |
| 4011 |
return self |
| 4012 |
|
| 4013 |
def fetchall(self) -> None: |
| 4014 |
self.released.wait(timeout=30) |
| 4015 |
return None |
| 4016 |
|
| 4017 |
|
| 4018 |
class _StuckConnection: |
| 4019 |
"""A connection whose every query blocks until it is cancelled.""" |
| 4020 |
|
| 4021 |
def __init__(self, *, stoppable: bool = True) -> None: |
| 4022 |
self.stoppable = stoppable |
| 4023 |
self.released = threading.Event() |
| 4024 |
self.cancelled = False |
| 4025 |
|
| 4026 |
def execute(self, query: str) -> _StuckCursor: |
| 4027 |
return _StuckCursor(self.released) |
| 4028 |
|
| 4029 |
def get_catalog(self) -> Any: |
| 4030 |
self.released.wait(timeout=30) |
| 4031 |
from harlequin.catalog import Catalog |
| 4032 |
|
| 4033 |
return Catalog(items=[]) |
| 4034 |
|
| 4035 |
def cancel(self) -> None: |
| 4036 |
self.cancelled = True |
| 4037 |
if self.stoppable: |
| 4038 |
self.released.set() |
| 4039 |
|
| 4040 |
|
| 4041 |
@pytest.fixture |
| 4042 |
def stuck_adapter(monkeypatch: pytest.MonkeyPatch) -> list[_StuckConnection]: |
| 4043 |
"""An installed adapter whose queries block until they are cancelled. |
| 4044 |
|
| 4045 |
A fake rather than a slow query: the deadline, the cancel and the |
| 4046 |
attribution are what these tests are about, and a real query slow enough to |
| 4047 |
time out is one every machine has a different opinion about. |
| 4048 |
|
| 4049 |
Yields the list the connections it opened land in, so a test can ask whether |
| 4050 |
the cancel it promised actually happened. |
| 4051 |
""" |
| 4052 |
from harlequin.adapter import HarlequinAdapter |
| 4053 |
|
| 4054 |
opened: list[_StuckConnection] = [] |
| 4055 |
|
| 4056 |
class StuckAdapter(HarlequinAdapter): |
| 4057 |
ADAPTER_OPTIONS = None |
| 4058 |
IMPLEMENTS_CANCEL = True |
| 4059 |
|
| 4060 |
def __init__(self, conn_str: Sequence[str], **options: Any) -> None: |
| 4061 |
pass |
| 4062 |
|
| 4063 |
def connect(self) -> Any: |
| 4064 |
opened.append(_StuckConnection()) |
| 4065 |
return opened[-1] |
| 4066 |
|
| 4067 |
entry_point = MagicMock() |
| 4068 |
entry_point.name = "stuck" |
| 4069 |
entry_point.load.return_value = StuckAdapter |
| 4070 |
monkeypatch.setattr("harlequin.plugins.entry_points", lambda group: [entry_point]) |
| 4071 |
return opened |
| 4072 |
|
| 4073 |
|
| 4074 |
def test_timeout_cancels_the_run_and_attributes_it( |
| 4075 |
hsql: Hsql, stuck_adapter: list[_StuckConnection] |
| 4076 |
) -> None: |
| 4077 |
"""The whole flag, on the run it exists for. |
| 4078 |
|
| 4079 |
Nothing on stdout is the half a naive deadline gets wrong: the result set a |
| 4080 |
cancel produces is empty and error-free, and printing it would report "your |
| 4081 |
query returned nothing" for a query that was killed. |
| 4082 |
""" |
| 4083 |
res = hsql("-a", "stuck", "--timeout", "0.1", "-c", "select 1") |
| 4084 |
assert res.exit_code == ExitCode.TIMEOUT |
| 4085 |
assert res.stdout == "" |
| 4086 |
assert "timed out after 0.1s" in res.stderr |
| 4087 |
assert stuck_adapter[0].cancelled |
| 4088 |
|
| 4089 |
|
| 4090 |
def test_timeout_stops_the_statements_after_the_one_it_cancelled( |
| 4091 |
hsql: Hsql, stuck_adapter: list[_StuckConnection] |
| 4092 |
) -> None: |
| 4093 |
"""A script is stopped, not just the statement that ran too long.""" |
| 4094 |
res = hsql("-a", "stuck", "--timeout", "0.1", "-c", "select 1; select 2; select 3") |
| 4095 |
assert res.exit_code == ExitCode.TIMEOUT |
| 4096 |
assert res.stdout == "" |
| 4097 |
# the one it was inside when the clock ran out, and none after it |
| 4098 |
assert res.stderr.count("timed out") == 1 |
| 4099 |
|
| 4100 |
|
| 4101 |
def test_timeout_is_what_stats_reports( |
| 4102 |
hsql: Hsql, stuck_adapter: list[_StuckConnection] |
| 4103 |
) -> None: |
| 4104 |
"""`--stats` is the machine channel, so it says what stderr said.""" |
| 4105 |
res = hsql("-a", "stuck", "--timeout", "0.1", "--stats", "-c", "select 1") |
| 4106 |
assert res.exit_code == ExitCode.TIMEOUT |
| 4107 |
stats = json.loads(res.stderr.strip().splitlines()[-1]) |
| 4108 |
assert stats["status"] == "error" |
| 4109 |
assert stats["error"] == "timed out after 0.1s" |
| 4110 |
|
| 4111 |
|
| 4112 |
def test_timeout_bounds_a_catalog_listing_too( |
| 4113 |
hsql: Hsql, stuck_adapter: list[_StuckConnection] |
| 4114 |
) -> None: |
| 4115 |
"""`--catalog` connects and waits on the database like a run does, and a |
| 4116 |
safety flag that silently did nothing there would be the worse half of the |
| 4117 |
choice.""" |
| 4118 |
res = hsql("-a", "stuck", "--timeout", "0.1", "--catalog") |
| 4119 |
assert res.exit_code == ExitCode.TIMEOUT |
| 4120 |
assert "timed out after 0.1s" in res.stderr |
| 4121 |
assert stuck_adapter[0].cancelled |
| 4122 |
|
| 4123 |
|
| 4124 |
def test_a_run_inside_the_deadline_is_untouched(hsql: Hsql, duck: list[str]) -> None: |
| 4125 |
"""The clock is the only thing the flag adds: same bytes, same code.""" |
| 4126 |
res = hsql(*duck, "--timeout", "60", "-c", "select 1 as a") |
| 4127 |
assert res.exit_code == ExitCode.OK |
| 4128 |
assert res.stdout == " a\n---\n 1\n(1 row)\n" |
| 4129 |
assert res.stderr == "" |
| 4130 |
|
| 4131 |
|
| 4132 |
def test_timeout_refuses_an_adapter_that_cannot_cancel( |
| 4133 |
hsql: Hsql, declares_nothing: str |
| 4134 |
) -> None: |
| 4135 |
"""There is no way to stop the work, so a deadline could only lie about |
| 4136 |
having stopped it -- which is worse than not having the flag.""" |
| 4137 |
res = hsql("-a", declares_nothing, "--timeout", "30", "-c", "select 1") |
| 4138 |
assert res.exit_code == ExitCode.USAGE |
| 4139 |
assert res.stdout == "" |
| 4140 |
assert declares_nothing in res.stderr |
| 4141 |
assert "--timeout" in res.stderr and "--info" in res.stderr |
| 4142 |
|
| 4143 |
|
| 4144 |
def test_timeout_from_a_profile_is_refused_the_same_way( |
| 4145 |
hsql: Hsql, declares_nothing: str, tmp_path: Path |
| 4146 |
) -> None: |
| 4147 |
path = tmp_path / ".harlequin.toml" |
| 4148 |
path.write_text("[profiles.prod]\ntimeout = 30\n") |
| 4149 |
res = hsql( |
| 4150 |
"--config-path", |
| 4151 |
str(path), |
| 4152 |
"-P", |
| 4153 |
"prod", |
| 4154 |
"-a", |
| 4155 |
declares_nothing, |
| 4156 |
"-c", |
| 4157 |
"select 1", |
| 4158 |
) |
| 4159 |
assert res.exit_code == ExitCode.USAGE |
| 4160 |
assert res.stdout == "" |
| 4161 |
assert declares_nothing in res.stderr |
| 4162 |
assert "profile" in res.stderr |
| 4163 |
|
| 4164 |
|
| 4165 |
def test_timeout_is_refused_ahead_of_the_mode_that_would_connect( |
| 4166 |
hsql: Hsql, declares_nothing: str |
| 4167 |
) -> None: |
| 4168 |
res = hsql("-a", declares_nothing, "--timeout", "30", "--catalog") |
| 4169 |
assert res.exit_code == ExitCode.USAGE |
| 4170 |
assert res.stdout == "" |
| 4171 |
assert declares_nothing in res.stderr |
| 4172 |
|
| 4173 |
|
| 4174 |
def test_timeout_is_refused_before_it_is_written_into_a_profile( |
| 4175 |
hsql: Hsql, declares_nothing: str, init_dirs: tuple[Path, Path] |
| 4176 |
) -> None: |
| 4177 |
"""A profile pairing an adapter with a timeout it cannot honor is one no |
| 4178 |
run would start under.""" |
| 4179 |
cwd, _ = init_dirs |
| 4180 |
res = hsql( |
| 4181 |
"--config", "init", "-P", "prod", "-a", declares_nothing, "--timeout", "5" |
| 4182 |
) |
| 4183 |
assert res.exit_code == ExitCode.USAGE |
| 4184 |
assert declares_nothing in res.stderr |
| 4185 |
assert not (cwd / ".harlequin.toml").exists() |
| 4186 |
|
| 4187 |
|
| 4188 |
def test_config_validate_reports_a_timeout_the_adapter_cannot_do( |
| 4189 |
hsql: Hsql, declares_nothing: str, config_dirs: tuple[Path, Path] |
| 4190 |
) -> None: |
| 4191 |
cwd, _ = config_dirs |
| 4192 |
(cwd / ".harlequin.toml").write_text( |
| 4193 |
f"[profiles.prod]\nadapter = '{declares_nothing}'\ntimeout = 30\n" |
| 4194 |
) |
| 4195 |
|
| 4196 |
res = hsql("--config", "validate", "-a", declares_nothing, "-tA") |
| 4197 |
assert res.exit_code == ExitCode.USAGE |
| 4198 |
file, key, problem, _ = res.stdout.strip().split("|") |
| 4199 |
assert file == str(cwd / ".harlequin.toml") |
| 4200 |
assert key == "profiles.prod.timeout" |
| 4201 |
assert declares_nothing in problem |
| 4202 |
|
| 4203 |
|
| 4204 |
@pytest.mark.parametrize( |
| 4205 |
"mode", [["--info"], ["--spec"], ["--config", "show"], ["--config", "validate"]] |
| 4206 |
) |
| 4207 |
def test_timeout_does_not_refuse_a_mode_that_reads_no_database( |
| 4208 |
hsql: Hsql, declares_nothing: str, mode: list[str], config_dirs: tuple[Path, Path] |
| 4209 |
) -> None: |
| 4210 |
"""None of them waits on a database, and two of them are where a caller |
| 4211 |
finds out which adapter they are on.""" |
| 4212 |
res = hsql(*mode, "-a", declares_nothing, "--timeout", "30") |
| 4213 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 4214 |
|
| 4215 |
|
| 4216 |
@pytest.mark.parametrize("value", ["0", "-1", "abc"]) |
| 4217 |
def test_timeout_takes_a_positive_number_of_seconds( |
| 4218 |
hsql: Hsql, duck: list[str], value: str |
| 4219 |
) -> None: |
| 4220 |
res = hsql(*duck, "--timeout", value, "-c", "select 1") |
| 4221 |
assert res.exit_code == ExitCode.USAGE |
| 4222 |
assert res.stdout == "" |
| 4223 |
|
| 4224 |
|
| 4225 |
@pytest.mark.parametrize("value", ["0", "true", "'soon'"]) |
| 4226 |
def test_a_profile_takes_a_positive_number_of_seconds_too( |
| 4227 |
hsql: Hsql, tmp_path: Path, value: str |
| 4228 |
) -> None: |
| 4229 |
"""click vets what was typed; a config file can say anything.""" |
| 4230 |
path = tmp_path / ".harlequin.toml" |
| 4231 |
path.write_text(f"[profiles.prod]\nadapter = 'duckdb'\ntimeout = {value}\n") |
| 4232 |
res = hsql("--config-path", str(path), "-P", "prod", ":memory:", "-c", "select 1") |
| 4233 |
assert res.exit_code == ExitCode.USAGE |
| 4234 |
assert res.stdout == "" |
| 4235 |
assert "--timeout" in res.stderr |
| 4236 |
|
| 4237 |
|
| 4238 |
def test_every_bundled_adapter_declares_cancel(hsql: Hsql) -> None: |
| 4239 |
"""`--info` is where a caller learns which adapters can be timed out.""" |
| 4240 |
adapters = info_of(hsql("--info"))["adapters"] |
| 4241 |
assert all( |
| 4242 |
adapters[name]["capabilities"]["implements_cancel"] |
| 4243 |
for name in ("duckdb", "sqlite") |
| 4244 |
) |
| 4245 |
|
| 4246 |
|
| 4247 |
def test_timeout_is_in_the_help(hsql: Hsql) -> None: |
| 4248 |
res = hsql("--help") |
| 4249 |
assert res.exit_code == ExitCode.OK |
| 4250 |
assert "--timeout" in res.output |
| 4251 |
|
| 4252 |
|
| 4253 |
UNSTOPPABLE = """ |
| 4254 |
import sys, threading |
| 4255 |
from unittest.mock import MagicMock |
| 4256 |
|
| 4257 |
import harlequin.plugins |
| 4258 |
import harlequin.hsql.timeout as timeout |
| 4259 |
from harlequin.adapter import HarlequinAdapter |
| 4260 |
|
| 4261 |
timeout.GRACE_SECONDS = 0.5 |
| 4262 |
|
| 4263 |
|
| 4264 |
class Cursor: |
| 4265 |
def columns(self): return [("n", "##")] |
| 4266 |
def set_limit(self, limit): return self |
| 4267 |
def fetchall(self): threading.Event().wait(60) |
| 4268 |
|
| 4269 |
|
| 4270 |
class Connection: |
| 4271 |
def execute(self, query): return Cursor() |
| 4272 |
def get_catalog(self): raise NotImplementedError |
| 4273 |
def cancel(self): pass |
| 4274 |
|
| 4275 |
|
| 4276 |
class Unstoppable(HarlequinAdapter): |
| 4277 |
ADAPTER_OPTIONS = None |
| 4278 |
IMPLEMENTS_CANCEL = True |
| 4279 |
def __init__(self, conn_str, **options): pass |
| 4280 |
def connect(self): return Connection() |
| 4281 |
|
| 4282 |
|
| 4283 |
entry_point = MagicMock() |
| 4284 |
entry_point.name = "unstoppable" |
| 4285 |
entry_point.load.return_value = Unstoppable |
| 4286 |
harlequin.plugins.entry_points = lambda group: [entry_point] |
| 4287 |
|
| 4288 |
sys.argv = ["hsql", "-a", "unstoppable", "--timeout", "0.2", "-c", "select 1"] |
| 4289 |
from harlequin.hsql import main |
| 4290 |
main() |
| 4291 |
""" |
| 4292 |
"""An adapter that declares it can cancel and then does not stop.""" |
| 4293 |
|
| 4294 |
|
| 4295 |
def test_a_run_that_outlasts_the_grace_period_still_exits_4( |
| 4296 |
tmp_path: Path, clean_env: dict[str, str] |
| 4297 |
) -> None: |
| 4298 |
"""`sys.exit()` around a thread still inside a driver aborts the interpreter |
| 4299 |
and exits 134, which is not a code hsql documents -- so the grace period |
| 4300 |
ends in `os._exit()` instead. Only a real subprocess can show the code. |
| 4301 |
""" |
| 4302 |
proc = subprocess.run( |
| 4303 |
[sys.executable, "-c", UNSTOPPABLE], |
| 4304 |
stdout=subprocess.PIPE, |
| 4305 |
stderr=subprocess.PIPE, |
| 4306 |
text=True, |
| 4307 |
timeout=60, |
| 4308 |
cwd=tmp_path, # out of the repo, whose own .harlequin.toml would apply |
| 4309 |
env=clean_env, |
| 4310 |
) |
| 4311 |
assert proc.returncode == ExitCode.TIMEOUT, proc.stderr |
| 4312 |
assert proc.stdout == "" |
| 4313 |
assert "timed out after 0.2s" in proc.stderr |
| 4314 |
|
| 4315 |
|
| 4316 |
def test_timeout_is_hsqls_where_an_adapter_declares_the_spelling(hsql: Hsql) -> None: |
| 4317 |
"""SQLite's own `timeout` is how long to wait for a locked table, and hsql's |
| 4318 |
own flags are the frozen part -- so `--timeout` here is the deadline, and |
| 4319 |
the adapter's is `--lock-timeout`.""" |
| 4320 |
res = hsql( |
| 4321 |
"-a", |
| 4322 |
"sqlite", |
| 4323 |
":memory:", |
| 4324 |
"--timeout", |
| 4325 |
"60", |
| 4326 |
"--lock-timeout", |
| 4327 |
"1", |
| 4328 |
"-tAc", |
| 4329 |
"select 1", |
| 4330 |
) |
| 4331 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 4332 |
assert res.stdout == "1\n" |
| 4333 |
|
| 4334 |
|
| 4335 |
def test_a_timed_out_script_does_not_report_a_missing_result_set( |
| 4336 |
hsql: Hsql, stuck_adapter: list[_StuckConnection] |
| 4337 |
) -> None: |
| 4338 |
"""A cancelled script produced fewer result sets than it was going to, and |
| 4339 |
the deadline is what a caller has to hear about rather than the count.""" |
| 4340 |
res = hsql( |
| 4341 |
"-a", "stuck", "--timeout", "0.1", "--result", "2", "-c", "select 1; select 2" |
| 4342 |
) |
| 4343 |
assert res.exit_code == ExitCode.TIMEOUT |
| 4344 |
assert "timed out after 0.1s" in res.stderr |
| 4345 |
assert "result sets" not in res.stderr |
| 4346 |
|
| 4347 |
|
| 4348 |
def test_a_real_duckdb_query_times_out_and_says_so( |
| 4349 |
tmp_path: Path, clean_env: dict[str, str] |
| 4350 |
) -> None: |
| 4351 |
"""The fakes above pin the attribution; this pins the interrupt itself. |
| 4352 |
|
| 4353 |
A subprocess because it is the only place the exit code is real: an |
| 4354 |
aggregate over fifty billion rows is one every machine is still working on |
| 4355 |
a second in. |
| 4356 |
""" |
| 4357 |
proc = subprocess.run( |
| 4358 |
[ |
| 4359 |
sys.executable, |
| 4360 |
"-c", |
| 4361 |
"import sys; from harlequin.hsql import main; sys.argv = sys.argv[1:]; " |
| 4362 |
"main()", |
| 4363 |
"hsql", |
| 4364 |
*["-a", "duckdb", "--no-init", ":memory:"], |
| 4365 |
*["--timeout", "1", "-c", "select sum(i) from range(50000000000) t(i)"], |
| 4366 |
], |
| 4367 |
stdout=subprocess.PIPE, |
| 4368 |
stderr=subprocess.PIPE, |
| 4369 |
text=True, |
| 4370 |
timeout=120, |
| 4371 |
cwd=tmp_path, # out of the repo, whose own .harlequin.toml would apply |
| 4372 |
env=clean_env, |
| 4373 |
) |
| 4374 |
assert proc.returncode == ExitCode.TIMEOUT, proc.stderr |
| 4375 |
# the empty result set a cancelled DuckDB cursor returns, not printed |
| 4376 |
assert proc.stdout == "" |
| 4377 |
assert "timed out after 1s" in proc.stderr |
| 4378 |
|
| 4379 |
|
| 4380 |
# --- a bug in hsql itself ---------------------------------------------------- |
| 4381 |
|
| 4382 |
|
| 4383 |
def run_main(monkeypatch: pytest.MonkeyPatch, *argv: str) -> int: |
| 4384 |
"""Call the console script's entry point, which is where crashes are caught.""" |
| 4385 |
from harlequin.hsql import main |
| 4386 |
|
| 4387 |
monkeypatch.setattr(sys, "argv", ["hsql", *argv]) |
| 4388 |
with pytest.raises(SystemExit) as exit_info: |
| 4389 |
main() |
| 4390 |
return cast(int, exit_info.value.code) |
| 4391 |
|
| 4392 |
|
| 4393 |
@pytest.fixture |
| 4394 |
def hsql_crashes(monkeypatch: pytest.MonkeyPatch) -> None: |
| 4395 |
"""A bug in hsql, before anything it runs has had a chance to catch it.""" |
| 4396 |
|
| 4397 |
def _boom(*_args: object, **_kwargs: object) -> None: |
| 4398 |
raise RuntimeError("a bug in hsql") |
| 4399 |
|
| 4400 |
monkeypatch.setattr("harlequin.hsql.cli.build_cli", _boom) |
| 4401 |
|
| 4402 |
|
| 4403 |
def test_a_bug_in_hsql_is_not_reported_as_a_failed_query( |
| 4404 |
monkeypatch: pytest.MonkeyPatch, |
| 4405 |
hsql_crashes: None, |
| 4406 |
crash_reports_go_to_tmp: Path, |
| 4407 |
capsys: pytest.CaptureFixture[str], |
| 4408 |
) -> None: |
| 4409 |
"""1 is what a database rejecting the SQL means. A caller scripting against |
| 4410 |
these could not otherwise tell the two apart.""" |
| 4411 |
code = run_main(monkeypatch, "-c", "select 1") |
| 4412 |
|
| 4413 |
assert code == ExitCode.CRASH |
| 4414 |
assert code != ExitCode.QUERY |
| 4415 |
|
| 4416 |
(report,) = list(crash_reports_go_to_tmp.glob("crash-*.log")) |
| 4417 |
assert "a bug in hsql" in report.read_text() |
| 4418 |
|
| 4419 |
stderr = capsys.readouterr().err |
| 4420 |
assert "hsql hit a bug in itself" in stderr |
| 4421 |
assert "please report this crash to help improve Harlequin" in stderr |
| 4422 |
# the ask comes before the file it needs, and neither is called a review |
| 4423 |
assert stderr.index(ISSUE_URL) < stderr.index(str(report)) |
| 4424 |
assert "review" not in stderr.lower() |
| 4425 |
|
| 4426 |
|
| 4427 |
def test_a_crash_report_masks_a_dsn_typed_on_the_command_line( |
| 4428 |
monkeypatch: pytest.MonkeyPatch, |
| 4429 |
hsql_crashes: None, |
| 4430 |
crash_reports_go_to_tmp: Path, |
| 4431 |
) -> None: |
| 4432 |
"""A crash during parsing happens before `hide_secrets_in()` runs, so the |
| 4433 |
span-masking is the only thing that catches it.""" |
| 4434 |
run_main(monkeypatch, "postgres://tco:hunter2-and-more@warehouse:5432/analytics") |
| 4435 |
|
| 4436 |
(report,) = list(crash_reports_go_to_tmp.glob("crash-*.log")) |
| 4437 |
text = report.read_text() |
| 4438 |
assert "hunter2-and-more" not in text |
| 4439 |
# and the rest of the DSN survives, which is what makes the argv worth having |
| 4440 |
assert "warehouse:5432/analytics" in text |
| 4441 |
|
| 4442 |
|
| 4443 |
def test_a_crash_report_masks_a_credential_typed_into_the_query( |
| 4444 |
monkeypatch: pytest.MonkeyPatch, |
| 4445 |
hsql_crashes: None, |
| 4446 |
crash_reports_go_to_tmp: Path, |
| 4447 |
) -> None: |
| 4448 |
"""The argv holds the statement `-c` was given, and a statement can carry a |
| 4449 |
credential that no option describes and no caller registered.""" |
| 4450 |
run_main( |
| 4451 |
monkeypatch, "-c", "create secret (type s3, secret 'sEcReT-value'); select 1" |
| 4452 |
) |
| 4453 |
|
| 4454 |
(report,) = list(crash_reports_go_to_tmp.glob("crash-*.log")) |
| 4455 |
text = report.read_text() |
| 4456 |
assert "sEcReT-value" not in text |
| 4457 |
# and the rest of the statement survives |
| 4458 |
assert "create secret (type s3" in text |
| 4459 |
|
| 4460 |
|
| 4461 |
def test_a_crash_report_that_cannot_be_written_still_exits_70( |
| 4462 |
monkeypatch: pytest.MonkeyPatch, |
| 4463 |
hsql_crashes: None, |
| 4464 |
capsys: pytest.CaptureFixture[str], |
| 4465 |
) -> None: |
| 4466 |
def _raise(*_args: object, **_kwargs: object) -> None: |
| 4467 |
raise OSError("the log dir is gone") |
| 4468 |
|
| 4469 |
monkeypatch.setattr("harlequin.crash.write_crash_report", _raise) |
| 4470 |
|
| 4471 |
assert run_main(monkeypatch, "-c", "select 1") == ExitCode.CRASH |
| 4472 |
assert "hsql hit a bug in itself" in capsys.readouterr().err |
| 4473 |
|
| 4474 |
|
| 4475 |
def test_an_interrupt_is_not_a_crash(monkeypatch: pytest.MonkeyPatch) -> None: |
| 4476 |
def _interrupt(*_args: object, **_kwargs: object) -> None: |
| 4477 |
raise KeyboardInterrupt |
| 4478 |
|
| 4479 |
monkeypatch.setattr("harlequin.hsql.cli.build_cli", _interrupt) |
| 4480 |
|
| 4481 |
assert run_main(monkeypatch, "-c", "select 1") == ExitCode.INTERRUPT |
| 4482 |
|
| 4483 |
|
| 4484 |
def test_a_bug_in_the_session_client_is_a_crash_too( |
| 4485 |
monkeypatch: pytest.MonkeyPatch, |
| 4486 |
crash_reports_go_to_tmp: Path, |
| 4487 |
capsys: pytest.CaptureFixture[str], |
| 4488 |
) -> None: |
| 4489 |
"""The warm path is hsql's too, so a bug in it exits 70 rather than 1.""" |
| 4490 |
|
| 4491 |
def _boom(*_args: object, **_kwargs: object) -> None: |
| 4492 |
raise RuntimeError("a bug in the client") |
| 4493 |
|
| 4494 |
monkeypatch.setattr("harlequin.hsql.session.requested_session", _boom) |
| 4495 |
|
| 4496 |
assert ( |
| 4497 |
run_main(monkeypatch, "--session", "warm", "-c", "select 1") == ExitCode.CRASH |
| 4498 |
) |
| 4499 |
|
| 4500 |
(report,) = list(crash_reports_go_to_tmp.glob("crash-*.log")) |
| 4501 |
assert "a bug in the client" in report.read_text() |
| 4502 |
assert "hsql hit a bug in itself" in capsys.readouterr().err |
| 4503 |
|
| 4504 |
|
| 4505 |
# --- the query log ----------------------------------------------------------- |
| 4506 |
|
| 4507 |
|
| 4508 |
def logged(store: Path) -> list[dict[str, Any]]: |
| 4509 |
"""Every row hsql wrote, oldest first.""" |
| 4510 |
db = sqlite3.connect(store) |
| 4511 |
db.row_factory = sqlite3.Row |
| 4512 |
try: |
| 4513 |
return [dict(row) for row in db.execute("select * from queries order by id")] |
| 4514 |
finally: |
| 4515 |
db.close() |
| 4516 |
|
| 4517 |
|
| 4518 |
def test_a_run_records_every_statement( |
| 4519 |
hsql: Hsql, duck: list[str], query_log_path: Path |
| 4520 |
) -> None: |
| 4521 |
res = hsql(*duck, "-c", "create table t (a int); select 1 as a; select nope") |
| 4522 |
assert res.exit_code == ExitCode.QUERY |
| 4523 |
recorded = logged(query_log_path) |
| 4524 |
assert [row["sql"] for row in recorded] == [ |
| 4525 |
"create table t (a int);", |
| 4526 |
"select 1 as a;", |
| 4527 |
"select nope", |
| 4528 |
] |
| 4529 |
assert [row["status"] for row in recorded] == ["ok", "ok", "error"] |
| 4530 |
assert [row["program"] for row in recorded] == ["hsql"] * 3 |
| 4531 |
assert recorded[1]["rows"] == 1 |
| 4532 |
assert recorded[2]["error"] |
| 4533 |
# one connection, one id, whatever the statement did |
| 4534 |
assert len({row["connection"] for row in recorded}) == 1 |
| 4535 |
|
| 4536 |
|
| 4537 |
def test_a_truncated_result_is_recorded_as_truncated( |
| 4538 |
hsql: Hsql, duck: list[str], query_log_path: Path |
| 4539 |
) -> None: |
| 4540 |
res = hsql(*duck, "--limit", "3", "-c", TEN_ROWS) |
| 4541 |
assert res.exit_code == ExitCode.OK |
| 4542 |
(row,) = logged(query_log_path) |
| 4543 |
assert (row["rows"], row["truncated"]) == (3, 1) |
| 4544 |
|
| 4545 |
|
| 4546 |
def test_a_statement_whose_rows_were_never_fetched_is_still_recorded( |
| 4547 |
hsql: Hsql, duck: list[str], query_log_path: Path |
| 4548 |
) -> None: |
| 4549 |
"""`--result last` declines to pay for the rest; they still ran.""" |
| 4550 |
res = hsql(*duck, "--result", "last", "-c", "select 1; select 2") |
| 4551 |
assert res.exit_code == ExitCode.OK |
| 4552 |
first, second = logged(query_log_path) |
| 4553 |
assert (first["status"], first["rows"]) == ("ok", None) |
| 4554 |
assert (second["status"], second["rows"]) == ("ok", 1) |
| 4555 |
|
| 4556 |
|
| 4557 |
def test_a_run_can_be_told_not_to_record_itself( |
| 4558 |
hsql: Hsql, duck: list[str], query_log_path: Path |
| 4559 |
) -> None: |
| 4560 |
res = hsql(*duck, "--no-write-history", "-c", "select 1") |
| 4561 |
assert res.exit_code == ExitCode.OK |
| 4562 |
assert not query_log_path.exists() |
| 4563 |
|
| 4564 |
|
| 4565 |
def test_a_profile_can_turn_the_log_off( |
| 4566 |
hsql: Hsql, tmp_path: Path, query_log_path: Path |
| 4567 |
) -> None: |
| 4568 |
config = tmp_path / ".harlequin.toml" |
| 4569 |
config.write_text( |
| 4570 |
"[profiles.quiet]\n" |
| 4571 |
"adapter = 'duckdb'\n" |
| 4572 |
"conn_str = [ ':memory:' ]\n" |
| 4573 |
"no_init = true\n" |
| 4574 |
"no_write_history = true\n" |
| 4575 |
) |
| 4576 |
res = hsql("--config-path", str(config), "-P", "quiet", "-c", "select 1") |
| 4577 |
assert res.exit_code == ExitCode.OK |
| 4578 |
assert not query_log_path.exists() |
| 4579 |
|
| 4580 |
|
| 4581 |
def test_a_profile_that_says_nothing_records_the_run( |
| 4582 |
hsql: Hsql, tmp_path: Path, query_log_path: Path |
| 4583 |
) -> None: |
| 4584 |
"""The flag only turns recording off: leaving it out is the default.""" |
| 4585 |
config = tmp_path / ".harlequin.toml" |
| 4586 |
config.write_text( |
| 4587 |
"[profiles.loud]\n" |
| 4588 |
"adapter = 'duckdb'\n" |
| 4589 |
"conn_str = [ ':memory:' ]\n" |
| 4590 |
"no_init = true\n" |
| 4591 |
) |
| 4592 |
res = hsql("--config-path", str(config), "-P", "loud", "-c", "select 1") |
| 4593 |
assert res.exit_code == ExitCode.OK |
| 4594 |
assert len(logged(query_log_path)) == 1 |
| 4595 |
|
| 4596 |
|
| 4597 |
def test_no_write_history_that_is_not_a_boolean_is_a_usage_error( |
| 4598 |
hsql: Hsql, tmp_path: Path |
| 4599 |
) -> None: |
| 4600 |
"""`no_write_history = "false"` read as true is a wrong a user cannot see.""" |
| 4601 |
config = tmp_path / ".harlequin.toml" |
| 4602 |
config.write_text( |
| 4603 |
"[profiles.odd]\n" |
| 4604 |
"adapter = 'duckdb'\n" |
| 4605 |
"conn_str = [ ':memory:' ]\n" |
| 4606 |
"no_write_history = 'sometimes'\n" |
| 4607 |
) |
| 4608 |
res = hsql("--config-path", str(config), "-P", "odd", "-c", "select 1") |
| 4609 |
assert res.exit_code == ExitCode.USAGE |
| 4610 |
assert "no_write_history=" in res.stderr |
| 4611 |
|
| 4612 |
|
| 4613 |
def test_a_log_that_cannot_be_written_does_not_fail_the_query( |
| 4614 |
hsql: Hsql, duck: list[str], tmp_path: Path, monkeypatch: pytest.MonkeyPatch |
| 4615 |
) -> None: |
| 4616 |
"""Said once on stderr, because stdout belongs to the query's output.""" |
| 4617 |
blocked = tmp_path / "not-a-directory" |
| 4618 |
blocked.write_text("") |
| 4619 |
monkeypatch.setattr( |
| 4620 |
"harlequin.query_log.default_path", lambda: blocked / "history.db" |
| 4621 |
) |
| 4622 |
res = hsql(*duck, "-tA", "-c", "select 1") |
| 4623 |
assert res.exit_code == ExitCode.OK |
| 4624 |
assert res.stdout == "1\n" |
| 4625 |
assert "query log" in res.stderr |
| 4626 |
|
| 4627 |
|
| 4628 |
def test_a_secret_never_reaches_the_query_log( |
| 4629 |
hsql: Hsql, tmp_path: Path, query_log_path: Path |
| 4630 |
) -> None: |
| 4631 |
"""A profile's declared secret is masked in the SQL that mentions it.""" |
| 4632 |
config = tmp_path / ".harlequin.toml" |
| 4633 |
config.write_text( |
| 4634 |
"[profiles.duck]\n" |
| 4635 |
"adapter = 'duckdb'\n" |
| 4636 |
"conn_str = [ ':memory:' ]\n" |
| 4637 |
"no_init = true\n" |
| 4638 |
"md_token = 'hunter2-and-then-some'\n" |
| 4639 |
) |
| 4640 |
res = hsql( |
| 4641 |
"--config-path", |
| 4642 |
str(config), |
| 4643 |
"-P", |
| 4644 |
"duck", |
| 4645 |
"-c", |
| 4646 |
"select 'hunter2-and-then-some' as a", |
| 4647 |
) |
| 4648 |
assert res.exit_code == ExitCode.OK |
| 4649 |
(row,) = logged(query_log_path) |
| 4650 |
assert "hunter2-and-then-some" not in row["sql"] |
| 4651 |
|
| 4652 |
|
| 4653 |
def _timed_out_run( |
| 4654 |
args: Sequence[str], *, clean_env: dict[str, str], tmp_path: Path |
| 4655 |
) -> tuple[subprocess.CompletedProcess[str], list[dict[str, Any]]]: |
| 4656 |
"""Run hsql in a child and read back what it recorded. |
| 4657 |
|
| 4658 |
A child because a run that will not stop within the grace period ends in |
| 4659 |
`os._exit()`, which in process would take the xdist worker with it. |
| 4660 |
""" |
| 4661 |
proc = subprocess.run( |
| 4662 |
[ |
| 4663 |
sys.executable, |
| 4664 |
"-c", |
| 4665 |
"import sys; from harlequin.hsql import main; sys.argv = sys.argv[1:]; " |
| 4666 |
"main()", |
| 4667 |
"hsql", |
| 4668 |
*args, |
| 4669 |
], |
| 4670 |
stdout=subprocess.PIPE, |
| 4671 |
stderr=subprocess.PIPE, |
| 4672 |
text=True, |
| 4673 |
timeout=120, |
| 4674 |
cwd=tmp_path, |
| 4675 |
env=clean_env, |
| 4676 |
) |
| 4677 |
# wherever platformdirs put it on this platform; `clean_env` keeps it here |
| 4678 |
(store,) = tmp_path.rglob("history.db") |
| 4679 |
return proc, logged(store) |
| 4680 |
|
| 4681 |
|
| 4682 |
def test_a_statement_cancelled_while_it_runs_is_still_recorded( |
| 4683 |
tmp_path: Path, clean_env: dict[str, str] |
| 4684 |
) -> None: |
| 4685 |
"""SQLite steps the query inside `execute()`, so the timeout lands there. |
| 4686 |
|
| 4687 |
A lazy adapter is cancelled in the fetch instead; the row has to exist |
| 4688 |
either way, or the history depends on which driver ran the query. |
| 4689 |
|
| 4690 |
What became of it is `test_every_statement_a_cancel_stopped_says_so`'s to |
| 4691 |
assert. Not this test's, because a cancel that reaches the connection |
| 4692 |
before the statement is stepping does not stop it: the run is then halted |
| 4693 |
around the thread rather than unwinding, and leaves the row a `kill -9` |
| 4694 |
would -- recorded, with no outcome. |
| 4695 |
""" |
| 4696 |
proc, recorded = _timed_out_run( |
| 4697 |
[ |
| 4698 |
*["-a", "sqlite", ":memory:"], |
| 4699 |
*["--timeout", "0.3"], |
| 4700 |
"-c", |
| 4701 |
"with recursive t(n) as (select 1 union all select n + 1 from t) " |
| 4702 |
"select count(*) from t", |
| 4703 |
], |
| 4704 |
clean_env=clean_env, |
| 4705 |
tmp_path=tmp_path, |
| 4706 |
) |
| 4707 |
assert proc.returncode == ExitCode.TIMEOUT, proc.stderr |
| 4708 |
(row,) = recorded |
| 4709 |
assert row["sql"].startswith("with recursive t(n)") |
| 4710 |
# it never produced one, however the run ended |
| 4711 |
assert row["rows"] is None |
| 4712 |
assert row["elapsed_ms"] is None |
| 4713 |
|
| 4714 |
|
| 4715 |
def test_every_statement_a_cancel_stopped_says_so( |
| 4716 |
tmp_path: Path, clean_env: dict[str, str] |
| 4717 |
) -> None: |
| 4718 |
"""Not just the one in flight: nothing after it was fetched either. |
| 4719 |
|
| 4720 |
The slow statement is in the middle, so a fix that marks only the statement |
| 4721 |
the clock caught leaves the last one `ok` with no rows -- which is what |
| 4722 |
`--result last` looks like. |
| 4723 |
|
| 4724 |
Generous rather than the tightest deadline that would do, because what it |
| 4725 |
has to outlast is a loaded runner opening duckdb and running `select 1`: |
| 4726 |
a clock that expires before the slow statement is running cancels a |
| 4727 |
connection that is not running one, and nothing then stops it. The run |
| 4728 |
ends in `os._exit()` at the grace period instead, having recorded only |
| 4729 |
what it reached -- which is `assert 1 == 3`, not a fix to make here. |
| 4730 |
""" |
| 4731 |
proc, recorded = _timed_out_run( |
| 4732 |
[ |
| 4733 |
*["-a", "duckdb", "--no-init", ":memory:"], |
| 4734 |
*["--timeout", "5"], |
| 4735 |
"-c", |
| 4736 |
"select 1; select sum(i) from range(50000000000) t(i); select 2", |
| 4737 |
], |
| 4738 |
clean_env=clean_env, |
| 4739 |
tmp_path=tmp_path, |
| 4740 |
) |
| 4741 |
assert proc.returncode == ExitCode.TIMEOUT, proc.stderr |
| 4742 |
assert len(recorded) == 3 |
| 4743 |
assert [row["status"] for row in recorded] == ["ok", "canceled", "canceled"] |
| 4744 |
# the one that did finish keeps what it returned |
| 4745 |
assert recorded[0]["rows"] == 1 |
| 4746 |
|
| 4747 |
|
| 4748 |
def test_the_two_commands_key_one_connection_the_same_way( |
| 4749 |
hsql: Hsql, tmp_path: Path, query_log_path: Path, monkeypatch: pytest.MonkeyPatch |
| 4750 |
) -> None: |
| 4751 |
"""One store with two writers is only one history if the ids agree. |
| 4752 |
|
| 4753 |
Against an adapter that declares no `connection_id`, which is the ABC's |
| 4754 |
default and so the case that actually hashes: a profile that sets hsql's |
| 4755 |
own keys, and a `-c` typed on the command line, must not move the id the |
| 4756 |
IDE derives from the same profile. |
| 4757 |
""" |
| 4758 |
from harlequin_duckdb import DuckDbAdapter |
| 4759 |
|
| 4760 |
# the property, replaced by the None every adapter that does not override |
| 4761 |
# it returns -- which is what sends both commands through the hash |
| 4762 |
monkeypatch.setattr(DuckDbAdapter, "connection_id", None) |
| 4763 |
|
| 4764 |
config = tmp_path / ".harlequin.toml" |
| 4765 |
config.write_text( |
| 4766 |
"[profiles.shared]\n" |
| 4767 |
"adapter = 'duckdb'\n" |
| 4768 |
"conn_str = [ ':memory:' ]\n" |
| 4769 |
"no_init = true\n" |
| 4770 |
"limit = 5\n" |
| 4771 |
"format = 'csv'\n" |
| 4772 |
"theme = 'fruity'\n" |
| 4773 |
"no_download_tzdata = true\n" |
| 4774 |
"no_write_history = false\n" |
| 4775 |
) |
| 4776 |
res = hsql("--config-path", str(config), "-P", "shared", "-c", "select 1") |
| 4777 |
assert res.exit_code == ExitCode.OK |
| 4778 |
(row,) = logged(query_log_path) |
| 4779 |
assert row["connection"], "an unset id would make this test vacuous" |
| 4780 |
|
| 4781 |
app = MagicMock() |
| 4782 |
# the command exits with it, and a MagicMock is not an exit code |
| 4783 |
app.return_value.return_code = 0 |
| 4784 |
monkeypatch.setattr("harlequin.cli.Harlequin", app) |
| 4785 |
from harlequin.cli import build_cli as ide_cli |
| 4786 |
|
| 4787 |
argv = ["--config-path", str(config), "-P", "shared"] |
| 4788 |
ide = CliRunner().invoke(ide_cli(argv), argv, catch_exceptions=False) |
| 4789 |
assert ide.exit_code == 0 |
| 4790 |
assert app.call_args.kwargs["connection_hash"] == row["connection"] |
| 4791 |
|
| 4792 |
|
| 4793 |
def test_the_sql_to_run_is_not_part_of_the_connections_id( |
| 4794 |
hsql: Hsql, query_log_path: Path, monkeypatch: pytest.MonkeyPatch |
| 4795 |
) -> None: |
| 4796 |
"""Two queries against one database are one connection, not two.""" |
| 4797 |
from harlequin_duckdb import DuckDbAdapter |
| 4798 |
|
| 4799 |
monkeypatch.setattr(DuckDbAdapter, "connection_id", None) |
| 4800 |
|
| 4801 |
for sql in ("select 1", "select 2"): |
| 4802 |
assert hsql("-a", "duckdb", "--no-init", ":memory:", "-c", sql).exit_code == ( |
| 4803 |
ExitCode.OK |
| 4804 |
) |
| 4805 |
first, second = logged(query_log_path) |
| 4806 |
assert first["connection"] == second["connection"] |
| 4807 |
|
| 4808 |
|
| 4809 |
# --- `--history`, the two modes that read the query log ---------------------- |
| 4810 |
|
| 4811 |
|
| 4812 |
@pytest.fixture |
| 4813 |
def two_databases( |
| 4814 |
hsql: Hsql, tmp_path: Path, query_log_path: Path |
| 4815 |
) -> tuple[list[str], list[str]]: |
| 4816 |
"""Two DuckDB files, with three queries between them, interleaved.""" |
| 4817 |
first = ["-a", "duckdb", "--no-init", str(tmp_path / "first.db")] |
| 4818 |
second = ["-a", "duckdb", "--no-init", str(tmp_path / "second.db")] |
| 4819 |
for argv, sql in ( |
| 4820 |
(first, "select 1 as one"), |
| 4821 |
(second, "select 2 as two"), |
| 4822 |
(first, "select 3 as three"), |
| 4823 |
): |
| 4824 |
res = hsql(*argv, "--format", "none", "-c", sql) |
| 4825 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 4826 |
return first, second |
| 4827 |
|
| 4828 |
|
| 4829 |
def sql_column(stdout: str) -> list[str]: |
| 4830 |
"""The `sql` cell of every row of a `-tA` listing, which is the last one.""" |
| 4831 |
return [row.split("|")[-1] for row in stdout.splitlines()] |
| 4832 |
|
| 4833 |
|
| 4834 |
def test_history_reports_every_connection_newest_first( |
| 4835 |
hsql: Hsql, two_databases: tuple[list[str], list[str]] |
| 4836 |
) -> None: |
| 4837 |
"""With no database named, the answer is every database this machine used: |
| 4838 |
the alternative is a listing of whichever one the command defaults to.""" |
| 4839 |
res = hsql("--history", "-tA") |
| 4840 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 4841 |
assert sql_column(res.stdout) == [ |
| 4842 |
"select 3 as three", |
| 4843 |
"select 2 as two", |
| 4844 |
"select 1 as one", |
| 4845 |
] |
| 4846 |
|
| 4847 |
|
| 4848 |
def test_history_narrows_to_the_database_the_invocation_names( |
| 4849 |
hsql: Hsql, two_databases: tuple[list[str], list[str]] |
| 4850 |
) -> None: |
| 4851 |
first, second = two_databases |
| 4852 |
res = hsql(*first, "--history", "-tA") |
| 4853 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 4854 |
assert sql_column(res.stdout) == ["select 3 as three", "select 1 as one"] |
| 4855 |
|
| 4856 |
res = hsql(*second, "--history", "-tA") |
| 4857 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 4858 |
assert sql_column(res.stdout) == ["select 2 as two"] |
| 4859 |
|
| 4860 |
|
| 4861 |
def test_history_narrows_to_the_profile_the_invocation_names( |
| 4862 |
hsql: Hsql, two_databases: tuple[list[str], list[str]], tmp_path: Path |
| 4863 |
) -> None: |
| 4864 |
"""A profile names a database as surely as a CONN_STR does.""" |
| 4865 |
first, _ = two_databases |
| 4866 |
config_file = tmp_path / "profile.toml" |
| 4867 |
config_file.write_text( |
| 4868 |
'[profiles.first]\nadapter = "duckdb"\n' |
| 4869 |
f"conn_str = [{json.dumps(first[-1])}]\nno_init = true\n" |
| 4870 |
) |
| 4871 |
res = hsql("--config-path", str(config_file), "-P", "first", "--history", "-tA") |
| 4872 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 4873 |
assert sql_column(res.stdout) == ["select 3 as three", "select 1 as one"] |
| 4874 |
|
| 4875 |
|
| 4876 |
def test_history_opens_no_database_but_the_store( |
| 4877 |
hsql: Hsql, tmp_path: Path, query_log_path: Path |
| 4878 |
) -> None: |
| 4879 |
"""The adapter is built to name a connection, never to make one: a path |
| 4880 |
that would exit 3 for a query is a listing of no rows here.""" |
| 4881 |
missing = str(tmp_path / "nowhere" / "absent.db") |
| 4882 |
assert hsql("-a", "duckdb", "--no-init", missing, "-c", "select 1").exit_code == ( |
| 4883 |
ExitCode.CONNECTION |
| 4884 |
) |
| 4885 |
res = hsql("-a", "duckdb", "--no-init", missing, "--history", "-tA") |
| 4886 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 4887 |
assert res.stdout == "" |
| 4888 |
|
| 4889 |
|
| 4890 |
def test_history_limit_takes_from_the_newest_end( |
| 4891 |
hsql: Hsql, two_databases: tuple[list[str], list[str]] |
| 4892 |
) -> None: |
| 4893 |
res = hsql("--history", "--limit", "1", "-tA") |
| 4894 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 4895 |
assert sql_column(res.stdout) == ["select 3 as three"] |
| 4896 |
|
| 4897 |
|
| 4898 |
def test_history_limit_says_there_was_more( |
| 4899 |
hsql: Hsql, two_databases: tuple[list[str], list[str]] |
| 4900 |
) -> None: |
| 4901 |
"""The store has a row count, so a limit on it is a hard limit like any |
| 4902 |
other -- and one row more than it keeps is what proves there was a fourth.""" |
| 4903 |
res = hsql("--history", "--limit", "2") |
| 4904 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 4905 |
assert res.stdout.strip().endswith("(2 of >2 rows)") |
| 4906 |
|
| 4907 |
|
| 4908 |
def test_history_limit_of_minus_one_is_every_row( |
| 4909 |
hsql: Hsql, two_databases: tuple[list[str], list[str]] |
| 4910 |
) -> None: |
| 4911 |
res = hsql("--history", "--limit", "-1", "-tA") |
| 4912 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 4913 |
assert len(sql_column(res.stdout)) == 3 |
| 4914 |
|
| 4915 |
|
| 4916 |
def test_history_reports_what_the_ide_ran_too( |
| 4917 |
hsql: Hsql, two_databases: tuple[list[str], list[str]], query_log_path: Path |
| 4918 |
) -> None: |
| 4919 |
"""One store, two writers: an agent joining a task mid-stream reads the |
| 4920 |
queries the human has been running, and the human reads the agent's.""" |
| 4921 |
from harlequin.query_log import QueryLog |
| 4922 |
|
| 4923 |
log = QueryLog(program="harlequin", path=query_log_path) |
| 4924 |
log.write("select 4 as four") |
| 4925 |
log.close() |
| 4926 |
|
| 4927 |
res = hsql("--history", "--limit", "1", "-tA") |
| 4928 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 4929 |
(row,) = cells(res.stdout) |
| 4930 |
assert (row[1], row[-1]) == ("harlequin", "select 4 as four") |
| 4931 |
|
| 4932 |
|
| 4933 |
def test_history_records_nothing_of_its_own( |
| 4934 |
hsql: Hsql, two_databases: tuple[list[str], list[str]], query_log_path: Path |
| 4935 |
) -> None: |
| 4936 |
"""Reading a history that listed the reads of it would be a history of |
| 4937 |
itself within a week.""" |
| 4938 |
before = len(logged(query_log_path)) |
| 4939 |
assert hsql("--history", "--format", "none").exit_code == ExitCode.OK |
| 4940 |
assert len(logged(query_log_path)) == before |
| 4941 |
|
| 4942 |
|
| 4943 |
def test_history_on_a_machine_that_has_run_nothing_is_an_empty_table( |
| 4944 |
hsql: Hsql, query_log_path: Path |
| 4945 |
) -> None: |
| 4946 |
"""And it does not create the store: a reader that wrote could fail.""" |
| 4947 |
res = hsql("--history") |
| 4948 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 4949 |
assert res.stdout.splitlines()[0].split("|")[0].strip() == "run_at" |
| 4950 |
assert res.stdout.strip().endswith("(0 rows)") |
| 4951 |
assert not query_log_path.exists() |
| 4952 |
|
| 4953 |
|
| 4954 |
def test_history_keeps_the_types_the_store_gave_it( |
| 4955 |
hsql: Hsql, two_databases: tuple[list[str], list[str]] |
| 4956 |
) -> None: |
| 4957 |
"""A count an agent can sum, rather than a string it has to parse back.""" |
| 4958 |
res = hsql("--history", "--limit", "1", "--json") |
| 4959 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 4960 |
(record,) = json.loads(res.stdout) |
| 4961 |
assert record["rows"] == 1 |
| 4962 |
assert isinstance(record["rows"], int) |
| 4963 |
assert isinstance(record["elapsed_ms"], float) |
| 4964 |
|
| 4965 |
|
| 4966 |
def test_history_reports_the_query_exactly_as_it_ran( |
| 4967 |
hsql: Hsql, duck: list[str], query_log_path: Path |
| 4968 |
) -> None: |
| 4969 |
"""The store holds what ran, and the listing hands it back: a comment still |
| 4970 |
only comments out its own line, and a literal keeps its own spacing.""" |
| 4971 |
sql = "select\n 1 as a, -- the first column\n 'hello world' as b" |
| 4972 |
written = hsql(*duck, "--format", "none", "-c", sql) |
| 4973 |
assert written.exit_code == ExitCode.OK, written.stderr |
| 4974 |
|
| 4975 |
listed = hsql("--history", "--json") |
| 4976 |
assert listed.exit_code == ExitCode.OK, listed.stderr |
| 4977 |
(record,) = json.loads(listed.stdout) |
| 4978 |
assert record["sql"] == sql |
| 4979 |
|
| 4980 |
# and it runs, which is what reporting it exactly is for |
| 4981 |
ran = hsql(*duck, "-tA", "-c", record["sql"]) |
| 4982 |
assert ran.exit_code == ExitCode.OK, ran.stderr |
| 4983 |
assert ran.stdout == "1|hello world\n" |
| 4984 |
|
| 4985 |
|
| 4986 |
def test_history_carries_the_same_sql_in_every_format( |
| 4987 |
hsql: Hsql, duck: list[str], query_log_path: Path |
| 4988 |
) -> None: |
| 4989 |
"""The layouts wrap it and csv quotes it; neither changes the value.""" |
| 4990 |
sql = "select\n 1 as a" |
| 4991 |
written = hsql(*duck, "--format", "none", "-c", sql) |
| 4992 |
assert written.exit_code == ExitCode.OK, written.stderr |
| 4993 |
|
| 4994 |
from_csv = hsql("--history", "--csv", "--no-header") |
| 4995 |
assert from_csv.exit_code == ExitCode.OK, from_csv.stderr |
| 4996 |
# the whole stream, not its lines: a quoted field holds the newlines |
| 4997 |
assert list(csv.reader(io.StringIO(from_csv.stdout)))[0][-1] == sql |
| 4998 |
|
| 4999 |
from_json = hsql("--history", "--json") |
| 5000 |
assert json.loads(from_json.stdout)[0]["sql"] == sql |
| 5001 |
|
| 5002 |
|
| 5003 |
def test_history_wraps_a_multi_line_query_in_the_table( |
| 5004 |
hsql: Hsql, duck: list[str], query_log_path: Path |
| 5005 |
) -> None: |
| 5006 |
"""One line per physical line, `+` where it continues -- so the columns |
| 5007 |
beside it stay lined up instead of the row running into the next.""" |
| 5008 |
written = hsql(*duck, "--format", "none", "-c", "select\n 1 as a") |
| 5009 |
assert written.exit_code == ExitCode.OK, written.stderr |
| 5010 |
res = hsql("--history", "--no-header", "--no-footer") |
| 5011 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 5012 |
lines = res.stdout.splitlines() |
| 5013 |
assert len(lines) == 2 |
| 5014 |
assert lines[0].endswith("| select +") |
| 5015 |
assert lines[1].endswith("| 1 as a") |
| 5016 |
|
| 5017 |
|
| 5018 |
def test_a_discovered_profile_does_not_narrow_the_history( |
| 5019 |
hsql: Hsql, two_databases: tuple[list[str], list[str]], tmp_path: Path |
| 5020 |
) -> None: |
| 5021 |
"""A config file in the working directory is not a database the caller |
| 5022 |
named, and narrowing to it is the answer this mode exists to not give.""" |
| 5023 |
first, _ = two_databases |
| 5024 |
config_file = tmp_path / ".harlequin.toml" |
| 5025 |
config_file.write_text( |
| 5026 |
'default_profile = "first"\n\n[profiles.first]\nadapter = "duckdb"\n' |
| 5027 |
f"conn_str = [{json.dumps(first[-1])}]\nno_init = true\n" |
| 5028 |
) |
| 5029 |
res = hsql("--config-path", str(config_file), "--history", "-tA") |
| 5030 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 5031 |
assert len(sql_column(res.stdout)) == 3 |
| 5032 |
|
| 5033 |
|
| 5034 |
def test_a_tunneled_profile_is_not_narrowed_and_says_so( |
| 5035 |
hsql: Hsql, two_databases: tuple[list[str], list[str]], tmp_path: Path |
| 5036 |
) -> None: |
| 5037 |
"""Keying a tunneled connection means opening the tunnel, and this mode |
| 5038 |
connects to nothing -- so it reports every connection rather than exiting 3 |
| 5039 |
or narrowing to an id no row carries.""" |
| 5040 |
first, _ = two_databases |
| 5041 |
config_file = tmp_path / "tunnel.toml" |
| 5042 |
config_file.write_text( |
| 5043 |
'[profiles.tunneled]\nadapter = "duckdb"\n' |
| 5044 |
f"conn_str = [{json.dumps(first[-1])}]\nno_init = true\n" |
| 5045 |
'ssh_host = "bastion.example.invalid"\n' |
| 5046 |
'ssh_forward = [ "15439:db:5439" ]\n' |
| 5047 |
) |
| 5048 |
res = hsql("--config-path", str(config_file), "-P", "tunneled", "--history", "-tA") |
| 5049 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 5050 |
assert len(sql_column(res.stdout)) == 3 |
| 5051 |
assert "bastion.example.invalid" in res.stderr |
| 5052 |
|
| 5053 |
|
| 5054 |
def test_history_search_matches_the_middle_of_a_query( |
| 5055 |
hsql: Hsql, two_databases: tuple[list[str], list[str]] |
| 5056 |
) -> None: |
| 5057 |
res = hsql("--history-search", "2 as", "-tA") |
| 5058 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 5059 |
assert sql_column(res.stdout) == ["select 2 as two"] |
| 5060 |
|
| 5061 |
|
| 5062 |
def test_history_search_ignores_case( |
| 5063 |
hsql: Hsql, two_databases: tuple[list[str], list[str]] |
| 5064 |
) -> None: |
| 5065 |
"""SQLite's `like` is case-insensitive over ASCII, which is the behavior a |
| 5066 |
caller hunting for a table name wants and would not think to ask for.""" |
| 5067 |
res = hsql("--history-search", "SELECT 2", "-tA") |
| 5068 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 5069 |
assert sql_column(res.stdout) == ["select 2 as two"] |
| 5070 |
|
| 5071 |
|
| 5072 |
def test_history_search_takes_an_underscore_literally( |
| 5073 |
hsql: Hsql, duck: list[str], query_log_path: Path |
| 5074 |
) -> None: |
| 5075 |
"""`_` matches any character in a `like`, and is in half the table names |
| 5076 |
there are.""" |
| 5077 |
for sql in ("select 1 as line_items", "select 1 as lineXitems"): |
| 5078 |
assert hsql(*duck, "--format", "none", "-c", sql).exit_code == ExitCode.OK |
| 5079 |
res = hsql("--history-search", "line_items", "-tA") |
| 5080 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 5081 |
assert sql_column(res.stdout) == ["select 1 as line_items"] |
| 5082 |
|
| 5083 |
|
| 5084 |
def test_history_search_narrows_to_the_database_the_invocation_names( |
| 5085 |
hsql: Hsql, two_databases: tuple[list[str], list[str]] |
| 5086 |
) -> None: |
| 5087 |
first, _ = two_databases |
| 5088 |
res = hsql(*first, "--history-search", "select", "-tA") |
| 5089 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 5090 |
assert sql_column(res.stdout) == ["select 3 as three", "select 1 as one"] |
| 5091 |
|
| 5092 |
|
| 5093 |
def test_history_search_needs_a_term(hsql: Hsql) -> None: |
| 5094 |
"""An unset shell variable, far more often than an ask for everything.""" |
| 5095 |
res = hsql("--history-search", "") |
| 5096 |
assert res.exit_code == ExitCode.USAGE |
| 5097 |
assert res.stdout == "" |
| 5098 |
assert "needs a term" in res.stderr |
| 5099 |
|
| 5100 |
|
| 5101 |
def test_history_takes_every_format_a_result_set_does( |
| 5102 |
hsql: Hsql, two_databases: tuple[list[str], list[str]], tmp_path: Path |
| 5103 |
) -> None: |
| 5104 |
res = hsql("--history", "--limit", "1", "--markdown") |
| 5105 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 5106 |
assert res.stdout.startswith("|") |
| 5107 |
|
| 5108 |
destination = tmp_path / "history.csv" |
| 5109 |
res = hsql("--history", "-o", str(destination), "--csv") |
| 5110 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 5111 |
assert res.stdout == "" |
| 5112 |
assert destination.read_text().startswith("run_at,") |
| 5113 |
|
| 5114 |
|
| 5115 |
def test_display_rows_caps_a_history_listing( |
| 5116 |
hsql: Hsql, two_databases: tuple[list[str], list[str]] |
| 5117 |
) -> None: |
| 5118 |
"""The soft cap, over rows already read, so the footer still counts them all.""" |
| 5119 |
res = hsql("--history", "--display-rows", "1") |
| 5120 |
assert res.exit_code == ExitCode.OK, res.stderr |
| 5121 |
assert res.stdout.strip().endswith("(1 of 3 rows)") |
| 5122 |
|
| 5123 |
|
| 5124 |
def test_history_does_not_run_sql(hsql: Hsql, duck: list[str]) -> None: |
| 5125 |
res = hsql(*duck, "--history", "-c", "select 1") |
| 5126 |
assert res.exit_code == ExitCode.USAGE |
| 5127 |
assert res.stdout == "" |
| 5128 |
assert "does not run SQL" in res.stderr |
| 5129 |
|
| 5130 |
|
| 5131 |
@pytest.mark.parametrize( |
| 5132 |
"modes", |
| 5133 |
[ |
| 5134 |
["--history", "--catalog"], |
| 5135 |
["--history", "--history-search", "x"], |
| 5136 |
["--history-search", "x", "--info"], |
| 5137 |
], |
| 5138 |
) |
| 5139 |
def test_two_modes_in_one_invocation_is_a_usage_error( |
| 5140 |
hsql: Hsql, modes: list[str] |
| 5141 |
) -> None: |
| 5142 |
res = hsql(*modes) |
| 5143 |
assert res.exit_code == ExitCode.USAGE |
| 5144 |
assert res.stdout == "" |
| 5145 |
assert "two modes" in res.stderr |
| 5146 |
|
| 5147 |
|
| 5148 |
def test_a_store_that_cannot_be_read_is_reported_rather_than_raised( |
| 5149 |
hsql: Hsql, query_log_path: Path |
| 5150 |
) -> None: |
| 5151 |
query_log_path.write_text("this is not a database") |
| 5152 |
res = hsql("--history") |
| 5153 |
assert res.exit_code == ExitCode.USAGE |
| 5154 |
assert res.stdout == "" |
| 5155 |
assert "query history" in res.stderr |
| 5156 |
|
| 5157 |
|
| 5158 |
def test_history_is_in_the_help(hsql: Hsql) -> None: |
| 5159 |
res = hsql("--help") |
| 5160 |
assert res.exit_code == ExitCode.OK |
| 5161 |
assert "--history" in res.output |
| 5162 |
assert "--history-search" in res.output |
| 5163 |
assert f"{PROGRAM} --history" in res.output |