| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import sys |
| 4 |
from typing import Callable, Generator |
| 5 |
|
| 6 |
import psycopg |
| 7 |
import pytest |
| 8 |
|
| 9 |
from harlequin_postgres.adapter import ( |
| 10 |
HarlequinPostgresAdapter, |
| 11 |
HarlequinPostgresConnection, |
| 12 |
) |
| 13 |
|
| 14 |
if sys.version_info < (3, 10): |
| 15 |
pass |
| 16 |
else: |
| 17 |
pass |
| 18 |
|
| 19 |
TEST_DB_CONN = "postgresql://postgres:for-testing@localhost:5432" |
| 20 |
|
| 21 |
|
| 22 |
@pytest.fixture |
| 23 |
def connection() -> Generator[HarlequinPostgresConnection, None, None]: |
| 24 |
pgconn = psycopg.connect(conninfo=TEST_DB_CONN, dbname="postgres") |
| 25 |
pgconn.autocommit = True |
| 26 |
cur = pgconn.cursor() |
| 27 |
cur.execute("drop database if exists test;") |
| 28 |
cur.execute("create database test;") |
| 29 |
cur.close() |
| 30 |
pgconn.close() |
| 31 |
conn = HarlequinPostgresAdapter( |
| 32 |
conn_str=(f"{TEST_DB_CONN}",), dbname="test" |
| 33 |
).connect() |
| 34 |
yield conn |
| 35 |
conn.close() |
| 36 |
pgconn = psycopg.connect(conninfo=TEST_DB_CONN, dbname="postgres") |
| 37 |
pgconn.autocommit = True |
| 38 |
cur = pgconn.cursor() |
| 39 |
cur.execute("drop database if exists test;") |
| 40 |
cur.close() |
| 41 |
pgconn.close() |
| 42 |
|
| 43 |
|
| 44 |
@pytest.fixture |
| 45 |
def connect_again( |
| 46 |
connection: HarlequinPostgresConnection, |
| 47 |
) -> Generator[Callable[..., HarlequinPostgresConnection], None, None]: |
| 48 |
"""Opens more connections to the same test database, closed at teardown. |
| 49 |
|
| 50 |
A connection resolves its search path when it connects, so a test that |
| 51 |
changes the search path needs a new one. |
| 52 |
""" |
| 53 |
connections: list[HarlequinPostgresConnection] = [] |
| 54 |
|
| 55 |
def _connect(dsn_params: str = "") -> HarlequinPostgresConnection: |
| 56 |
conn_str = f"{TEST_DB_CONN}/?{dsn_params}" if dsn_params else TEST_DB_CONN |
| 57 |
conn = HarlequinPostgresAdapter(conn_str=(conn_str,), dbname="test").connect() |
| 58 |
connections.append(conn) |
| 59 |
return conn |
| 60 |
|
| 61 |
yield _connect |
| 62 |
|
| 63 |
for conn in connections: |
| 64 |
conn.close() |
| 65 |
|
| 66 |
|
| 67 |
@pytest.fixture |
| 68 |
def read_only_connection( |
| 69 |
connection: HarlequinPostgresConnection, |
| 70 |
) -> Generator[HarlequinPostgresConnection, None, None]: |
| 71 |
""" |
| 72 |
A read-only connection to the same (read-write provisioned) test database. |
| 73 |
""" |
| 74 |
connection.execute("create table foo (a int)") |
| 75 |
connection.execute("insert into foo values (1)") |
| 76 |
ro_conn = HarlequinPostgresAdapter( |
| 77 |
conn_str=(f"{TEST_DB_CONN}",), dbname="test", read_only=True |
| 78 |
).connect() |
| 79 |
yield ro_conn |
| 80 |
ro_conn.close() |