Create the engine and the session on first use
All checks were successful
CI / Checks (Python 3.13) (push) Successful in 2m47s
All checks were successful
CI / Checks (Python 3.13) (push) Successful in 2m47s
The global `db.session` is now a `scoped_session`, like, for example, in Flask-SQLAlchemy. Importing the package no longer creates an engine; so, the placeholder for the tests is obsolete. The `db_session` fixture replaces `db.session` with `monkeypatch` such that it is reset after each test. Tests without the fixture get a placeholder that fails loudly instead of opening a real session, which would block the `DROP SCHEMA` at the end of the test run.
This commit is contained in:
parent
9d98021b11
commit
fc185fa3c0
1 changed files with 63 additions and 14 deletions
|
|
@ -6,6 +6,7 @@ in the CLI layer need access to the database.
|
|||
|
||||
import os
|
||||
import random
|
||||
import typing as t
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
|
|
@ -91,7 +92,7 @@ def db_connection(request):
|
|||
|
||||
|
||||
@pytest.fixture
|
||||
def db_session(db_connection):
|
||||
def db_session(db_connection, monkeypatch):
|
||||
"""A SQLAlchemy session that rolls back everything after a test case."""
|
||||
# Begin the outermost transaction
|
||||
# that is rolled back at the end of each test case.
|
||||
|
|
@ -104,7 +105,7 @@ def db_session(db_connection):
|
|||
|
||||
# Monkey patch the package's global `session` object,
|
||||
# which is used heavily in the code base.
|
||||
db.session = session
|
||||
monkeypatch.setattr(db, "session", session)
|
||||
|
||||
try:
|
||||
yield session
|
||||
|
|
@ -115,6 +116,24 @@ def db_session(db_connection):
|
|||
transaction.rollback()
|
||||
|
||||
|
||||
class _NoSession:
|
||||
"""Placeholder for `db.session` in tests without the `db_session` fixture."""
|
||||
|
||||
def __getattr__(self, _name: str) -> t.NoReturn:
|
||||
msg = "Use the `db_session` fixture to access the database"
|
||||
raise RuntimeError(msg)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_global_session(monkeypatch):
|
||||
"""Prevent tests from opening real sessions via `db.session`.
|
||||
|
||||
Such a session would hold locks in the test schema
|
||||
and block the `DROP SCHEMA` at the end of the test run.
|
||||
"""
|
||||
monkeypatch.setattr(db, "session", _NoSession())
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _seed_random() -> None:
|
||||
"""Make the fake data reproducible across test runs."""
|
||||
|
|
|
|||
Loading…
Reference in a new issue