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