diff --git a/README.rst b/README.rst index 4615139f..f47ba2b9 100644 --- a/README.rst +++ b/README.rst @@ -207,6 +207,23 @@ You can create additional fixtures using factories: # Async client fixture (requires pytest-postgresql[async], pytest-asyncio >= 1.4) postgresql_my_async = factories.postgresql_async('postgresql_my_proc') +The client fixtures accept a ``connection_kwargs`` mapping, which is forwarded +to ``psycopg.connect`` (or ``AsyncConnection.connect``) when opening the test +connection. This is useful for options like ``row_factory``: + +.. code-block:: python + + import psycopg.rows + + # Return dict rows instead of tuples + postgresql_dict_rows = factories.postgresql( + 'postgresql_my_proc', + connection_kwargs={'row_factory': psycopg.rows.dict_row}, + ) + +Keys that control the connection identity (``dbname``, ``user``, ``host``, +``port``) are managed by the fixtures and rejected in ``connection_kwargs``. + .. note:: Each process fixture can be configured independently through factory arguments. diff --git a/newsfragments/1418.feature.rst b/newsfragments/1418.feature.rst new file mode 100644 index 00000000..b4ba8bbc --- /dev/null +++ b/newsfragments/1418.feature.rst @@ -0,0 +1 @@ +Allow passing extra keyword arguments through to ``psycopg.connect`` in the ``postgresql`` and ``postgresql_async`` factories via a new ``connection_kwargs`` parameter, e.g. to set ``row_factory``. Identity keys managed by the fixtures (``dbname``, ``user``, ``host``, ``port``) are rejected so the janitor-managed connection isolation stays intact. diff --git a/pytest_postgresql/factories/client.py b/pytest_postgresql/factories/client.py index 8f90ae55..299b82c8 100644 --- a/pytest_postgresql/factories/client.py +++ b/pytest_postgresql/factories/client.py @@ -17,7 +17,7 @@ # along with pytest-postgresql. If not, see . """Fixture factory for postgresql client.""" -from typing import AsyncIterator, Callable, Iterator, cast +from typing import Any, AsyncIterator, Callable, Iterator, cast import psycopg import pytest @@ -35,6 +35,28 @@ pytest_asyncio = _pytest_asyncio +# Connection identity keys managed by the janitor/fixtures. Allowing them in +# ``connection_kwargs`` would let the client connect to a different database or +# server than the one the janitor creates and drops, breaking fixture isolation. +_RESERVED_CONNECTION_KWARGS = ("dbname", "user", "host", "port") + + +def _reject_reserved_connection_kwargs(connection_kwargs: dict[str, Any] | None) -> None: + """Raise ValueError if connection_kwargs tries to override the managed connection identity. + + :param connection_kwargs: caller-supplied extra connect kwargs, if any + :raises ValueError: if any reserved identity key is present + """ + if not connection_kwargs: + return + reserved = sorted(key for key in _RESERVED_CONNECTION_KWARGS if key in connection_kwargs) + if reserved: + raise ValueError( + f"connection_kwargs must not override the janitor-managed connection identity: " + f"{', '.join(reserved)}. These keys are set by the fixture; override the " + f"process/noproc fixture instead if a different target is needed." + ) + def _postgresql_async_unavailable_stub() -> Callable[[pytest.FixtureRequest], AsyncIterator[AsyncConnection]]: """Return a sync fixture stub that raises when pytest-asyncio is missing or too old.""" @@ -58,6 +80,7 @@ def postgresql( process_fixture_name: str, dbname: str | None = None, isolation_level: "psycopg.IsolationLevel | None" = None, + connection_kwargs: dict[str, Any] | None = None, ) -> Callable[[pytest.FixtureRequest], Iterator[Connection]]: """Return connection fixture factory for PostgreSQL. @@ -65,8 +88,12 @@ def postgresql( :param dbname: database name :param isolation_level: optional postgresql isolation level defaults to server's default + :param connection_kwargs: optional additional keyword arguments passed + through to ``psycopg.connect`` for the client + connection, e.g. ``{"row_factory": psycopg.rows.dict_row}`` :returns: function which makes a connection to postgresql """ + _reject_reserved_connection_kwargs(connection_kwargs) @pytest.fixture def postgresql_factory(request: pytest.FixtureRequest) -> Iterator[Connection]: @@ -97,14 +124,17 @@ def postgresql_factory(request: pytest.FixtureRequest) -> Iterator[Connection]: if config.drop_test_database: janitor.drop() with janitor: - db_connection: Connection = psycopg.connect( - dbname=pg_db, - user=pg_user, - password=pg_password, - host=pg_host, - port=pg_port, - options=pg_options, - ) + connect_kwargs: dict[str, Any] = { + "dbname": pg_db, + "user": pg_user, + "password": pg_password, + "host": pg_host, + "port": pg_port, + "options": pg_options, + } + if connection_kwargs: + connect_kwargs.update(connection_kwargs) + db_connection: Connection = psycopg.connect(**connect_kwargs) try: if isolation_level is not None: db_connection.isolation_level = isolation_level @@ -119,6 +149,7 @@ def postgresql_async( process_fixture_name: str, dbname: str | None = None, isolation_level: "psycopg.IsolationLevel | None" = None, + connection_kwargs: dict[str, Any] | None = None, ) -> Callable[[pytest.FixtureRequest], AsyncIterator[AsyncConnection]]: """Return async connection fixture factory for PostgreSQL. @@ -128,8 +159,13 @@ def postgresql_async( :param dbname: database name :param isolation_level: optional postgresql isolation level defaults to server's default + :param connection_kwargs: optional additional keyword arguments passed + through to ``AsyncConnection.connect`` for the + client connection :returns: function which makes an async connection to postgresql """ + _reject_reserved_connection_kwargs(connection_kwargs) + if not supports_loop_factories(pytest_asyncio): return _postgresql_async_unavailable_stub() @@ -162,14 +198,17 @@ async def postgresql_async_factory(request: pytest.FixtureRequest) -> AsyncItera if config.drop_test_database: await janitor.drop() async with janitor: - db_connection: AsyncConnection = await AsyncConnection.connect( - dbname=pg_db, - user=pg_user, - password=pg_password, - host=pg_host, - port=pg_port, - options=pg_options, - ) + connect_kwargs: dict[str, Any] = { + "dbname": pg_db, + "user": pg_user, + "password": pg_password, + "host": pg_host, + "port": pg_port, + "options": pg_options, + } + if connection_kwargs: + connect_kwargs.update(connection_kwargs) + db_connection: AsyncConnection = await AsyncConnection.connect(**connect_kwargs) try: if isolation_level is not None: await db_connection.set_isolation_level(isolation_level) diff --git a/tests/conftest.py b/tests/conftest.py index f3b334ae..c0001235 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -3,6 +3,8 @@ import os from pathlib import Path +import psycopg.rows + from pytest_postgresql import factories pytest_plugins = ["pytester"] @@ -15,6 +17,16 @@ postgresql_proc2 = factories.postgresql_proc(port=None, load=[TEST_SQL_FILE, TEST_SQL_FILE2]) postgresql2 = factories.postgresql("postgresql_proc2", dbname="test-db") +postgresql2_dict_row = factories.postgresql( + "postgresql_proc2", + dbname="test-db", + connection_kwargs={"row_factory": psycopg.rows.dict_row}, +) postgresql_load_1 = factories.postgresql("postgresql_proc2") postgresql2_async = factories.postgresql_async("postgresql_proc2", dbname="test-db") +postgresql2_dict_row_async = factories.postgresql_async( + "postgresql_proc2", + dbname="test-db", + connection_kwargs={"row_factory": psycopg.rows.dict_row}, +) postgresql_load_1_async = factories.postgresql_async("postgresql_proc2") diff --git a/tests/test_postgresql.py b/tests/test_postgresql.py index 38337f59..97a7cb9b 100644 --- a/tests/test_postgresql.py +++ b/tests/test_postgresql.py @@ -39,6 +39,38 @@ def test_two_postgreses(postgresql: Connection, postgresql2: Connection) -> None cur.close() +@pytest.mark.parametrize("reserved_key", ["dbname", "user", "host", "port"]) +def test_connection_kwargs_rejects_managed_identity(reserved_key: str) -> None: + """connection_kwargs must not override the janitor-managed connection identity.""" + from pytest_postgresql import factories + + with pytest.raises(ValueError, match=reserved_key): + factories.postgresql("postgresql_proc", connection_kwargs={reserved_key: "override"}) + + +@pytest.mark.parametrize("reserved_key", ["dbname", "user", "host", "port"]) +def test_connection_kwargs_rejects_managed_identity_async(reserved_key: str) -> None: + """Async factory rejects the same managed identity keys.""" + from pytest_postgresql import factories + + with pytest.raises(ValueError, match=reserved_key): + factories.postgresql_async("postgresql_proc", connection_kwargs={reserved_key: "override"}) + + +def test_connection_kwargs_passed_through(postgresql2_dict_row: Connection) -> None: + """Test that connection_kwargs are forwarded to psycopg.connect. + + ``row_factory`` is a psycopg.connect keyword argument, so passing it + through the factory should change how rows are returned. + """ + cur = postgresql2_dict_row.cursor() + cur.execute("SELECT * FROM test_load;") + row = cur.fetchone() + cur.close() + + assert isinstance(row, dict) + + def test_postgres_load_two_files(postgresql_load_1: Connection) -> None: """Check postgresql fixture can load two files.""" cur = postgresql_load_1.cursor() @@ -92,6 +124,16 @@ async def test_two_postgreses_async(postgresql_async: AsyncConnection, postgresq await postgresql2_async.commit() +@pytest.mark.asyncio +async def test_connection_kwargs_passed_through_async(postgresql2_dict_row_async: AsyncConnection) -> None: + """Test that connection_kwargs are forwarded to AsyncConnection.connect.""" + async with postgresql2_dict_row_async.cursor() as cur: + await cur.execute(SELECT_Q) + row = await cur.fetchone() + + assert isinstance(row, dict) + + @pytest.mark.asyncio async def test_postgres_load_two_files_async(postgresql_load_1_async: AsyncConnection) -> None: """Async check postgresql fixture can load two files."""