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.
141 lines
4.4 KiB
Python
141 lines
4.4 KiB
Python
"""Fixtures for testing the entire package.
|
|
|
|
The ORM related fixtures are placed here too as some integration tests
|
|
in the CLI layer need access to the database.
|
|
"""
|
|
|
|
import os
|
|
import random
|
|
import typing as t
|
|
|
|
import pytest
|
|
import sqlalchemy as sa
|
|
from alembic import command as alembic_cmd
|
|
from alembic import config as alembic_config
|
|
from factory import random as factory_random
|
|
from sqlalchemy import orm
|
|
|
|
from velofy import config as pkg_config
|
|
from velofy import db
|
|
|
|
|
|
# Register the shared fixtures in `tests.db.fake_data` here,
|
|
# as tests/console/, tests/db/, and tests/forecasts/ use them
|
|
pytest_plugins = [
|
|
"tests.db.fake_data.fixture_makers",
|
|
"tests.db.fake_data.static_fixtures",
|
|
]
|
|
|
|
|
|
# The TESTING environment variable is set
|
|
# in pyproject.toml in pytest's config section.
|
|
if not os.getenv("TESTING"):
|
|
msg = "Tests must be executed with TESTING set in the environment"
|
|
raise RuntimeError(msg)
|
|
|
|
if not pkg_config.TESTING:
|
|
msg = "The testing configuration was not loaded"
|
|
raise RuntimeError(msg)
|
|
|
|
|
|
@pytest.fixture(scope="session", params=["all_at_once", "sequentially"])
|
|
def db_connection(request):
|
|
"""Create all tables given the ORM models.
|
|
|
|
The tables are put into a distinct PostgreSQL schema
|
|
that is removed after all tests are over.
|
|
|
|
The database connection used to do that is yielded.
|
|
|
|
There are two modes for this fixture:
|
|
|
|
- "all_at_once": build up the tables all at once with MetaData.create_all()
|
|
- "sequentially": build up the tables sequentially with `alembic upgrade head`
|
|
|
|
This ensures that Alembic's migration files are consistent.
|
|
"""
|
|
# We need a fresh database connection for each of the two `params`.
|
|
# Otherwise, the first test of the parameter run second will fail.
|
|
engine = sa.create_engine(pkg_config.DATABASE_URI)
|
|
connection = engine.connect()
|
|
|
|
if request.param == "all_at_once":
|
|
with connection.begin():
|
|
connection.execute(sa.text(f"CREATE SCHEMA {pkg_config.CLEAN_SCHEMA};"))
|
|
db.Base.metadata.create_all(connection)
|
|
else:
|
|
cfg = alembic_config.Config("alembic.ini")
|
|
alembic_cmd.upgrade(cfg, "head")
|
|
|
|
try:
|
|
yield connection
|
|
|
|
finally:
|
|
# Close the connection first: this rolls back any transaction a test
|
|
# may have left open, which would otherwise swallow the `DROP`s below.
|
|
connection.close()
|
|
|
|
with engine.begin() as cleanup:
|
|
cleanup.execute(sa.text(f"DROP SCHEMA {pkg_config.CLEAN_SCHEMA} CASCADE;"))
|
|
|
|
if request.param == "sequentially":
|
|
tmp_alembic_version = (
|
|
f"{pkg_config.ALEMBIC_TABLE}_{pkg_config.CLEAN_SCHEMA}"
|
|
)
|
|
cleanup.execute(
|
|
sa.text(
|
|
f"DROP TABLE {pkg_config.ALEMBIC_TABLE_SCHEMA}.{tmp_alembic_version};", # noqa:E501
|
|
),
|
|
)
|
|
|
|
engine.dispose()
|
|
|
|
|
|
@pytest.fixture
|
|
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.
|
|
transaction = db_connection.begin()
|
|
|
|
# Create a session bound to the same connection as the `transaction`.
|
|
# Using any other session would not result in the roll back.
|
|
# Commits inside a test case then only release a savepoint.
|
|
session = orm.Session(bind=db_connection, join_transaction_mode="create_savepoint")
|
|
|
|
# Monkey patch the package's global `session` object,
|
|
# which is used heavily in the code base.
|
|
monkeypatch.setattr(db, "session", session)
|
|
|
|
try:
|
|
yield session
|
|
|
|
finally:
|
|
session.close()
|
|
|
|
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."""
|
|
random.seed(42)
|
|
factory_random.reseed_random(42)
|