Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions newsfragments/1418.feature.rst
Original file line number Diff line number Diff line change
@@ -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.
73 changes: 56 additions & 17 deletions pytest_postgresql/factories/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
# along with pytest-postgresql. If not, see <http://www.gnu.org/licenses/>.
"""Fixture factory for postgresql client."""

from typing import AsyncIterator, Callable, Iterator, cast
from typing import Any, AsyncIterator, Callable, Iterator, cast

import psycopg
import pytest
Expand All @@ -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: "

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these are not a janitor-managed, but fixture/plugin;s managed kwargs. They either come from process (which is not a janitor) or fixture factory argument in case of dbname

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."""
Expand All @@ -58,15 +80,20 @@ 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.

:param process_fixture_name: name of the process fixture
: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]:
Expand Down Expand Up @@ -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)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
db_connection: Connection = psycopg.connect(**connect_kwargs)
try:
if isolation_level is not None:
db_connection.isolation_level = isolation_level
Expand All @@ -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.

Expand All @@ -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()

Expand Down Expand Up @@ -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)
Expand Down
12 changes: 12 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import os
from pathlib import Path

import psycopg.rows

from pytest_postgresql import factories

pytest_plugins = ["pytester"]
Expand All @@ -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")
42 changes: 42 additions & 0 deletions tests/test_postgresql.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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."""
Expand Down
Loading