Debian Codegraph @

tests/test_adapter.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import sys
4 from datetime import date, datetime
5
6 import psycopg
7 import pytest
8 from harlequin.adapter import HarlequinAdapter, HarlequinConnection, HarlequinCursor
9 from harlequin.catalog import Catalog, CatalogItem
10 from harlequin.exception import HarlequinConnectionError, HarlequinQueryError
11 from textual_fastdatatable.backend import create_backend
12
13 from harlequin_postgres.adapter import (
14 HarlequinPostgresAdapter,
15 HarlequinPostgresConnection,
16 )
17
18 if sys.version_info < (3, 10):
19 from importlib_metadata import entry_points
20 else:
21 from importlib.metadata import entry_points
22
23 TEST_DB_CONN = "postgresql://postgres:for-testing@localhost:5432"
24
25
26 def test_plugin_discovery() -> None:
27 PLUGIN_NAME = "postgres"
28 eps = entry_points(group="harlequin.adapter")
29 assert eps[PLUGIN_NAME]
30 adapter_cls = eps[PLUGIN_NAME].load()
31 assert issubclass(adapter_cls, HarlequinAdapter)
32 assert adapter_cls == HarlequinPostgresAdapter
33
34
35 def test_connect() -> None:
36 conn = HarlequinPostgresAdapter(conn_str=(TEST_DB_CONN,)).connect()
37 assert isinstance(conn, HarlequinConnection)
38
39
40 def test_init_extra_kwargs() -> None:
41 assert HarlequinPostgresAdapter(
42 conn_str=(TEST_DB_CONN,), foo=1, bar="baz"
43 ).connect()
44
45
46 @pytest.mark.parametrize(
47 "conn_str",
48 [
49 ("foo",),
50 ("host=foo",),
51 ("postgresql://admin:pass@foo:5432/db",),
52 ],
53 )
54 def test_connect_raises_connection_error(conn_str: tuple[str]) -> None:
55 with pytest.raises(HarlequinConnectionError):
56 _ = HarlequinPostgresAdapter(conn_str=conn_str, connect_timeout=0.1).connect()
57
58
59 @pytest.mark.parametrize(
60 "conn_str,options,expected",
61 [
62 (("",), {}, "localhost:5432/postgres"),
63 (("host=foo",), {}, "foo:5432/postgres"),
64 (("postgresql://foo",), {}, "foo:5432/postgres"),
65 (("postgresql://foo",), {"port": 5431}, "foo:5431/postgres"),
66 (("postgresql://foo/mydb",), {"port": 5431}, "foo:5431/mydb"),
67 (("postgresql://admin:pass@foo/mydb",), {"port": 5431}, "foo:5431/mydb"),
68 (("postgresql://admin:pass@foo:5431/mydb",), {}, "foo:5431/mydb"),
69 ],
70 )
71 def test_connection_id(
72 conn_str: tuple[str], options: dict[str, int | float | str | None], expected: str
73 ) -> None:
74 adapter = HarlequinPostgresAdapter(
75 conn_str=conn_str,
76 **options, # type: ignore[arg-type]
77 )
78 assert adapter.connection_id == expected
79
80
81 def test_get_catalog(connection: HarlequinPostgresConnection) -> None:
82 catalog = connection.get_catalog()
83 assert isinstance(catalog, Catalog)
84 assert catalog.items
85 assert isinstance(catalog.items[0], CatalogItem)
86
87
88 def test_get_schemas_includes_user_schema_named_pgmq(
89 connection: HarlequinPostgresConnection,
90 ) -> None:
91 connection.execute("create schema pgmq")
92 schemas = connection._get_schemas("test")
93 assert ("pgmq",) in schemas
94
95
96 def test_get_completions(connection: HarlequinPostgresConnection) -> None:
97 completions = connection.get_completions()
98 test_labels = ["atomic", "greatest", "point_right", "autovacuum"]
99 filtered = list(filter(lambda x: x.label in test_labels, completions))
100 assert len(filtered) == 4
101 value_filtered = list(filter(lambda x: x.value in test_labels, completions))
102 assert len(value_filtered) == 4
103
104
105 def test_execute_ddl(connection: HarlequinPostgresConnection) -> None:
106 cur = connection.execute("create table foo (a int)")
107 assert cur is None
108
109
110 def test_execute_select(connection: HarlequinPostgresConnection) -> None:
111 cur = connection.execute("select 1 as a")
112 assert isinstance(cur, HarlequinCursor)
113 assert cur.columns() == [("a", "#")]
114 data = cur.fetchall()
115 backend = create_backend(data)
116 assert backend.column_count == 1
117 assert backend.row_count == 1
118
119
120 def test_execute_select_dupe_cols(connection: HarlequinPostgresConnection) -> None:
121 cur = connection.execute("select 1 as a, 2 as a, 3 as a")
122 assert isinstance(cur, HarlequinCursor)
123 assert len(cur.columns()) == 3
124 data = cur.fetchall()
125 backend = create_backend(data)
126 assert backend.column_count == 3
127 assert backend.row_count == 1
128
129
130 def test_set_limit(connection: HarlequinPostgresConnection) -> None:
131 cur = connection.execute("select 1 as a union all select 2 union all select 3")
132 assert isinstance(cur, HarlequinCursor)
133 cur = cur.set_limit(2)
134 assert isinstance(cur, HarlequinCursor)
135 data = cur.fetchall()
136 backend = create_backend(data)
137 assert backend.column_count == 1
138 assert backend.row_count == 2
139
140
141 def test_execute_raises_query_error(connection: HarlequinPostgresConnection) -> None:
142 with pytest.raises(HarlequinQueryError):
143 _ = connection.execute("sel;")
144
145
146 def test_inf_timestamps(connection: HarlequinPostgresConnection) -> None:
147 cur = connection.execute(
148 """select
149 'infinity'::date,
150 'infinity'::timestamp,
151 'infinity'::timestamptz,
152 '-infinity'::date,
153 '-infinity'::timestamp,
154 '-infinity'::timestamptz
155 """
156 )
157 assert cur is not None
158 data = cur.fetchall()
159 assert data == [
160 (
161 date.max,
162 datetime.max,
163 datetime.max,
164 date.min,
165 datetime.min,
166 datetime.min,
167 )
168 ]
169
170
171 def test_closed_conn_raises_right_error(
172 connection: HarlequinPostgresConnection,
173 ) -> None:
174 connection._main_conn.close()
175
176 with pytest.raises(HarlequinQueryError):
177 connection.execute("select 1")
178
179
180 def test_implements_read_only() -> None:
181 assert HarlequinPostgresAdapter.IMPLEMENTS_READ_ONLY is True
182
183
184 def test_read_only_defaults_to_false() -> None:
185 adapter = HarlequinPostgresAdapter(conn_str=(TEST_DB_CONN,))
186 assert adapter.read_only is False
187 conn = adapter.connect()
188 assert conn.read_only is False
189 conn.close()
190
191
192 def test_read_only_is_not_a_conn_info_option() -> None:
193 """
194 read_only is not a libpq conninfo key, so it must never be passed to psycopg.
195 """
196 adapter = HarlequinPostgresAdapter(conn_str=(TEST_DB_CONN,), read_only=True)
197 assert adapter.read_only is True
198 assert "read_only" not in adapter.options
199 assert adapter.connection_id == "localhost:5432/postgres"
200
201 conn = adapter.connect()
202 # the conninfo passed to psycopg is unchanged; read-only is applied to each
203 # connection after it is opened.
204 assert "read_only" not in conn.conn_info
205 assert "options" not in conn.conn_info
206 conn.close()
207
208
209 def test_read_only_connection_can_read(
210 read_only_connection: HarlequinPostgresConnection,
211 ) -> None:
212 assert read_only_connection.read_only is True
213 cur = read_only_connection.execute("select * from foo")
214 assert isinstance(cur, HarlequinCursor)
215 assert cur.fetchall() == [(1,)]
216
217
218 @pytest.mark.parametrize(
219 "query",
220 [
221 "insert into foo values (2)",
222 "update foo set a = 2",
223 "delete from foo",
224 "create table bar (a int)",
225 "drop table foo",
226 ],
227 )
228 def test_read_only_connection_rejects_writes(
229 read_only_connection: HarlequinPostgresConnection, query: str
230 ) -> None:
231 with pytest.raises(HarlequinQueryError):
232 read_only_connection.execute(query)
233
234
235 def test_read_only_survives_transaction_mode_toggle(
236 read_only_connection: HarlequinPostgresConnection,
237 ) -> None:
238 assert read_only_connection.transaction_mode.label == "Auto"
239 for _ in range(4):
240 with pytest.raises(HarlequinQueryError):
241 read_only_connection.execute("insert into foo values (2)")
242 read_only_connection.toggle_transaction_mode()
243
244
245 def test_read_only_applies_to_pooled_connections(
246 read_only_connection: HarlequinPostgresConnection,
247 ) -> None:
248 # the catalog and completions run on connections from the pool, not on the
249 # main connection.
250 conn = read_only_connection.pool.getconn()
251 try:
252 with conn.cursor() as cur:
253 cur.execute("select current_setting('default_transaction_read_only')")
254 assert cur.fetchone() == ("on",)
255 with pytest.raises(psycopg.errors.ReadOnlySqlTransaction):
256 cur.execute("create table baz (a int)")
257 conn.rollback()
258 finally:
259 read_only_connection.pool.putconn(conn)
260
261
262 def test_read_only_connection_get_catalog(
263 read_only_connection: HarlequinPostgresConnection,
264 ) -> None:
265 catalog = read_only_connection.get_catalog()
266 assert isinstance(catalog, Catalog)
267 assert catalog.items
268
269
270 def test_read_only_refuses_to_connect_if_server_does_not_enforce(
271 monkeypatch: pytest.MonkeyPatch,
272 ) -> None:
273 """
274 If the read-only setting does not make it to the server, connecting must fail
275 loudly, rather than hand back a connection that would happily write.
276 """
277 monkeypatch.setattr(
278 HarlequinPostgresConnection,
279 "_configure_connection",
280 lambda self, conn: None,
281 )
282 with pytest.raises(HarlequinConnectionError):
283 HarlequinPostgresAdapter(conn_str=(TEST_DB_CONN,), read_only=True).connect()
284
285
286 def test_read_only_enforced_in_autocommit_session(
287 read_only_connection: HarlequinPostgresConnection,
288 ) -> None:
289 """
290 psycopg's Connection.read_only does not affect autocommit sessions, since
291 psycopg never issues a BEGIN for them; the session characteristic does.
292 """
293 assert read_only_connection.transaction_mode.label == "Auto"
294 assert read_only_connection._main_conn.autocommit is True
295 with pytest.raises(HarlequinQueryError):
296 read_only_connection.execute("insert into foo values (2)")