Debian Codegraph @

tests/unit_tests/test_symbols.py

raw
1 from __future__ import annotations
2
3 import pytest
4
5 from harlequin.autocomplete import BufferSymbols, find_symbols
6
7 # (name, sql, expected names, expected members). The name is the pytest id.
8 CORPUS: list[tuple[str, str, list[str], list[tuple[str, str]]]] = [
9 ("empty", "", [], []),
10 ("whitespace only", " \n\t ", [], []),
11 ("keywords only", "select 1", [], []),
12 ("one table", "select * from my_table", ["my_table"], []),
13 (
14 "columns and aliases",
15 "select foo as bar, baz from t",
16 ["foo", "bar", "baz", "t"],
17 [],
18 ),
19 (
20 "qualified table",
21 "select * from my_db.my_schema.my_table",
22 ["my_db", "my_schema", "my_table"],
23 [("my_db", "my_schema"), ("my_schema", "my_table")],
24 ),
25 (
26 "aliased columns",
27 "select t.a, t.b from my_table t",
28 ["t", "a", "b", "my_table"],
29 [("t", "a"), ("t", "b")],
30 ),
31 (
32 "cte",
33 "with my_cte as (select 1 as n) select my_cte.n from my_cte",
34 ["my_cte", "n"],
35 [("my_cte", "n")],
36 ),
37 (
38 "quoted identifiers",
39 'select t."Mixed Case" from "My Table" t',
40 ["t", "Mixed Case", "My Table"],
41 [("t", "Mixed Case")],
42 ),
43 # the user is mid-edit far more often than not, so the parse has to keep
44 # going past whatever they have not finished typing.
45 ("unterminated member", "select * from my_table t where t.", ["my_table", "t"], []),
46 (
47 "half-typed clause",
48 "select a, from my_table",
49 ["a", "from", "my_table"],
50 [],
51 ),
52 (
53 "several statements",
54 "select a from one; select b from two",
55 ["a", "one", "b", "two"],
56 [],
57 ),
58 # a symbol is worth offering once, under the spelling it first appeared in.
59 (
60 "repeated, in mixed case",
61 "select FOO from t union all select foo from t",
62 ["FOO", "t"],
63 [],
64 ),
65 # semicolons and words inside these belong to one node, so nothing in them
66 # is an identifier.
67 ("string literal", "select 'not_a_symbol' from t", ["t"], []),
68 ("comment", "select a from t -- not_a_symbol\n", ["a", "t"], []),
69 ]
70
71
72 @pytest.mark.parametrize(
73 "sql,expected_names,expected_members",
74 [pytest.param(*case[1:], id=case[0]) for case in CORPUS],
75 )
76 def test_find_symbols(
77 sql: str, expected_names: list[str], expected_members: list[tuple[str, str]]
78 ) -> None:
79 assert find_symbols(sql) == BufferSymbols(
80 names=tuple(expected_names), members=tuple(expected_members)
81 )