Skip to content

prefer-pytest-fixture-injection

Request shared database-pool setup through a pytest fixture.

Why

Calling a shared conftest pool helper during initial test setup bypasses an explicit pytest fixture dependency, per-test caching, and fixture overrides, even when the helper already centralizes allocation. This preference does not establish a resource leak.

Fix

Request one function-scoped fixture visible to the test. Declare required setup ordering as fixture dependencies and preserve initial pool state and cleanup ownership. An unopened allocation fixture should return the pool without opening or closing it when application lifespan owns that lifecycle. Use yield teardown only when the fixture owns cleanup; keep factories for variants or fresh instances.

Examples

Before — flagged Application-owned lifecycle still uses a fixture dependency
tests/conftest.py
from psycopg_pool import AsyncConnectionPool
def pool() -> AsyncConnectionPool[object]:
return AsyncConnectionPool[object](open=False)
tests/test_app.py
from tests.conftest import pool
async def test_app():
resource = pool()
app = Application(resource)
async with lifespan(app):
assert not resource.closed
assert resource.closed
After — preferred An unopened fixture leaves open and close ownership with the application
tests/conftest.py
import pytest
from psycopg_pool import AsyncConnectionPool
@pytest.fixture
def pool() -> AsyncConnectionPool[object]:
return AsyncConnectionPool[object](open=False)
tests/test_app.py
async def test_app(pool):
app = Application(pool)
assert pool.closed
async with lifespan(app):
assert not pool.closed
assert pool.closed
Before — flagged A test calls shared generic pool setup
tests/conftest.py
from psycopg_pool import ConnectionPool
def pool() -> ConnectionPool[object]:
return ConnectionPool[object](open=False)
tests/test_app.py
from tests.conftest import pool
def test_app():
resource = pool()
app = Application(resource)
assert app
After — preferred A test requests its shared resource
tests/conftest.py
import pytest
from psycopg_pool import ConnectionPool
@pytest.fixture
def pool() -> ConnectionPool[object]:
return ConnectionPool[object](open=False)
tests/test_app.py
def test_app(pool):
app = Application(pool)
assert app