Debian Codegraph @

tests/functional_tests/conftest.py

raw
1 import asyncio
2 import sys
3 from contextlib import suppress
4 from typing import Awaitable, Callable
5 from unittest.mock import MagicMock
6
7 import pytest
8 from textual.widgets import Input
9 from textual.worker import WorkerCancelled
10
11 from harlequin.app import Harlequin
12 from harlequin.autocomplete import HarlequinCompletion
13
14
15 @pytest.fixture(autouse=True)
16 def no_cursor_blink(monkeypatch: pytest.MonkeyPatch) -> None:
17 """Freeze every Input's cursor in the visible state.
18
19 Snapshots are captured after a settle delay that is longer than the blink
20 interval, so a blinking cursor makes snapshot tests nondeterministic.
21 Neutering the toggle leaves the pause/restart behavior (and so the blurred
22 state) intact.
23 """
24 monkeypatch.setattr(Input, "_toggle_cursor", lambda _self: None)
25
26
27 @pytest.fixture(autouse=True)
28 def no_use_buffer_cache(
29 monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest
30 ) -> None:
31 if "use_cache" in request.keywords:
32 return
33 monkeypatch.setattr("harlequin.components.code_editor.load_cache", lambda: None)
34 monkeypatch.setattr(
35 "harlequin.components.code_editor.adopt_recovery", lambda: (None, None)
36 )
37 monkeypatch.setattr("harlequin.app.write_editor_cache", lambda *_: None)
38 monkeypatch.setattr("harlequin.app.write_recovery", lambda *_: True)
39 monkeypatch.setattr("harlequin.app.clear_recovery", lambda *_: None)
40
41
42 @pytest.fixture(autouse=True)
43 def no_use_catalog_cache(
44 monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest
45 ) -> None:
46 if "use_cache" in request.keywords:
47 return
48 monkeypatch.setattr("harlequin.app.get_catalog_cache", lambda *_: None)
49 monkeypatch.setattr("harlequin.app.update_catalog_cache", lambda *_, **__: None)
50
51
52 @pytest.fixture(autouse=True)
53 def mock_config_loader(no_discovered_config: None) -> None:
54 """Autouse wrapper over the shared fixture. test_keys_app overrides it."""
55
56
57 @pytest.fixture(autouse=True)
58 def mock_completions(monkeypatch: pytest.MonkeyPatch) -> None:
59 KEYWORDS = [
60 "abort",
61 "all",
62 "alter",
63 "always",
64 "analyze",
65 "and",
66 "as",
67 "asc",
68 "begin",
69 "between",
70 "by",
71 "cascade",
72 "case",
73 "column",
74 "commit",
75 "create",
76 "database",
77 "delete",
78 "desc",
79 "distinct",
80 "drop",
81 "else",
82 "end",
83 "explain",
84 "from",
85 "group",
86 "groups",
87 "having",
88 "in",
89 "inner",
90 "insert",
91 "intersect",
92 "into",
93 "is",
94 "join",
95 "left",
96 "like",
97 "limit",
98 "null",
99 "on",
100 "order",
101 "outer",
102 "over",
103 "partition",
104 "row",
105 "savepoint",
106 "select",
107 "set",
108 "table",
109 "temp",
110 "temporary",
111 "then",
112 "union",
113 "update",
114 "using",
115 "values",
116 "view",
117 "when",
118 "where",
119 "window",
120 ]
121
122 FUNCTIONS = [
123 ("array_select", "fn"),
124 ("count", "agg"),
125 ("greatest", "fn"),
126 ("least", "fn"),
127 ("list_select", "fn"),
128 ("sqrt", "fn"),
129 ("sum", "agg"),
130 ]
131
132 keyword_completions = [
133 HarlequinCompletion(
134 label=kw_name, type_label="kw", value=kw_name, priority=100, context=None
135 )
136 for kw_name in KEYWORDS
137 ]
138
139 function_completions = [
140 HarlequinCompletion(
141 label=label, type_label=type_label, value=label, priority=1000, context=None
142 )
143 for label, type_label in FUNCTIONS
144 ]
145
146 completions = [*keyword_completions, *function_completions]
147 duckdb_completions = [
148 (
149 completion.label,
150 completion.type_label,
151 completion.priority,
152 completion.context,
153 )
154 for completion in completions
155 ]
156 monkeypatch.setattr(
157 "harlequin_sqlite.adapter.get_completion_data",
158 lambda *_: completions,
159 raising=True,
160 )
161 monkeypatch.setattr(
162 "harlequin_duckdb.adapter.get_completion_data",
163 lambda *_: duckdb_completions,
164 raising=True,
165 )
166
167
168 @pytest.fixture
169 def mock_pyperclip(monkeypatch: pytest.MonkeyPatch) -> MagicMock:
170 mock = MagicMock()
171 mock.determine_clipboard.return_value = mock.copy, mock.paste
172
173 def set_paste(x: str) -> None:
174 mock.paste.return_value = x
175
176 mock.copy.side_effect = set_paste
177 monkeypatch.setattr("textual_textarea.text_editor.pyperclip", mock)
178
179 return mock
180
181
182 _WORKER_HANDOFFS = 8
183 """How many times a worker may hand off to another before the wait gives up.
184
185 The query path is two (`_execute_query` then `_fetch_data`); the ceiling is
186 there so a worker that restarts itself cannot hang the suite.
187 """
188
189 _PUMP_TICKS = 4
190 """Event-loop turns to give the message pump between passes."""
191
192
193 @pytest.fixture
194 def wait_for_workers() -> Callable[[Harlequin], Awaitable[None]]:
195 async def wait_for_filtered_workers(app: Harlequin) -> None:
196 """Wait until no worker but the catalog's background loader is running.
197
198 In a loop, because a worker's result is delivered as a message and the
199 handler for it starts the next one: `_execute_query` posts
200 `QueriesExecuted`, whose handler starts `_fetch_data`. Waiting on the
201 set once returns before the second one exists, which is only invisible
202 while every worker is fast.
203 """
204 for _ in range(_WORKER_HANDOFFS):
205 filtered_workers = [
206 w for w in app.workers if w.name != "_database_tree_background_loader"
207 ]
208 if not filtered_workers:
209 return
210 with suppress(WorkerCancelled):
211 await app.workers.wait_for_complete(filtered_workers)
212 # let the message carrying the result be handled, so that a worker
213 # it starts is in the set the next pass reads
214 for _ in range(_PUMP_TICKS):
215 await asyncio.sleep(0)
216
217 return wait_for_filtered_workers
218
219
220 @pytest.fixture
221 def transaction_button_visible() -> Callable[[Harlequin], bool]:
222 def fn(app: Harlequin) -> bool:
223 """
224 Skip snapshot checks for versions of that app showing the autocommit button.
225 """
226 return (
227 sys.version_info >= (3, 12) and "Sqlite" in app.adapter.__class__.__name__
228 )
229
230 return fn