| 1 |
import sys |
| 2 |
import threading |
| 3 |
from pathlib import Path |
| 4 |
from typing import ( |
| 5 |
Awaitable, |
| 6 |
Callable, |
| 7 |
ClassVar, |
| 8 |
List, |
| 9 |
NamedTuple, |
| 10 |
Set, |
| 11 |
Type, |
| 12 |
cast, |
| 13 |
) |
| 14 |
from unittest.mock import MagicMock |
| 15 |
|
| 16 |
import duckdb |
| 17 |
import pytest |
| 18 |
from rich.style import Style |
| 19 |
from rich.text import Text |
| 20 |
from textual import work |
| 21 |
from textual.geometry import Offset |
| 22 |
from textual.widgets import Input, Tooltip |
| 23 |
from textual.worker import WorkerState |
| 24 |
|
| 25 |
from harlequin import Harlequin |
| 26 |
from harlequin.autocomplete.completers import BUFFER_TYPE_LABEL |
| 27 |
from harlequin.catalog import CatalogItem, InteractiveCatalogItem |
| 28 |
from harlequin.components import ErrorModal, ExportScreen |
| 29 |
from harlequin.components.data_catalog.database_tree import DatabaseTree |
| 30 |
from harlequin_duckdb.adapter import DuckDbAdapter |
| 31 |
|
| 32 |
|
| 33 |
class MockS3Object(NamedTuple): |
| 34 |
key: str |
| 35 |
|
| 36 |
|
| 37 |
class SimpleCatalogItem(InteractiveCatalogItem): |
| 38 |
"""An interactive item whose children fetch as an empty list.""" |
| 39 |
|
| 40 |
|
| 41 |
@pytest.fixture |
| 42 |
def mock_boto3(monkeypatch: pytest.MonkeyPatch) -> None: |
| 43 |
mock_boto3 = MagicMock(name="mock_boto3") |
| 44 |
mock_s3 = MagicMock(name="mock_s3") |
| 45 |
mock_boto3.resource.return_value = mock_s3 |
| 46 |
mock_bucket = MagicMock(name="mock_bucket") |
| 47 |
mock_bucket.name = "my-bucket" |
| 48 |
mock_s3.Bucket.return_value = mock_bucket |
| 49 |
mock_s3.buckets.all.return_value = [mock_bucket] |
| 50 |
objects = [ |
| 51 |
MockS3Object(key="one/alpha/foo.csv"), |
| 52 |
MockS3Object(key="one/bravo/bar.csv"), |
| 53 |
MockS3Object(key="two/apple/baz/qux.csv"), |
| 54 |
] |
| 55 |
mock_bucket.objects.all.return_value = objects |
| 56 |
mock_bucket.objects.filter.return_value = objects |
| 57 |
|
| 58 |
monkeypatch.setattr("harlequin.components.data_catalog.boto3", mock_boto3) |
| 59 |
monkeypatch.setattr("harlequin.components.data_catalog.s3_tree.boto3", mock_boto3) |
| 60 |
|
| 61 |
|
| 62 |
@pytest.mark.asyncio |
| 63 |
async def test_data_catalog( |
| 64 |
app_multi_duck: Harlequin, |
| 65 |
app_snapshot: Callable[..., Awaitable[bool]], |
| 66 |
wait_for_workers: Callable[[Harlequin], Awaitable[None]], |
| 67 |
mock_pyperclip: MagicMock, |
| 68 |
) -> None: |
| 69 |
snap_results: List[bool] = [] |
| 70 |
app = app_multi_duck |
| 71 |
async with app.run_test(size=(120, 36)) as pilot: |
| 72 |
await wait_for_workers(app) |
| 73 |
while app.editor is None: |
| 74 |
await pilot.pause() |
| 75 |
catalog = app.data_catalog |
| 76 |
assert not catalog.database_tree.show_root |
| 77 |
|
| 78 |
# this test app has two databases attached. |
| 79 |
dbs = catalog.database_tree.root.children |
| 80 |
assert len(dbs) == 2 |
| 81 |
|
| 82 |
# the first db is called "small" |
| 83 |
assert str(dbs[0].label) == "small db" |
| 84 |
assert dbs[0].data is not None |
| 85 |
assert dbs[0].data.qualified_identifier == '"small"' |
| 86 |
assert dbs[0].data.query_name == '"small"' |
| 87 |
assert dbs[0].is_expanded is False |
| 88 |
|
| 89 |
# the small db has two schemas, but you can't see them yet: a collapsed |
| 90 |
# node holds its children on `data` and only builds TreeNodes when it is |
| 91 |
# expanded, so that a huge catalog costs a screenful of nodes, not one |
| 92 |
# per object in the database. |
| 93 |
assert isinstance(dbs[0].data, InteractiveCatalogItem) |
| 94 |
while not dbs[0].data.loaded: |
| 95 |
await pilot.pause(0.1) |
| 96 |
assert len(dbs[0].data.children) == 2 |
| 97 |
assert not dbs[0].children |
| 98 |
snap_results.append(await app_snapshot(app, "Initialization")) |
| 99 |
|
| 100 |
assert str(dbs[1].label) == "tiny db" |
| 101 |
assert dbs[0].is_expanded is False |
| 102 |
|
| 103 |
# click on "small" and see it expand. |
| 104 |
await pilot.click(catalog.__class__, offset=Offset(x=6, y=1)) |
| 105 |
await pilot.pause() |
| 106 |
assert dbs[0].is_expanded is True |
| 107 |
assert dbs[1].is_expanded is False |
| 108 |
assert len(dbs[0].children) == 2 |
| 109 |
assert all(not node.is_expanded for node in dbs[0].children) |
| 110 |
# the schemas are on screen now, so the catalog probes them; wait, or the |
| 111 |
# snapshot catches "empty" still showing an expand arrow it will lose. |
| 112 |
for schema in dbs[0].children: |
| 113 |
while not getattr(schema.data, "loaded", True): |
| 114 |
await pilot.pause() |
| 115 |
snap_results.append(await app_snapshot(app, "small expanded")) |
| 116 |
|
| 117 |
# small's second schema is "main". click "main" |
| 118 |
schema_main = dbs[0].children[1] |
| 119 |
await pilot.click(catalog.__class__, offset=Offset(x=8, y=3)) |
| 120 |
await pilot.pause() |
| 121 |
assert schema_main.is_expanded is True |
| 122 |
assert catalog.database_tree.cursor_line == 2 # main is selected |
| 123 |
snap_results.append(await app_snapshot(app, "small.main expanded")) |
| 124 |
|
| 125 |
# ctrl+enter to insert into editor; editor gets focus |
| 126 |
await pilot.press("ctrl+j") |
| 127 |
await pilot.pause() |
| 128 |
assert schema_main.is_expanded is True |
| 129 |
assert app.editor.text == '"small"."main"' |
| 130 |
assert not catalog.has_focus |
| 131 |
snap_results.append(await app_snapshot(app, "Inserted small.main")) |
| 132 |
|
| 133 |
# use keys to navigate the tree into main.drivers |
| 134 |
await pilot.press("f6") |
| 135 |
await pilot.pause() |
| 136 |
assert catalog.database_tree.has_focus |
| 137 |
await pilot.press("down") |
| 138 |
await pilot.press("space") |
| 139 |
await pilot.press("down") |
| 140 |
await pilot.press("down") |
| 141 |
await pilot.press("enter") |
| 142 |
await pilot.pause() |
| 143 |
|
| 144 |
col_node = catalog.database_tree.cursor_node |
| 145 |
assert col_node is not None |
| 146 |
assert col_node.data is not None |
| 147 |
assert col_node.data.qualified_identifier == '"small"."main"."drivers"."dob"' |
| 148 |
assert col_node.data.query_name == '"dob"' |
| 149 |
snap_results.append(await app_snapshot(app, "small.main.drivers.dob selected")) |
| 150 |
|
| 151 |
# copy it |
| 152 |
await pilot.press("ctrl+c") |
| 153 |
assert mock_pyperclip.paste() == '"dob"' |
| 154 |
|
| 155 |
# reset the editor, then insert "dob" |
| 156 |
app.editor.text = "" |
| 157 |
await pilot.press("ctrl+j") |
| 158 |
await pilot.pause() |
| 159 |
assert app.editor.text == '"dob"' |
| 160 |
snap_results.append(await app_snapshot(app, "small.main.drivers.dob inserted")) |
| 161 |
|
| 162 |
assert all(snap_results) |
| 163 |
|
| 164 |
|
| 165 |
@pytest.mark.asyncio |
| 166 |
async def test_double_click_inserts_node_into_editor( |
| 167 |
app_multi_duck: Harlequin, |
| 168 |
wait_for_workers: Callable[[Harlequin], Awaitable[None]], |
| 169 |
) -> None: |
| 170 |
app = app_multi_duck |
| 171 |
async with app.run_test(size=(120, 36)) as pilot: |
| 172 |
await wait_for_workers(app) |
| 173 |
while app.editor is None: |
| 174 |
await pilot.pause() |
| 175 |
catalog = app.data_catalog |
| 176 |
|
| 177 |
dbs = catalog.database_tree.root.children |
| 178 |
assert isinstance(dbs[0].data, InteractiveCatalogItem) |
| 179 |
while not dbs[0].data.loaded: |
| 180 |
await pilot.pause(0.1) |
| 181 |
|
| 182 |
# a single click on "small" selects and expands it, but inserts nothing |
| 183 |
await pilot.click(catalog.__class__, offset=Offset(x=6, y=1)) |
| 184 |
await pilot.pause() |
| 185 |
assert app.editor.text == "" |
| 186 |
|
| 187 |
# a double click inserts the node's query name into the editor |
| 188 |
await pilot.double_click(catalog.__class__, offset=Offset(x=6, y=1)) |
| 189 |
await pilot.pause() |
| 190 |
assert app.editor.text == '"small"' |
| 191 |
assert dbs[0].is_expanded is True |
| 192 |
|
| 193 |
|
| 194 |
@pytest.mark.asyncio |
| 195 |
async def test_file_tree( |
| 196 |
duckdb_adapter: Type[DuckDbAdapter], |
| 197 |
data_dir: Path, |
| 198 |
app_snapshot: Callable[..., Awaitable[bool]], |
| 199 |
mock_pyperclip: MagicMock, |
| 200 |
) -> None: |
| 201 |
snap_results: List[bool] = [] |
| 202 |
test_dir = data_dir / "functional_tests" / "files" |
| 203 |
relative_test_dir = test_dir.relative_to(Path.cwd()) |
| 204 |
app = Harlequin( |
| 205 |
duckdb_adapter((":memory:",)), |
| 206 |
show_files=relative_test_dir, |
| 207 |
) |
| 208 |
async with app.run_test(size=(120, 36)) as pilot: |
| 209 |
while app.editor is None: |
| 210 |
await pilot.pause() |
| 211 |
catalog = app.data_catalog |
| 212 |
assert catalog.file_tree is not None |
| 213 |
|
| 214 |
await pilot.press("f6") # focus catalog |
| 215 |
await pilot.press("k") # show files |
| 216 |
snap_results.append(await app_snapshot(app, "Initialization")) |
| 217 |
|
| 218 |
await pilot.press("down") |
| 219 |
await pilot.press("enter") |
| 220 |
snap_results.append(await app_snapshot(app, "expanded foo dir")) |
| 221 |
|
| 222 |
await pilot.press("ctrl+c") |
| 223 |
assert mock_pyperclip.paste() == str(test_dir / "foo") |
| 224 |
|
| 225 |
assert all(snap_results) |
| 226 |
|
| 227 |
|
| 228 |
@pytest.mark.py12 |
| 229 |
@pytest.mark.skipif( |
| 230 |
sys.version_info < (3, 12), reason="3.12 renders CSS differently for this test..." |
| 231 |
) |
| 232 |
@pytest.mark.asyncio |
| 233 |
async def test_s3_tree( |
| 234 |
duckdb_adapter: Type[DuckDbAdapter], |
| 235 |
app_snapshot: Callable[..., Awaitable[bool]], |
| 236 |
wait_for_workers: Callable[[Harlequin], Awaitable[None]], |
| 237 |
mock_pyperclip: MagicMock, |
| 238 |
mock_boto3: None, |
| 239 |
) -> None: |
| 240 |
snap_results: List[bool] = [] |
| 241 |
app = Harlequin( |
| 242 |
duckdb_adapter((":memory:",)), |
| 243 |
show_s3="my-bucket", |
| 244 |
) |
| 245 |
async with app.run_test(size=(120, 36)) as pilot: |
| 246 |
await wait_for_workers(app) |
| 247 |
while app.editor is None: |
| 248 |
await pilot.pause() |
| 249 |
catalog = app.data_catalog |
| 250 |
assert catalog.s3_tree is not None |
| 251 |
while not catalog.s3_tree.is_mounted: |
| 252 |
await pilot.pause() |
| 253 |
|
| 254 |
await pilot.press("f6") # focus catalog |
| 255 |
await pilot.press("k") # show s3 |
| 256 |
snap_results.append(await app_snapshot(app, "Initialization")) |
| 257 |
|
| 258 |
await pilot.press("down") |
| 259 |
await pilot.press("enter") |
| 260 |
await pilot.press("down") |
| 261 |
await pilot.press("enter") |
| 262 |
snap_results.append(await app_snapshot(app, "expanded one dir")) |
| 263 |
|
| 264 |
await pilot.press("ctrl+c") |
| 265 |
assert mock_pyperclip.paste() == "s3://my-bucket/one" |
| 266 |
|
| 267 |
assert all(snap_results) |
| 268 |
|
| 269 |
|
| 270 |
@pytest.mark.skipif("boto3" in sys.modules, reason="boto3 is installed.") |
| 271 |
@pytest.mark.asyncio |
| 272 |
async def test_s3_tree_does_not_crash_without_boto3( |
| 273 |
duckdb_adapter: Type[DuckDbAdapter], |
| 274 |
app_snapshot: Callable[..., Awaitable[bool]], |
| 275 |
wait_for_workers: Callable[[Harlequin], Awaitable[None]], |
| 276 |
) -> None: |
| 277 |
app = Harlequin( |
| 278 |
duckdb_adapter((":memory:",)), |
| 279 |
show_s3="my-bucket", |
| 280 |
) |
| 281 |
async with app.run_test(size=(120, 36)) as pilot: |
| 282 |
await wait_for_workers(app) |
| 283 |
while app.editor is None: |
| 284 |
await pilot.pause() |
| 285 |
assert await app_snapshot(app, "Error visible") |
| 286 |
|
| 287 |
|
| 288 |
@pytest.mark.asyncio |
| 289 |
async def test_context_menu( |
| 290 |
app_small_duck: Harlequin, |
| 291 |
app_snapshot: Callable[..., Awaitable[bool]], |
| 292 |
wait_for_workers: Callable[[Harlequin], Awaitable[None]], |
| 293 |
expand_catalog_node: Callable[..., Awaitable[None]], |
| 294 |
) -> None: |
| 295 |
app = app_small_duck |
| 296 |
snap_results: List[bool] = [] |
| 297 |
async with app.run_test(size=(120, 36)) as pilot: |
| 298 |
await wait_for_workers(app) |
| 299 |
while app.editor is None: |
| 300 |
await pilot.pause() |
| 301 |
|
| 302 |
# we need to expand the data catalog to load items into the completer |
| 303 |
while ( |
| 304 |
app.data_catalog.database_tree.loading |
| 305 |
or not app.data_catalog.database_tree.root.children |
| 306 |
): |
| 307 |
await pilot.pause() |
| 308 |
for db_node in app.data_catalog.database_tree.root.children: |
| 309 |
await expand_catalog_node(pilot, db_node) |
| 310 |
for schema_node in db_node.children: |
| 311 |
schema_node.expand() |
| 312 |
|
| 313 |
app.data_catalog.focus() |
| 314 |
await pilot.press("full_stop") |
| 315 |
await pilot.pause() |
| 316 |
await wait_for_workers(app) |
| 317 |
await pilot.pause() |
| 318 |
await pilot.wait_for_scheduled_animations() |
| 319 |
snap_results.append(await app_snapshot(app, "db context menu expanded")) |
| 320 |
|
| 321 |
await pilot.press("enter") |
| 322 |
await pilot.pause() |
| 323 |
await wait_for_workers(app) |
| 324 |
await pilot.pause() |
| 325 |
await pilot.wait_for_scheduled_animations() |
| 326 |
snap_results.append(await app_snapshot(app, "db name inserted")) |
| 327 |
|
| 328 |
app.data_catalog.focus() |
| 329 |
await pilot.press("down") |
| 330 |
await pilot.press("full_stop") |
| 331 |
await pilot.pause() |
| 332 |
await wait_for_workers(app) |
| 333 |
await pilot.pause() |
| 334 |
await pilot.wait_for_scheduled_animations() |
| 335 |
snap_results.append(await app_snapshot(app, "schema context menu expanded")) |
| 336 |
|
| 337 |
await pilot.press("escape") |
| 338 |
await pilot.press("down") |
| 339 |
await pilot.press("down") |
| 340 |
await pilot.press("full_stop") |
| 341 |
await pilot.pause() |
| 342 |
await wait_for_workers(app) |
| 343 |
await pilot.pause() |
| 344 |
await pilot.wait_for_scheduled_animations() |
| 345 |
snap_results.append(await app_snapshot(app, "table context menu expanded")) |
| 346 |
|
| 347 |
assert all(snap_results) |
| 348 |
|
| 349 |
|
| 350 |
def _file_tree_paths(app: Harlequin) -> Set[Path]: |
| 351 |
"""Return the paths of the top-level nodes in the file tree.""" |
| 352 |
assert app.data_catalog.file_tree is not None |
| 353 |
return { |
| 354 |
node.data.path |
| 355 |
for node in app.data_catalog.file_tree.root.children |
| 356 |
if node.data is not None |
| 357 |
} |
| 358 |
|
| 359 |
|
| 360 |
@pytest.mark.asyncio |
| 361 |
async def test_file_tree_refreshes_after_editor_save( |
| 362 |
duckdb_adapter: Type[DuckDbAdapter], |
| 363 |
tmp_path: Path, |
| 364 |
) -> None: |
| 365 |
""" |
| 366 |
Regression test for https://github.com/tconbeer/harlequin/issues/871: |
| 367 |
the file tree should refresh after Harlequin saves a file from the editor, |
| 368 |
without the user having to manually refresh the catalog. |
| 369 |
""" |
| 370 |
app = Harlequin(duckdb_adapter((":memory:",)), show_files=tmp_path) |
| 371 |
async with app.run_test() as pilot: |
| 372 |
while app.editor is None: |
| 373 |
await pilot.pause() |
| 374 |
assert app.data_catalog.file_tree is not None |
| 375 |
|
| 376 |
new_file = tmp_path / "saved_by_harlequin.sql" |
| 377 |
assert new_file not in _file_tree_paths(app) |
| 378 |
|
| 379 |
app.editor.focus() |
| 380 |
app.editor.text = "select 1" |
| 381 |
await pilot.press("ctrl+s") |
| 382 |
await pilot.pause() |
| 383 |
save_input = app.editor.query_one("#textarea__save_input", Input) |
| 384 |
save_input.value = str(new_file) |
| 385 |
await pilot.press("enter") |
| 386 |
|
| 387 |
for _ in range(100): |
| 388 |
await pilot.pause() |
| 389 |
if new_file in _file_tree_paths(app): |
| 390 |
break |
| 391 |
|
| 392 |
assert new_file.is_file() |
| 393 |
assert new_file in _file_tree_paths(app) |
| 394 |
|
| 395 |
|
| 396 |
@pytest.mark.asyncio |
| 397 |
async def test_file_tree_refreshes_after_export( |
| 398 |
duckdb_adapter: Type[DuckDbAdapter], |
| 399 |
tmp_path: Path, |
| 400 |
) -> None: |
| 401 |
""" |
| 402 |
Regression test for https://github.com/tconbeer/harlequin/issues/871: |
| 403 |
the file tree should refresh after Harlequin exports data to a file, |
| 404 |
without the user having to manually refresh the catalog. |
| 405 |
""" |
| 406 |
app = Harlequin(duckdb_adapter((":memory:",)), show_files=tmp_path) |
| 407 |
async with app.run_test(size=(120, 36)) as pilot: |
| 408 |
while app.editor is None: |
| 409 |
await pilot.pause() |
| 410 |
|
| 411 |
app.editor.text = "select 1 as a, 2 as b" |
| 412 |
await pilot.press("ctrl+j") # run query |
| 413 |
for _ in range(100): |
| 414 |
await pilot.pause() |
| 415 |
if app.results_viewer.get_visible_table() is not None: |
| 416 |
break |
| 417 |
assert app.results_viewer.get_visible_table() is not None |
| 418 |
|
| 419 |
export_path = tmp_path / "exported.csv" |
| 420 |
assert export_path not in _file_tree_paths(app) |
| 421 |
|
| 422 |
await pilot.press("ctrl+e") |
| 423 |
while not isinstance(app.screen, ExportScreen): |
| 424 |
await pilot.pause() |
| 425 |
app.screen.file_input.value = str(export_path) |
| 426 |
await pilot.pause() |
| 427 |
await pilot.press("enter") |
| 428 |
|
| 429 |
for _ in range(100): |
| 430 |
await pilot.pause() |
| 431 |
if export_path in _file_tree_paths(app): |
| 432 |
break |
| 433 |
|
| 434 |
assert export_path.is_file() |
| 435 |
assert export_path in _file_tree_paths(app) |
| 436 |
|
| 437 |
|
| 438 |
class BlockingCatalogItem(InteractiveCatalogItem): |
| 439 |
"""A catalog item whose fetch_children() blocks until it is released.""" |
| 440 |
|
| 441 |
started: ClassVar[threading.Event] = threading.Event() |
| 442 |
release: ClassVar[threading.Event] = threading.Event() |
| 443 |
|
| 444 |
def fetch_children(self) -> List[CatalogItem]: |
| 445 |
type(self).started.set() |
| 446 |
type(self).release.wait(timeout=10) |
| 447 |
return [] |
| 448 |
|
| 449 |
|
| 450 |
@pytest.mark.asyncio |
| 451 |
async def test_reload_while_loader_is_fetching( |
| 452 |
duckdb_adapter: Type[DuckDbAdapter], |
| 453 |
) -> None: |
| 454 |
"""Reloading the catalog mid-fetch must not crash the background loader. |
| 455 |
|
| 456 |
reload() replaces the tree's load queue. The loader used to call task_done() |
| 457 |
on whatever `self._load_queue` pointed at when its fetch returned, so a reload |
| 458 |
that landed mid-fetch made it call task_done() on the fresh queue -- which has |
| 459 |
no outstanding get() -- and the worker died with "task_done() called too many |
| 460 |
times" ([#991](https://github.com/tconbeer/harlequin/issues/991)). |
| 461 |
""" |
| 462 |
BlockingCatalogItem.started.clear() |
| 463 |
BlockingCatalogItem.release.clear() |
| 464 |
|
| 465 |
app = Harlequin(duckdb_adapter((":memory:",))) |
| 466 |
async with app.run_test(size=(120, 36)) as pilot: |
| 467 |
tree = app.data_catalog.database_tree |
| 468 |
while tree.loading: |
| 469 |
await pilot.pause() |
| 470 |
|
| 471 |
item = BlockingCatalogItem( |
| 472 |
qualified_identifier="blocking", |
| 473 |
query_name="blocking", |
| 474 |
label="blocking", |
| 475 |
type_label="t", |
| 476 |
) |
| 477 |
tree.root.add("blocking", data=item) |
| 478 |
tree._add_to_load_queue(item, priority=0) |
| 479 |
|
| 480 |
# wait until the adapter call is actually in flight |
| 481 |
while not BlockingCatalogItem.started.is_set(): |
| 482 |
await pilot.pause() |
| 483 |
|
| 484 |
# ... and swap the queue out from under the in-flight loader |
| 485 |
await tree.reload() |
| 486 |
BlockingCatalogItem.release.set() |
| 487 |
for _ in range(50): |
| 488 |
await pilot.pause() |
| 489 |
|
| 490 |
loaders = [ |
| 491 |
w for w in app.workers if w.name == "_database_tree_background_loader" |
| 492 |
] |
| 493 |
assert not [w.error for w in loaders if w.error is not None] |
| 494 |
|
| 495 |
|
| 496 |
@pytest.mark.asyncio |
| 497 |
async def test_tooltip_shows_the_full_label_of_a_truncated_item( |
| 498 |
duckdb_adapter: Type[DuckDbAdapter], |
| 499 |
tmp_path: Path, |
| 500 |
wait_for_workers: Callable[[Harlequin], Awaitable[None]], |
| 501 |
expand_catalog_node: Callable[..., Awaitable[None]], |
| 502 |
) -> None: |
| 503 |
"""A catalog item too wide for the catalog gets a tooltip on hover. |
| 504 |
|
| 505 |
([#1104](https://github.com/tconbeer/harlequin/issues/1104)) |
| 506 |
""" |
| 507 |
db_path = tmp_path / "tooltip.db" |
| 508 |
conn = duckdb.connect(str(db_path)) |
| 509 |
# the brackets are a type label's shape ("[s]" is a list of strings), so this |
| 510 |
# name also pins that a label never reaches the tooltip as console markup |
| 511 |
conn.execute('create table "a_table_[s]_with_a_name_too_long_to_fit" (a int)') |
| 512 |
conn.close() |
| 513 |
|
| 514 |
app = Harlequin(duckdb_adapter([str(db_path)], no_init=True), connection_hash="tt") |
| 515 |
async with app.run_test(size=(120, 36), tooltips=True) as pilot: |
| 516 |
await wait_for_workers(app) |
| 517 |
tree = app.data_catalog.database_tree |
| 518 |
while tree.loading or not tree.root.children: |
| 519 |
await pilot.pause() |
| 520 |
db_node = tree.root.children[0] |
| 521 |
await expand_catalog_node(pilot, db_node) |
| 522 |
await expand_catalog_node(pilot, db_node.children[0]) |
| 523 |
await pilot.pause() |
| 524 |
|
| 525 |
# the db's own label fits in the catalog, so it gets no tooltip |
| 526 |
await pilot.hover(app.data_catalog.__class__, offset=Offset(x=6, y=1)) |
| 527 |
await pilot.pause() |
| 528 |
assert tree.hover_line == 0 |
| 529 |
assert tree.tooltip is None |
| 530 |
|
| 531 |
# the table's does not, so hovering it shows the label and type label |
| 532 |
await pilot.hover(app.data_catalog.__class__, offset=Offset(x=6, y=3)) |
| 533 |
await pilot.pause() |
| 534 |
assert tree.hover_line == 2 |
| 535 |
assert isinstance(tree.tooltip, Text) |
| 536 |
assert tree.tooltip.plain == "a_table_[s]_with_a_name_too_long_to_fit t" |
| 537 |
|
| 538 |
# and the type label keeps the muted color it has in the tree |
| 539 |
type_label_span = tree.tooltip.spans[-1] |
| 540 |
assert tree.tooltip.plain[type_label_span.start : type_label_span.end] == "t" |
| 541 |
assert isinstance(type_label_span.style, Style) |
| 542 |
assert type_label_span.style.color is not None |
| 543 |
|
| 544 |
tooltip = app.screen.get_child_by_type(Tooltip) |
| 545 |
await pilot.pause(app.TOOLTIP_DELAY + 0.1) |
| 546 |
assert tooltip.display |
| 547 |
|
| 548 |
|
| 549 |
@pytest.mark.asyncio |
| 550 |
async def test_buffer_symbols_load_the_items_they_name( |
| 551 |
duckdb_adapter: Type[DuckDbAdapter], |
| 552 |
tmp_path: Path, |
| 553 |
wait_for_workers: Callable[[Harlequin], Awaitable[None]], |
| 554 |
) -> None: |
| 555 |
"""The catalog loads the children of the items the query editor names. |
| 556 |
|
| 557 |
Lazy loading otherwise leaves a schema's relations (and their columns) out of |
| 558 |
the completions until the user expands the schema in the Data Catalog |
| 559 |
([#752](https://github.com/tconbeer/harlequin/issues/752)). |
| 560 |
""" |
| 561 |
db_path = tmp_path / "symbols.db" |
| 562 |
conn = duckdb.connect(str(db_path)) |
| 563 |
conn.execute("create schema my_schema") |
| 564 |
conn.execute("create table my_schema.my_table (my_col int)") |
| 565 |
conn.close() |
| 566 |
|
| 567 |
app = Harlequin( |
| 568 |
duckdb_adapter((str(db_path),), no_init=True), |
| 569 |
connection_hash="symbols", |
| 570 |
) |
| 571 |
async with app.run_test(size=(120, 36)) as pilot: |
| 572 |
await wait_for_workers(app) |
| 573 |
tree = app.data_catalog.database_tree |
| 574 |
while ( |
| 575 |
tree.loading |
| 576 |
or app.editor is None |
| 577 |
or app.editor_collection.member_completer is None |
| 578 |
): |
| 579 |
await pilot.pause() |
| 580 |
member_completer = app.editor_collection.member_completer |
| 581 |
|
| 582 |
database_item = tree.root.data.children[0] if tree.root.data else None |
| 583 |
assert database_item is not None |
| 584 |
while not getattr(database_item, "loaded", False): |
| 585 |
await pilot.pause() |
| 586 |
schema_item = next( |
| 587 |
item for item in database_item.children if item.label == "my_schema" |
| 588 |
) |
| 589 |
assert not schema_item.children |
| 590 |
assert not member_completer("my_schema.my_t") |
| 591 |
|
| 592 |
app.editor.text = "select * from my_schema.my_table" |
| 593 |
|
| 594 |
# the editor re-reads the buffer on a timer, the tree loads the schema |
| 595 |
# the buffer names, and then the relation it names under it |
| 596 |
for _ in range(100): |
| 597 |
if member_completer("my_table.my_c"): |
| 598 |
break |
| 599 |
await pilot.pause(0.1) |
| 600 |
|
| 601 |
# the buffer names my_table, so its own completion for it is not proof; |
| 602 |
# the column is one only the catalog could have offered. |
| 603 |
(schema_label, schema_value), *_ = member_completer("my_schema.my_t") |
| 604 |
assert schema_value == "my_schema.my_table" |
| 605 |
assert schema_label[1] != BUFFER_TYPE_LABEL |
| 606 |
(column_label, column_value), *_ = member_completer("my_table.my_c") |
| 607 |
assert column_value == "my_table.my_col" |
| 608 |
assert column_label[1] != BUFFER_TYPE_LABEL |
| 609 |
|
| 610 |
|
| 611 |
@pytest.mark.asyncio |
| 612 |
async def test_child_worker_failure_is_surfaced_and_loader_continues( |
| 613 |
duckdb_adapter: Type[DuckDbAdapter], |
| 614 |
monkeypatch: pytest.MonkeyPatch, |
| 615 |
) -> None: |
| 616 |
"""An unexpected failure in the loader's per-item worker shows one catalog |
| 617 |
modal, and the loader goes on to the next item. |
| 618 |
|
| 619 |
_load_children catches adapter failures itself; a child worker that fails |
| 620 |
anyway reaches the loader's WorkerFailed path, and its StateChanged ERROR |
| 621 |
is surfaced by DatabaseTree rather than crashing Harlequin (regression |
| 622 |
test for #1117). |
| 623 |
""" |
| 624 |
poison_item = SimpleCatalogItem( |
| 625 |
qualified_identifier="poison", |
| 626 |
query_name="poison", |
| 627 |
label="poison", |
| 628 |
type_label="t", |
| 629 |
) |
| 630 |
good_item = SimpleCatalogItem( |
| 631 |
qualified_identifier="good", |
| 632 |
query_name="good", |
| 633 |
label="good", |
| 634 |
type_label="t", |
| 635 |
) |
| 636 |
original_load_children = cast( |
| 637 |
Callable[[DatabaseTree, CatalogItem], list[CatalogItem]], |
| 638 |
getattr(DatabaseTree._load_children, "__wrapped__"), # noqa: B009 |
| 639 |
) |
| 640 |
|
| 641 |
@work(thread=True, exit_on_error=False, description="_load_children") |
| 642 |
def patched_load_children( |
| 643 |
tree: DatabaseTree, item: CatalogItem |
| 644 |
) -> list[CatalogItem]: |
| 645 |
if item is poison_item: |
| 646 |
raise RuntimeError("boom in _load_children") |
| 647 |
return original_load_children(tree, item) |
| 648 |
|
| 649 |
monkeypatch.setattr(DatabaseTree, "_load_children", patched_load_children) |
| 650 |
|
| 651 |
app = Harlequin(duckdb_adapter((":memory:",)), connection_hash="child-failure") |
| 652 |
async with app.run_test(size=(120, 36)) as pilot: |
| 653 |
tree = app.data_catalog.database_tree |
| 654 |
while tree.loading or app.editor is None: |
| 655 |
await pilot.pause() |
| 656 |
|
| 657 |
tree.root.add("poison", data=poison_item) |
| 658 |
tree._add_to_load_queue(poison_item, priority=0) |
| 659 |
for _ in range(200): |
| 660 |
if any(isinstance(screen, ErrorModal) for screen in app.screen_stack): |
| 661 |
break |
| 662 |
await pilot.pause(0.05) |
| 663 |
assert isinstance(app.screen, ErrorModal) |
| 664 |
assert "boom in _load_children" in str(app.screen.error) |
| 665 |
assert app._exception is None |
| 666 |
await pilot.press("space") |
| 667 |
await pilot.pause() |
| 668 |
assert len(app.screen_stack) == 1 |
| 669 |
|
| 670 |
# the loader survived the failed item and still processes the queue |
| 671 |
tree.root.add("good", data=good_item) |
| 672 |
tree._add_to_load_queue(good_item, priority=0) |
| 673 |
for _ in range(200): |
| 674 |
if good_item.loaded: |
| 675 |
break |
| 676 |
await pilot.pause(0.05) |
| 677 |
assert good_item.loaded |
| 678 |
assert len(app.screen_stack) == 1 |
| 679 |
assert app._exception is None |
| 680 |
|
| 681 |
|
| 682 |
@pytest.mark.asyncio |
| 683 |
async def test_background_loader_failure_is_surfaced_without_crashing( |
| 684 |
duckdb_adapter: Type[DuckDbAdapter], |
| 685 |
monkeypatch: pytest.MonkeyPatch, |
| 686 |
) -> None: |
| 687 |
"""An unexpected failure inside the background loader stops that loader |
| 688 |
with one catalog modal, and does not crash Harlequin. |
| 689 |
|
| 690 |
Regression test for #1117: the loader used Textual's default |
| 691 |
exit_on_error=True, so anything escaping its loop took the whole app down. |
| 692 |
""" |
| 693 |
|
| 694 |
def raise_on_named_items(tree: DatabaseTree) -> None: |
| 695 |
raise RuntimeError("boom in the loader") |
| 696 |
|
| 697 |
monkeypatch.setattr(DatabaseTree, "_queue_named_items", raise_on_named_items) |
| 698 |
# the editor's own symbol scans reach _queue_named_items on the message |
| 699 |
# pump (via load_items_named); record their names without queuing, so the |
| 700 |
# raiser above only ever fires from inside the background loader. |
| 701 |
monkeypatch.setattr( |
| 702 |
DatabaseTree, |
| 703 |
"load_items_named", |
| 704 |
lambda tree, names: setattr( |
| 705 |
tree, "_symbol_names", frozenset(name.casefold() for name in names) |
| 706 |
), |
| 707 |
) |
| 708 |
# no prefetch work either: the loader must still be waiting on an empty |
| 709 |
# queue when the test captures it, not already dead on a queued item. |
| 710 |
monkeypatch.setattr(DatabaseTree, "_schedule_prefetch_scan", lambda self: None) |
| 711 |
app = Harlequin(duckdb_adapter((":memory:",)), connection_hash="loader-failure") |
| 712 |
async with app.run_test(size=(120, 36)) as pilot: |
| 713 |
tree = app.data_catalog.database_tree |
| 714 |
while tree.loading or app.editor is None: |
| 715 |
await pilot.pause() |
| 716 |
for _ in range(200): |
| 717 |
loaders = [ |
| 718 |
worker |
| 719 |
for worker in app.workers |
| 720 |
if worker.name == "_database_tree_background_loader" |
| 721 |
and worker.state == WorkerState.RUNNING |
| 722 |
] |
| 723 |
if loaders: |
| 724 |
break |
| 725 |
await pilot.pause(0.05) |
| 726 |
assert len(loaders) == 1 |
| 727 |
loader = loaders[0] |
| 728 |
|
| 729 |
item = SimpleCatalogItem( |
| 730 |
qualified_identifier="x", |
| 731 |
query_name="x", |
| 732 |
label="x", |
| 733 |
type_label="t", |
| 734 |
) |
| 735 |
tree.root.add("x", data=item) |
| 736 |
tree._add_to_load_queue(item, priority=0) |
| 737 |
for _ in range(200): |
| 738 |
if any(isinstance(screen, ErrorModal) for screen in app.screen_stack): |
| 739 |
break |
| 740 |
await pilot.pause(0.05) |
| 741 |
assert isinstance(app.screen, ErrorModal) |
| 742 |
assert "boom in the loader" in str(app.screen.error) |
| 743 |
assert app._exception is None |
| 744 |
|
| 745 |
# the failure stopped the loader: it is terminal, not waiting for work |
| 746 |
assert loader.state == WorkerState.ERROR |
| 747 |
assert app.is_running |