|
| 1 | +import typing as t |
| 2 | +import os |
| 3 | + |
| 4 | +import psycopg |
| 5 | +import pytest |
| 6 | + |
| 7 | + |
| 8 | +@pytest.fixture(scope="function") |
| 9 | +def connection_factory() -> t.Callable[[str], psycopg.Connection]: |
| 10 | + def factory(connection_uri: str) -> psycopg.Connection: |
| 11 | + return psycopg.connect(connection_uri) |
| 12 | + return factory |
| 13 | + |
| 14 | + |
| 15 | +@pytest.fixture(scope="function") |
| 16 | +def connection(connection_factory) -> psycopg.Connection: |
| 17 | + return connection_factory(os.getenv("CONNECTION_URI")) |
| 18 | + |
| 19 | + |
| 20 | +def test_connection_uri(): |
| 21 | + """Test that CONNECTION_URI matches EXPECTED_CONNECTION_URI.""" |
| 22 | + |
| 23 | + connection_uri = os.getenv("CONNECTION_URI") |
| 24 | + expected_connection_uri = os.getenv("EXPECTED_CONNECTION_URI") |
| 25 | + assert connection_uri == expected_connection_uri |
| 26 | + |
| 27 | + |
| 28 | +def test_user_permissions(connection: psycopg.Connection): |
| 29 | + """Test that a user can create databases but is not a superuser.""" |
| 30 | + |
| 31 | + with connection: |
| 32 | + record = connection \ |
| 33 | + .execute("SELECT usecreatedb, usesuper FROM pg_user WHERE usename = CURRENT_USER") \ |
| 34 | + .fetchone() |
| 35 | + assert record |
| 36 | + |
| 37 | + usecreatedb, usesuper = record |
| 38 | + assert usecreatedb |
| 39 | + assert not usesuper |
| 40 | + |
| 41 | + |
| 42 | +def test_user_create_insert_select(connection: psycopg.Connection): |
| 43 | + """Test that a user has CRUD permissions in a database.""" |
| 44 | + |
| 45 | + table_name = "test_setup_postgres" |
| 46 | + |
| 47 | + with connection, connection.transaction(force_rollback=True): |
| 48 | + records = connection \ |
| 49 | + .execute(f"CREATE TABLE {table_name}(eggs INTEGER, rice VARCHAR)") \ |
| 50 | + .execute(f"INSERT INTO {table_name}(eggs, rice) VALUES (1, '42')") \ |
| 51 | + .execute(f"SELECT * FROM {table_name}") \ |
| 52 | + .fetchall() |
| 53 | + assert records == [(1, "42")] |
| 54 | + |
| 55 | + |
| 56 | +def test_user_create_drop_database(connection: psycopg.Connection): |
| 57 | + """Test that a user has no permissions to create databases.""" |
| 58 | + |
| 59 | + # CREATE/DROP DATABASE statements don't work within transactions, and with |
| 60 | + # autocommit disabled transactions are created by psycopg automatically. |
| 61 | + connection.autocommit = True |
| 62 | + |
| 63 | + database_name = "foobar42" |
| 64 | + connection.execute(f"CREATE DATABASE {database_name}") |
| 65 | + connection.execute(f"DROP DATABASE {database_name}") |
0 commit comments