diff --git a/src/velofy/db/connection.py b/src/velofy/db/connection.py index 1e29d81..0e4a8cf 100644 --- a/src/velofy/db/connection.py +++ b/src/velofy/db/connection.py @@ -1,13 +1,12 @@ """Provide connection utils for the ORM layer. -This module defines a fully configured `session` object -to be used as a global within the `velofy` package. - -If a database is not guaranteed to be available, it is set to `None`. -That is the case on the CI server. +The `session` object is used as a global within the `velofy` package, +like `db.session` in Flask-SQLAlchemy: It is a proxy to one session per thread. +The engine and the session are only created on first use; +so, importing the package does not require a database. """ -import os +import functools import typing as t import sqlalchemy as sa @@ -16,10 +15,18 @@ from sqlalchemy import orm import velofy -if os.getenv("TESTING"): - # Placeholder that the test fixtures replace - session: orm.Session = None # type: ignore[assignment] +@functools.cache +def get_engine() -> sa.Engine: + """The engine for the configured `DATABASE_URI`, created on first use.""" + return sa.create_engine(t.cast(str, velofy.config.DATABASE_URI)) -else: # pragma: no cover - engine = sa.create_engine(t.cast(str, velofy.config.DATABASE_URI)) - session = orm.Session(bind=engine) + +# `scoped_session()` accepts any callable creating sessions +# while its type stubs expect a `sessionmaker` +# => The lambda defers creating the engine to first use. +session: orm.scoped_session[orm.Session] = orm.scoped_session( + t.cast( + "orm.sessionmaker[orm.Session]", + lambda: orm.Session(bind=get_engine()), + ), +) diff --git a/tests/conftest.py b/tests/conftest.py index 754f515..31f8442 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -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.""" diff --git a/tests/db/test_connection.py b/tests/db/test_connection.py new file mode 100644 index 0000000..73275a0 --- /dev/null +++ b/tests/db/test_connection.py @@ -0,0 +1,23 @@ +"""Test the connection utils in `velofy.db.connection`.""" + +import sqlalchemy as sa + +from velofy import config as pkg_config +from velofy.db import connection + + +def test_engine_uses_the_configured_database(): + """`get_engine()` connects to the `DATABASE_URI`.""" + result = connection.get_engine() + + assert result.url == sa.make_url(pkg_config.DATABASE_URI) + + +def test_session_is_bound_to_the_engine(): + """The `session` proxy creates sessions bound to `get_engine()`.""" + session = connection.session() + + try: + assert session.get_bind() is connection.get_engine() + finally: + connection.session.remove()