| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
import subprocess |
| 5 |
import sys |
| 6 |
from pathlib import Path |
| 7 |
from typing import Callable |
| 8 |
|
| 9 |
import pytest |
| 10 |
|
| 11 |
from harlequin.adapter import HarlequinAdapter |
| 12 |
from harlequin.query import ResultSet, RowLimit, execute, fetch |
| 13 |
from harlequin.statements import split |
| 14 |
|
| 15 |
|
| 16 |
@pytest.fixture |
| 17 |
def result_set( |
| 18 |
duckdb_adapter: type[HarlequinAdapter], |
| 19 |
) -> Callable[..., ResultSet]: |
| 20 |
"""Run one statement against an in-memory DuckDB and fetch its result. |
| 21 |
|
| 22 |
DuckDB rather than a fake cursor: everything downstream of `fetch()` is |
| 23 |
about how real values -- decimals, blobs, structs -- come out, and a fake |
| 24 |
would only prove that the fixture and the assertion agree. |
| 25 |
""" |
| 26 |
connection = duckdb_adapter([":memory:"], no_init=True).connect() |
| 27 |
|
| 28 |
def _result_set(sql: str, limit: RowLimit | None = None) -> ResultSet: |
| 29 |
(executed,) = execute(connection, split(sql), limit=limit) |
| 30 |
return fetch(executed, limit=limit) |
| 31 |
|
| 32 |
return _result_set |
| 33 |
|
| 34 |
|
| 35 |
@pytest.fixture |
| 36 |
def run_python(tmp_path: Path) -> Callable[[str], subprocess.CompletedProcess[str]]: |
| 37 |
"""Run a snippet in a fresh interpreter and capture its streams. |
| 38 |
|
| 39 |
In-process assertions can't see the state these tests care about: which |
| 40 |
modules an import pulled in, and which stream something was written to. |
| 41 |
Both are properties of a clean interpreter, and pytest has already imported |
| 42 |
half the world by the time a test runs. |
| 43 |
|
| 44 |
A clean *machine*, too: `no_discovered_config` cannot reach into a |
| 45 |
subprocess, so the child gets an empty directory as its cwd, its home and |
| 46 |
its config dir. Otherwise it reads the config files of whoever is running |
| 47 |
the tests. |
| 48 |
""" |
| 49 |
env = { |
| 50 |
**os.environ, |
| 51 |
# where config discovery looks, on every platform platformdirs knows |
| 52 |
"HOME": str(tmp_path), |
| 53 |
"USERPROFILE": str(tmp_path), |
| 54 |
"XDG_CONFIG_HOME": str(tmp_path / "xdg"), |
| 55 |
"APPDATA": str(tmp_path / "appdata"), |
| 56 |
"LOCALAPPDATA": str(tmp_path / "localappdata"), |
| 57 |
} |
| 58 |
|
| 59 |
def _run(code: str) -> subprocess.CompletedProcess[str]: |
| 60 |
return subprocess.run( |
| 61 |
[sys.executable, "-c", code], |
| 62 |
capture_output=True, |
| 63 |
text=True, |
| 64 |
check=True, |
| 65 |
cwd=tmp_path, |
| 66 |
env=env, |
| 67 |
) |
| 68 |
|
| 69 |
return _run |