Debian Codegraph @

tests/unit_tests/test_navigate.py

raw
1 """The path grammar, and the walk it drives.
2
3 Two things are asserted here that nothing else can: that a path spelled by a
4 listing is a path `parse()` reads back as the same segments -- which is what
5 lets an agent walk a catalog by copying a cell out of the last answer -- and
6 that the walk costs one `fetch_children()` per level and no more.
7
8 The catalog is hand-built rather than a database's: what varies between adapters
9 is how deep it goes and what a level is called, and a fake is the only way to
10 assert against a shape no bundled adapter has.
11 """
12
13 from __future__ import annotations
14
15 import itertools
16 from dataclasses import dataclass, field
17 from typing import Iterator, Sequence
18
19 import pytest
20
21 from harlequin.adapter import HarlequinConnection, HarlequinCursor
22 from harlequin.catalog import (
23 Catalog,
24 CatalogItem,
25 CatalogSearchKind,
26 CatalogSearchResult,
27 InteractiveCatalogItem,
28 )
29 from harlequin.exception import HarlequinCatalogPathError, HarlequinQueryError
30 from harlequin.navigate import (
31 CatalogPath,
32 list_children,
33 resolve,
34 search,
35 spell,
36 )
37
38 FETCHES: list[str] = []
39 """Every `fetch_children()` the walk made, in order. One entry is one round trip."""
40
41
42 @dataclass
43 class FakeItem(InteractiveCatalogItem["FakeConnection"]):
44 """A node that records the times it was asked to fetch."""
45
46 to_fetch: list["FakeItem"] = field(default_factory=list)
47
48 def fetch_children(self) -> Sequence[CatalogItem]:
49 FETCHES.append(self.label)
50 return self.to_fetch
51
52
53 def item(label: str, *children: FakeItem, type_label: str = "t") -> FakeItem:
54 return FakeItem(
55 qualified_identifier=label,
56 query_name=f'"{label}"',
57 label=label,
58 type_label=type_label,
59 to_fetch=list(children),
60 )
61
62
63 class FakeConnection(HarlequinConnection):
64 """Just enough connection for the walk: a catalog, and a count of asks."""
65
66 def __init__(self, *items: CatalogItem) -> None:
67 super().__init__()
68 self.items = list(items)
69 self.catalog_calls = 0
70
71 def execute(self, query: str) -> HarlequinCursor | None:
72 raise AssertionError("the walk ran SQL")
73
74 def get_catalog(self) -> Catalog:
75 self.catalog_calls += 1
76 return Catalog(items=list(self.items))
77
78
79 class SearchingConnection(FakeConnection):
80 """A connection whose catalog can be searched, and records the asks."""
81
82 def __init__(self, *items: CatalogItem) -> None:
83 super().__init__(*items)
84 self.searches: list[tuple[str, str]] = []
85
86 def search_catalog(
87 self, term: str, kind: CatalogSearchKind = "all"
88 ) -> list[CatalogSearchResult]:
89 self.searches.append((term, kind))
90 return [
91 CatalogSearchResult(item=item("orders"), parents=("mydb", "analytics")),
92 CatalogSearchResult(item=item("orders"), parents=("otherdb", "public")),
93 ]
94
95
96 @pytest.fixture(autouse=True)
97 def fetches() -> Iterator[list[str]]:
98 FETCHES.clear()
99 yield FETCHES
100 FETCHES.clear()
101
102
103 @pytest.fixture
104 def connection() -> FakeConnection:
105 return FakeConnection(
106 item(
107 "mydb",
108 item(
109 "analytics",
110 item("orders", item("id", type_label="##")),
111 item("order_items"),
112 type_label="sch",
113 ),
114 item("empty", type_label="sch"),
115 type_label="db",
116 )
117 )
118
119
120 # --- the grammar -------------------------------------------------------------
121
122
123 @pytest.mark.parametrize(
124 "text,segments",
125 [
126 (None, ()),
127 ("", ()),
128 (" ", ()),
129 ("mydb", ("mydb",)),
130 ("mydb.analytics", ("mydb", "analytics")),
131 ('mydb."my.schema"', ("mydb", "my.schema")),
132 ('"quoted ""name"""', ('quoted "name"',)),
133 ('mydb."has*star"', ("mydb", "has*star")),
134 ('""', ("",)),
135 ],
136 )
137 def test_a_path_is_dotted_segments(text: str | None, segments: tuple[str, ...]) -> None:
138 parsed = CatalogPath.parse(text)
139 assert parsed.segments == segments
140 assert parsed.glob is None
141
142
143 @pytest.mark.parametrize("text", ["mydb.ord*", "ord*", "mydb.analytics.?d"])
144 def test_a_trailing_wildcard_is_a_filter_not_a_segment(text: str) -> None:
145 parsed = CatalogPath.parse(text)
146 assert parsed.glob == text.rsplit(".", 1)[-1]
147 assert parsed.segments == tuple(text.split(".")[:-1])
148
149
150 @pytest.mark.parametrize("text", ["*.orders", "mydb.*.orders", "my?b.analytics"])
151 def test_an_interior_wildcard_is_refused(text: str) -> None:
152 """It cannot be answered without fetching every level it could match, so it
153 is refused rather than quietly walked."""
154 with pytest.raises(HarlequinCatalogPathError, match="wildcard"):
155 CatalogPath.parse(text)
156
157
158 @pytest.mark.parametrize("text", ["mydb.", ".mydb", "mydb..analytics"])
159 def test_an_empty_segment_is_refused(text: str) -> None:
160 with pytest.raises(HarlequinCatalogPathError, match="empty path segment"):
161 CatalogPath.parse(text)
162
163
164 def test_an_unterminated_quote_is_refused() -> None:
165 with pytest.raises(HarlequinCatalogPathError, match="never closes"):
166 CatalogPath.parse('mydb."analytics')
167
168
169 @pytest.mark.parametrize("text", ['"a"b', 'a"b"c', 'schema."quoted rel"*'])
170 def test_a_segment_quoted_in_part_is_refused(text: str) -> None:
171 """A segment is quoted whole or not at all.
172
173 Concatenating the two would leave one `quoted` flag describing a segment
174 that was half quoted -- and `"rel"*` would then ask for a wildcard the
175 quotes have already said is a character.
176 """
177 with pytest.raises(HarlequinCatalogPathError, match="quotes part of"):
178 CatalogPath.parse(text)
179
180
181 @pytest.mark.parametrize(
182 "segments",
183 [
184 ("mydb", "analytics"),
185 ("my.db", "analytics"),
186 ('a "quoted" one', "b"),
187 ("has*star",),
188 ("",),
189 ],
190 )
191 def test_a_spelled_path_parses_back_to_the_same_segments(
192 segments: tuple[str, ...],
193 ) -> None:
194 """The property the `path` column depends on: a cell from one listing is
195 the argument that lists that item's children."""
196 assert CatalogPath.parse(spell(segments)).segments == segments
197
198
199 NASTY = ["a", ".", '"', "`", "[", "]", "*", "?", " ", "\\", "'"]
200 """Every character that could break a splitter, plus one that could not."""
201
202
203 def test_every_label_a_catalog_can_hand_us_round_trips() -> None:
204 """`spell()` and `parse()` are inverses, over labels nobody would type.
205
206 An adapter's label is whatever the database holds, so a label this pair
207 disagrees about is a row whose `path` column names something the next
208 invocation cannot reach.
209 """
210 for size in (1, 2, 3):
211 for combination in itertools.product(NASTY, repeat=size):
212 label = "".join(combination)
213 assert CatalogPath.parse(spell([label])).segments == (label,), label
214
215
216 def test_two_such_labels_round_trip_together() -> None:
217 """The same, where a dot between the two is the thing being escaped."""
218 labels = ["".join(pair) for pair in itertools.product(NASTY, repeat=2)]
219 for first, second in itertools.product(labels, repeat=2):
220 parsed = CatalogPath.parse(spell([first, second])).segments
221 assert parsed == (first, second), (first, second)
222
223
224 @pytest.mark.parametrize("label", ["my`table", "[bracketed]", "'quoted'"])
225 def test_another_dialects_quoting_is_a_label_like_any_other(label: str) -> None:
226 """A backtick or a bracket is a character in a name here, not quoting.
227
228 Treating either as a quote would make a MySQL table named ``my`table``
229 unreachable, which is the cost of accepting more than one spelling.
230 """
231 connection = FakeConnection(item(label))
232 listing = list_children(connection, CatalogPath.parse(spell([label])))
233 assert listing.parent is not None
234 assert listing.parent.label == label
235
236
237 @pytest.mark.parametrize("typed", ["`mydb`", "[mydb]"])
238 def test_a_path_quoted_for_a_database_says_what_to_type_instead(
239 connection: FakeConnection, typed: str
240 ) -> None:
241 """So an agent that reached for its dialect's quoting is told the spelling
242 this takes, rather than left with a path that names nothing."""
243 with pytest.raises(HarlequinCatalogPathError, match="Did you mean mydb"):
244 list_children(connection, CatalogPath.parse(typed))
245
246
247 def test_a_plain_segment_is_spelled_without_quotes() -> None:
248 """A path a person reads should look like the one they would have typed."""
249 assert spell(["mydb", "analytics", "orders"]) == "mydb.analytics.orders"
250
251
252 # --- the walk ----------------------------------------------------------------
253
254
255 def test_the_top_level_is_the_catalog(connection: FakeConnection) -> None:
256 listing = list_children(connection, CatalogPath.parse(None))
257 assert listing.parent is None
258 assert [child.label for child in listing.items] == ["mydb"]
259 assert connection.catalog_calls == 1
260
261
262 def test_a_listing_is_one_round_trip_per_segment_plus_one(
263 connection: FakeConnection,
264 ) -> None:
265 """The cost this module promises, and the reason there is no `--depth`."""
266 listing = list_children(connection, CatalogPath.parse("mydb.analytics"))
267 assert listing.parent is not None
268 assert listing.parent.label == "analytics"
269 assert [child.label for child in listing.items] == ["orders", "order_items"]
270
271 # one for the catalog, and one per segment walked past -- and nothing else
272 assert connection.catalog_calls == 1
273 assert FETCHES == ["mydb", "analytics"]
274
275
276 def test_listing_a_relation_is_describing_it(connection: FakeConnection) -> None:
277 listing = list_children(connection, CatalogPath.parse("mydb.analytics.orders"))
278 assert [(child.label, child.type_label) for child in listing.items] == [
279 ("id", "##")
280 ]
281
282
283 def test_a_node_with_no_children_lists_nothing(connection: FakeConnection) -> None:
284 """Zero rows, not an error: an empty schema is an answer."""
285 assert list_children(connection, CatalogPath.parse("mydb.empty")).items == []
286
287
288 def test_a_trailing_wildcard_filters_one_level(connection: FakeConnection) -> None:
289 listing = list_children(connection, CatalogPath.parse("mydb.analytics.order*"))
290 assert [child.label for child in listing.items] == ["orders", "order_items"]
291 # the parent it filtered, not a level below it
292 assert listing.parent is not None
293 assert listing.parent.label == "analytics"
294
295
296 def test_a_wildcard_that_matches_nothing_lists_nothing(
297 connection: FakeConnection,
298 ) -> None:
299 assert list_children(connection, CatalogPath.parse("mydb.z*")).items == []
300
301
302 def test_a_segment_that_names_nothing_says_what_is_there(
303 connection: FakeConnection,
304 ) -> None:
305 """A guessed path is the common case, so the error answers the question."""
306 with pytest.raises(HarlequinCatalogPathError) as excinfo:
307 list_children(connection, CatalogPath.parse("mydb.analytic"))
308 assert "analytic" in excinfo.value.msg
309 assert "Did you mean analytics?" in excinfo.value.msg
310
311
312 def test_a_top_level_miss_says_where_it_looked(connection: FakeConnection) -> None:
313 with pytest.raises(HarlequinCatalogPathError, match="top of the catalog"):
314 list_children(connection, CatalogPath.parse("nope"))
315
316
317 def test_a_miss_under_a_childless_node_says_so(connection: FakeConnection) -> None:
318 with pytest.raises(HarlequinCatalogPathError, match="nothing under it"):
319 list_children(connection, CatalogPath.parse("mydb.empty.orders"))
320
321
322 def test_resolve_fetches_the_ancestors_and_not_the_level(
323 connection: FakeConnection,
324 ) -> None:
325 """`resolve()` is the walk without the listing, and costs one call less."""
326 found = resolve(connection, CatalogPath.parse("mydb.analytics"))
327 assert found is not None and found.label == "analytics"
328 assert FETCHES == ["mydb"]
329
330
331 def test_children_already_loaded_are_not_fetched_again(
332 connection: FakeConnection,
333 ) -> None:
334 """An adapter that hands over a whole subtree is not asked to do it twice."""
335 path = CatalogPath.parse("mydb.analytics")
336 list_children(connection, path)
337 list_children(connection, path)
338 assert FETCHES == ["mydb", "analytics"]
339
340
341 def test_a_plain_catalog_item_has_no_children_to_fetch() -> None:
342 """The degradation path: an adapter whose items are not interactive."""
343 connection = FakeConnection(
344 CatalogItem(
345 qualified_identifier="db", query_name='"db"', label="db", type_label="db"
346 )
347 )
348 assert list_children(connection, CatalogPath.parse("db")).items == []
349
350
351 # --- the search, which is the call a walk cannot serve ------------------------
352
353
354 def test_search_asks_the_adapter_once_and_walks_nothing() -> None:
355 connection = SearchingConnection()
356 found = search(connection, "orders", CatalogPath(), "columns")
357 assert connection.searches == [("orders", "columns")]
358 assert FETCHES == []
359 assert len(found) == 2
360
361
362 def test_a_scope_narrows_the_answer_to_one_subtree(
363 connection: FakeConnection,
364 ) -> None:
365 searching = SearchingConnection(*connection.items)
366 found = search(searching, "orders", CatalogPath.parse("mydb"))
367 assert [result.parents for result in found] == [("mydb", "analytics")]
368
369
370 def test_a_scope_that_names_nothing_says_so_rather_than_finding_nothing() -> None:
371 """The same error `--catalog --path` gives, since it is the same question
372 about the same path."""
373 searching = SearchingConnection()
374 with pytest.raises(HarlequinCatalogPathError, match="top of the catalog"):
375 search(searching, "orders", CatalogPath.parse("nope"))
376 assert searching.searches == []
377
378
379 def test_an_adapter_that_declared_a_search_it_lacks_is_an_error() -> None:
380 """A declaration can be wrong, and the failure is a message rather than a
381 traceback."""
382 connection = FakeConnection()
383 with pytest.raises(HarlequinQueryError, match="does not implement it"):
384 search(connection, "orders", CatalogPath())