Debian Codegraph @

tests/functional_tests/test_query_editor.py

raw
1 from __future__ import annotations
2
3 import sys
4 from typing import Awaitable, Callable, List
5
6 import pytest
7 from textual.widgets import TextArea
8 from textual.widgets.text_area import Selection
9 from textual.worker import WorkerFailed
10
11 from harlequin import Harlequin
12 from harlequin.autocomplete import BufferSymbols
13 from harlequin.autocomplete import find_symbols as real_find_symbols
14 from harlequin.components.code_editor import CodeEditor
15 from harlequin.statements import find_separators, split
16
17
18 @pytest.mark.asyncio
19 async def test_query_formatting(
20 app: Harlequin,
21 wait_for_workers: Callable[[Harlequin], Awaitable[None]],
22 ) -> None:
23 async with app.run_test() as pilot:
24 await wait_for_workers(app)
25 while app.editor is None:
26 await pilot.pause()
27 app.editor.text = "select\n\n1 FROM\n\n foo"
28
29 await pilot.press("f4")
30 assert app.editor.text == "select 1 from foo\n"
31 assert list(app._notifications)[-1].message == "Formatted query."
32
33 # formatting an already-formatted query notifies that nothing changed
34 await pilot.press("f4")
35 assert app.editor.text == "select 1 from foo\n"
36 assert "no changes" in list(app._notifications)[-1].message
37
38
39 @pytest.mark.flaky
40 @pytest.mark.asyncio
41 async def test_multiple_buffers(
42 app: Harlequin,
43 app_snapshot: Callable[..., Awaitable[bool]],
44 wait_for_workers: Callable[[Harlequin], Awaitable[None]],
45 ) -> None:
46 snap_results: List[bool] = []
47 async with app.run_test(size=(120, 36)) as pilot:
48 await wait_for_workers(app)
49 while app.editor is None:
50 await pilot.pause()
51 assert app.editor_collection
52 assert app.editor_collection.tab_count == 1
53 assert app.editor_collection.active == "tab-1"
54 app.editor.text = "tab 1"
55 await pilot.press("home")
56 await pilot.pause()
57 snap_results.append(await app_snapshot(app, "Tab 1 of 1 (No tabs)"))
58
59 await pilot.press("ctrl+n")
60 await pilot.pause()
61 await pilot.wait_for_scheduled_animations()
62 assert app.editor_collection.tab_count == 2
63 assert app.editor_collection.active == "tab-2"
64 assert app.editor.text == ""
65 app.editor.text = "tab 2"
66 await pilot.press("home")
67 await pilot.pause()
68 snap_results.append(await app_snapshot(app, "Tab 2 of 2"))
69
70 await pilot.press("ctrl+n")
71 await pilot.pause()
72 await pilot.wait_for_scheduled_animations()
73 assert app.editor_collection.tab_count == 3
74 assert app.editor_collection.active == "tab-3"
75 assert app.editor.text == ""
76 app.editor.text = "tab 3"
77 await pilot.press("home")
78 await pilot.pause()
79 snap_results.append(await app_snapshot(app, "Tab 3 of 3"))
80
81 await pilot.press("ctrl+k")
82 await pilot.pause()
83 await pilot.wait_for_scheduled_animations()
84 assert app.editor_collection.tab_count == 3
85 assert app.editor_collection.active == "tab-1"
86 assert app.editor.text == "tab 1"
87 snap_results.append(await app_snapshot(app, "Tab 1 of 3"))
88
89 await pilot.press("ctrl+k")
90 await pilot.pause()
91 await pilot.wait_for_scheduled_animations()
92 assert app.editor_collection.tab_count == 3
93 assert app.editor_collection.active == "tab-2"
94 assert app.editor.text == "tab 2"
95 snap_results.append(await app_snapshot(app, "Tab 2 of 3"))
96
97 await pilot.press("ctrl+w")
98 await pilot.pause()
99 await pilot.wait_for_scheduled_animations()
100 assert app.editor_collection.tab_count == 2
101 assert app.editor_collection.active == "tab-3"
102 assert app.editor.text == "tab 3"
103 # TODO: bring back this flaky test.
104 # snap_results.append(await app_snapshot(app, "Tab 3 after deleting 2"))
105
106 await pilot.press("ctrl+k")
107 await pilot.pause()
108 await pilot.wait_for_scheduled_animations()
109 assert app.editor_collection.active == "tab-1"
110 assert app.editor.text == "tab 1"
111 snap_results.append(await app_snapshot(app, "Tab 1 of [1,3]"))
112
113 await pilot.press("ctrl+k")
114 await pilot.pause()
115 await pilot.wait_for_scheduled_animations()
116 assert app.editor_collection.active == "tab-3"
117 assert app.editor.text == "tab 3"
118 snap_results.append(await app_snapshot(app, "Tab 3 of [1,3]"))
119
120 assert all(snap_results)
121
122
123 @pytest.mark.asyncio
124 async def test_buffers_keep_their_state(
125 app: Harlequin,
126 wait_for_workers: Callable[[Harlequin], Awaitable[None]],
127 ) -> None:
128 """Switching buffers has to carry everything the editor holds, not just the text."""
129 async with app.run_test(size=(120, 36)) as pilot:
130 await wait_for_workers(app)
131 while app.editor is None:
132 await pilot.pause()
133
134 app.editor.focus()
135 await pilot.press(*"select 1")
136 await pilot.press("ctrl+n")
137 await pilot.pause()
138 await pilot.press(*"select 2")
139 await pilot.press("ctrl+k")
140 await pilot.pause()
141
142 assert app.editor_collection.active == "tab-1"
143 assert app.editor.text == "select 1"
144 assert app.editor.selection == Selection((0, 8), (0, 8))
145
146 # the undo history moves with the buffer: this undoes the typing
147 # in buffer one, not the switch that loaded it.
148 await pilot.press("ctrl+z")
149 await pilot.pause()
150 assert app.editor.text == ""
151 await pilot.press("ctrl+z")
152 await pilot.pause()
153 assert app.editor.text == ""
154
155 await pilot.press("ctrl+k")
156 await pilot.pause()
157 assert app.editor_collection.active == "tab-2"
158 assert app.editor.text == "select 2"
159
160 # a buffer scrolled away from its cursor comes back where it was,
161 # instead of snapping to the cursor.
162 assert app.editor.text_input is not None
163 app.editor.text = "\n".join(f"select {i}" for i in range(100))
164 await pilot.press("ctrl+down", "ctrl+down", "ctrl+down")
165 await pilot.pause()
166 scrolled_to = app.editor.text_input.scroll_offset
167 assert scrolled_to.y > 0
168 assert app.editor.selection == Selection((0, 0), (0, 0))
169
170 await pilot.press("ctrl+k")
171 await pilot.pause()
172 await pilot.press("ctrl+k")
173 await pilot.pause()
174 assert app.editor_collection.active == "tab-2"
175 assert app.editor.text_input.scroll_offset == scrolled_to
176
177
178 @pytest.mark.flaky
179 @pytest.mark.asyncio
180 async def test_word_autocomplete(
181 app_all_adapters: Harlequin,
182 app_snapshot: Callable[..., Awaitable[bool]],
183 wait_for_workers: Callable[[Harlequin], Awaitable[None]],
184 transaction_button_visible: Callable[[Harlequin], bool],
185 ) -> None:
186 app = app_all_adapters
187 snap_results: List[bool] = []
188 async with app.run_test() as pilot:
189 await wait_for_workers(app)
190 while app.editor is None or app.editor_collection.word_completer is None:
191 await pilot.pause()
192
193 # we need to let the data catalog load the root's children
194 while (
195 app.data_catalog.database_tree.loading
196 or not app.data_catalog.database_tree.root.children
197 ):
198 await pilot.pause()
199
200 app.editor.focus()
201
202 await pilot.press("s")
203 await pilot.pause()
204 await wait_for_workers(app)
205 await pilot.pause()
206 await pilot.wait_for_scheduled_animations()
207 snap_results.append(await app_snapshot(app, "s"))
208
209 await pilot.press("e")
210 await pilot.pause()
211 await wait_for_workers(app)
212 await pilot.pause()
213 await pilot.wait_for_scheduled_animations()
214 snap_results.append(await app_snapshot(app, "se"))
215
216 await pilot.press("l")
217 await pilot.pause()
218 await wait_for_workers(app)
219 await pilot.pause()
220 await pilot.wait_for_scheduled_animations()
221 snap_results.append(await app_snapshot(app, "sel"))
222
223 await pilot.press("backspace")
224 await pilot.pause()
225 await wait_for_workers(app)
226 await pilot.pause()
227 await pilot.wait_for_scheduled_animations()
228 snap_results.append(await app_snapshot(app, "se again"))
229
230 await pilot.press("l")
231 await pilot.pause()
232 await wait_for_workers(app)
233 await pilot.pause()
234 await pilot.wait_for_scheduled_animations()
235 await pilot.press("enter")
236 await pilot.pause()
237 await wait_for_workers(app)
238 await pilot.pause()
239 await pilot.wait_for_scheduled_animations()
240 snap_results.append(await app_snapshot(app, "submitted"))
241
242 if not (transaction_button_visible(app)):
243 assert all(snap_results)
244
245
246 @pytest.mark.skipif(
247 sys.platform == "win32", reason="Initial snapshot very flaky on windows."
248 )
249 @pytest.mark.flaky
250 @pytest.mark.asyncio
251 async def test_member_autocomplete(
252 app_small_duck: Harlequin,
253 app_snapshot: Callable[..., Awaitable[bool]],
254 wait_for_workers: Callable[[Harlequin], Awaitable[None]],
255 expand_catalog_node: Callable[..., Awaitable[None]],
256 ) -> None:
257 app = app_small_duck
258 snap_results: List[bool] = []
259 async with app.run_test() as pilot:
260 await wait_for_workers(app)
261
262 # we need to expand the data catalog to load items into the completer
263 while (
264 app.data_catalog.database_tree.loading
265 or not app.data_catalog.database_tree.root.children
266 ):
267 await pilot.pause()
268 for db_node in app.data_catalog.database_tree.root.children:
269 await expand_catalog_node(pilot, db_node)
270 await wait_for_workers(app)
271 for schema_node in db_node.children:
272 await expand_catalog_node(pilot, schema_node)
273 await wait_for_workers(app)
274 # the relations are on screen now, so the catalog prefetches their
275 # columns; wait for those to reach the member completer.
276 await pilot.pause(1)
277
278 # now the completer should be populated
279 while app.editor is None or app.editor_collection.member_completer is None:
280 await pilot.pause()
281
282 app.editor.text = '"drivers"'
283 app.editor.selection = Selection((0, 9), (0, 9))
284 app.editor.focus()
285
286 await pilot.press("full_stop")
287 await pilot.pause()
288 await wait_for_workers(app)
289 await pilot.pause()
290 await pilot.wait_for_scheduled_animations()
291 snap_results.append(await app_snapshot(app, "driver members"))
292
293 await pilot.press("quotation_mark")
294 await pilot.pause()
295 await wait_for_workers(app)
296 await pilot.pause()
297 await pilot.wait_for_scheduled_animations()
298 snap_results.append(await app_snapshot(app, "with quote"))
299
300 await pilot.press("enter")
301 await pilot.pause()
302 await wait_for_workers(app)
303 await pilot.pause()
304 await pilot.wait_for_scheduled_animations()
305 snap_results.append(await app_snapshot(app, "submitted"))
306
307 assert all(snap_results)
308
309
310 @pytest.mark.asyncio
311 async def test_footer_inputs(
312 app: Harlequin,
313 wait_for_workers: Callable[[Harlequin], Awaitable[None]],
314 app_snapshot: Callable[..., Awaitable[bool]],
315 ) -> None:
316 snap_results: List[bool] = []
317 async with app.run_test() as pilot:
318 await wait_for_workers(app)
319
320 while app.editor is None:
321 await pilot.pause()
322
323 assert app.editor is not None
324 assert app.editor.text_input is not None
325 app.editor.text = "select 1"
326
327 await pilot.press("ctrl+o")
328 await pilot.pause()
329 snap_results.append(await app_snapshot(app, "Open Input visible"))
330
331 await pilot.press("ctrl+s")
332 await pilot.pause()
333 snap_results.append(await app_snapshot(app, "Save Input visible"))
334
335 await pilot.press("escape")
336 await pilot.pause(0.1)
337 snap_results.append(await app_snapshot(app, "No Input visible"))
338
339 await pilot.press("ctrl+f")
340 await pilot.pause()
341 snap_results.append(await app_snapshot(app, "Find Input visible"))
342
343 await pilot.press("escape")
344 await pilot.pause()
345
346 await pilot.press("ctrl+g")
347 await pilot.pause()
348 snap_results.append(await app_snapshot(app, "Goto Input visible"))
349
350 assert all(snap_results)
351
352
353 @pytest.mark.asyncio
354 async def test_selected_queries(
355 app: Harlequin,
356 wait_for_workers: Callable[[Harlequin], Awaitable[None]],
357 ) -> None:
358 """Regression test for #929: the queries at the cursor or selection are
359 returned once each, in the order they appear in the buffer."""
360 create = "create table foo (a int);"
361 insert = "insert into foo values (1);"
362 select = "select * from foo;"
363 drop = "drop table foo;"
364 async with app.run_test() as pilot:
365 await wait_for_workers(app)
366
367 while app.editor is None:
368 await pilot.pause()
369
370 assert app.editor.text_input is not None
371 assert app.editor.text_input.is_syntax_aware
372 app.editor.text = f"{create}\n{insert}\n{select}\n{drop}\n"
373 await pilot.pause()
374
375 # tree-sitter does not capture the semicolons in buffer order
376 assert find_separators(app.editor.text) == [
377 (0, 25),
378 (1, 27),
379 (2, 18),
380 (3, 15),
381 ]
382
383 # the whole buffer
384 app.editor.selection = Selection((0, 0), (4, 0))
385 assert app.editor.selected_queries() == [create, insert, select, drop]
386
387 # a reverse selection is the same as a forward one
388 app.editor.selection = Selection((4, 0), (0, 0))
389 assert app.editor.selected_queries() == [create, insert, select, drop]
390
391 # a selection that partially covers two queries runs both of them
392 app.editor.selection = Selection((1, 5), (2, 5))
393 assert app.editor.selected_queries() == [insert, select]
394
395 # a cursor inside a query runs only that query
396 for row, query in enumerate([create, insert, select, drop]):
397 app.editor.selection = Selection((row, 3), (row, 3))
398 assert app.editor.selected_queries() == [query]
399
400 # a cursor just after a semicolon runs the query it terminates,
401 # not the one that follows it
402 app.editor.selection = Selection((1, 27), (1, 27))
403 assert app.editor.selected_queries() == [insert]
404
405 # a cursor at the start of a query runs that query
406 app.editor.selection = Selection((2, 0), (2, 0))
407 assert app.editor.selected_queries() == [select]
408
409 # a cursor in the trailing whitespace runs the last query
410 app.editor.selection = Selection((4, 0), (4, 0))
411 assert app.editor.selected_queries() == [drop]
412
413 # a semicolon in a string literal does not separate queries
414 app.editor.text = "select 'a;b'"
415 await pilot.pause()
416 app.editor.selection = Selection((0, 0), (0, 0))
417 assert app.editor.selected_queries() == ["select 'a;b'"]
418
419
420 @pytest.mark.asyncio
421 async def test_symbol_scan_failure_warns_once_per_failure_streak(
422 app: Harlequin,
423 wait_for_workers: Callable[[Harlequin], Awaitable[None]],
424 monkeypatch: pytest.MonkeyPatch,
425 ) -> None:
426 """A failed symbol scan warns instead of crashing the app.
427
428 Regression test for #1117: read_symbols used Textual's default
429 exit_on_error=True, so a buffer the scanner couldn't parse (or any bug in
430 the scanner) took the whole app down with it. The failure warns once per
431 streak -- repeated failures on the same buffer stay quiet until a scan
432 succeeds again.
433 """
434 WARNING = "Harlequin could not read this buffer's identifiers."
435 outcomes: list[str] = ["fail", "fail", "ok", "fail"]
436 # the editor schedules a scan of the buffer shortly after mounting; it
437 # would cancel (exclusive group) whichever direct scan below it landed on,
438 # so drop that handler from the registry before the app mounts.
439 monkeypatch.setitem(CodeEditor._decorated_handlers, TextArea.Changed, [])
440
441 def flaky_scan(text: str) -> BufferSymbols:
442 outcome = outcomes.pop(0)
443 if outcome == "fail":
444 raise RuntimeError("symbol scan boom")
445 return real_find_symbols(text)
446
447 def warning_count() -> int:
448 return len(
449 [
450 notification
451 for notification in list(app._notifications)
452 if notification.severity == "warning"
453 and notification.message == WARNING
454 ]
455 )
456
457 async with app.run_test() as pilot:
458 await wait_for_workers(app)
459 while app.editor is None:
460 await pilot.pause()
461 editor = app.editor
462 assert editor is not None
463 monkeypatch.setattr("harlequin.components.code_editor.find_symbols", flaky_scan)
464
465 # the first failure of a streak warns ...
466 with pytest.raises(WorkerFailed):
467 await editor.read_symbols("select 1").wait()
468 await pilot.pause()
469 assert warning_count() == 1
470
471 # ... a repeated failure on the same buffer does not
472 with pytest.raises(WorkerFailed):
473 await editor.read_symbols("select 1").wait()
474 await pilot.pause()
475 assert warning_count() == 1
476
477 # a successful scan resets the streak
478 await editor.read_symbols("select 1").wait()
479 for _ in range(20):
480 if not editor._symbol_scan_failed:
481 break
482 await pilot.pause(0.05)
483 assert not editor._symbol_scan_failed
484 assert warning_count() == 1
485
486 # so the next failure warns again
487 with pytest.raises(WorkerFailed):
488 await editor.read_symbols("select 1").wait()
489 await pilot.pause()
490 assert warning_count() == 2
491
492 # and the app never saw an unhandled exception
493 assert app._exception is None
494 assert app.is_running
495
496
497 @pytest.mark.asyncio
498 async def test_selected_queries_split_on_character_columns(
499 app: Harlequin,
500 wait_for_workers: Callable[[Harlequin], Awaitable[None]],
501 ) -> None:
502 """Regression test for #1015: the editor and `harlequin.statements` split
503 at the same place.
504
505 tree-sitter reports columns in bytes, and the editor used to feed one
506 straight to `get_text_range()`, which wants characters. Any non-ASCII
507 before a semicolon shifted the cut, and both halves came out as syntax
508 errors -- this split into "select '日本語';select" and "2".
509 """
510 async with app.run_test() as pilot:
511 await wait_for_workers(app)
512
513 while app.editor is None:
514 await pilot.pause()
515
516 app.editor.text = "select '日本語';select 2"
517 await pilot.pause()
518 app.editor.selection = Selection((0, 0), (0, 22))
519 assert app.editor.selected_queries() == ["select '日本語';", "select 2"]
520 assert app.editor.selected_queries() == [s.sql for s in split(app.editor.text)]
521
522
523 @pytest.mark.asyncio
524 async def test_selected_queries_do_not_split_dollar_quoted_bodies(
525 app: Harlequin,
526 wait_for_workers: Callable[[Harlequin], Awaitable[None]],
527 ) -> None:
528 """Regression test for #1019: the editor and `harlequin.statements` agree,
529 and neither treats a semicolon inside `$$ ... $$` as a separator."""
530 async with app.run_test() as pilot:
531 await wait_for_workers(app)
532
533 while app.editor is None:
534 await pilot.pause()
535
536 script = "create function f() as $$ select 1; $$; select 2"
537 app.editor.text = script
538 await pilot.pause()
539 app.editor.selection = Selection((0, 0), (0, len(script)))
540 assert app.editor.selected_queries() == [
541 "create function f() as $$ select 1; $$;",
542 "select 2",
543 ]
544 assert app.editor.selected_queries() == [s.sql for s in split(app.editor.text)]
545
546
547 @pytest.mark.asyncio
548 async def test_buffer_symbols_reach_the_completers(
549 app: Harlequin,
550 wait_for_workers: Callable[[Harlequin], Awaitable[None]],
551 ) -> None:
552 async with app.run_test() as pilot:
553 await wait_for_workers(app)
554 while app.editor is None or app.editor_collection.word_completer is None:
555 await pilot.pause()
556 word_completer = app.editor_collection.word_completer
557 member_completer = app.editor_collection.member_completer
558 assert member_completer is not None
559
560 assert not word_completer("my_c")
561 assert not member_completer("t.my_c")
562
563 app.editor.text = (
564 "with my_cte as (select 1 as my_col) select t.my_col from my_cte t"
565 )
566
567 # the editor re-reads the buffer on a timer
568 for _ in range(20):
569 if word_completer("my_c"):
570 break
571 await pilot.pause(0.1)
572
573 assert word_completer("my_c")[0] == (("my_cte", "buf"), "my_cte")
574 assert member_completer("t.my_c") == [(("t.my_col", "buf"), "t.my_col")]
575
576 # symbols belong to the buffer they were read from, so switching tabs
577 # away from that query drops them, and switching back brings them back.
578 first_buffer_id = app.editor_collection.active
579 assert first_buffer_id is not None
580 await app.editor_collection.action_new_buffer()
581 for _ in range(20):
582 if not word_completer("my_c"):
583 break
584 await pilot.pause(0.1)
585
586 assert not word_completer("my_c")
587
588 app.editor_collection.tabs.active = first_buffer_id
589 for _ in range(20):
590 if word_completer("my_c"):
591 break
592 await pilot.pause(0.1)
593
594 assert word_completer("my_c")[0] == (("my_cte", "buf"), "my_cte")
595
596
597 @pytest.mark.asyncio
598 async def test_numbers_do_not_open_the_completion_list(
599 app: Harlequin,
600 wait_for_workers: Callable[[Harlequin], Awaitable[None]],
601 ) -> None:
602 """A number leaves the list closed, so enter inserts a newline."""
603 async with app.run_test() as pilot:
604 await wait_for_workers(app)
605 while app.editor is None or app.editor_collection.word_completer is None:
606 await pilot.pause()
607
608 app.editor_collection.word_completer.update_buffer_symbols(
609 BufferSymbols(names=("foo_1",))
610 )
611 app.editor.focus()
612
613 await pilot.press("1")
614 await pilot.pause()
615 await wait_for_workers(app)
616 await pilot.pause()
617 assert not app.editor.completion_list.is_open
618
619 await pilot.press("enter")
620 await pilot.pause()
621 assert app.editor.text == "1\n"