"""Shared test fixtures.""" from collections.abc import Generator from glob import glob from os import path from sqlite3 import Connection as SQLite3Connection from unittest import mock import pytest from sqlalchemy import create_engine, event, text from sqlalchemy.engine import Engine from sqlalchemy.pool import StaticPool _SCHEMA_SQL = """ CREATE TABLE report_run ( id INTEGER PRIMARY KEY AUTOINCREMENT, uuid TEXT NOT NULL, period_ids TEXT, trigger_type TEXT, snowflake_query_id TEXT ); CREATE TABLE report ( id INTEGER PRIMARY KEY AUTOINCREMENT, report_run_id INTEGER, collaborator_id INTEGER, status TEXT DEFAULT 'REQUESTED' ); CREATE TABLE collaborator ( id INTEGER PRIMARY KEY AUTOINCREMENT, performance_rights INTEGER DEFAULT 0 ); CREATE TABLE split ( id INTEGER PRIMARY KEY AUTOINCREMENT, collaborator_id INTEGER, identifier TEXT, split_rate REAL, rate_type TEXT DEFAULT 'NET', split_type_id INTEGER ); """ @event.listens_for(Engine, "connect") def _set_sqlite_pragma(dbapi_conn, _connection_record): if isinstance(dbapi_conn, SQLite3Connection): dbapi_conn.execute("PRAGMA foreign_keys=ON") @pytest.fixture(scope="session", autouse=True) def test_db() -> Generator[Engine, None, None]: """In-memory SQLite DB seeded with test data. Patches trigger.utils.rds.engine.""" engine = create_engine( "sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool, ) with engine.begin() as conn: for stmt in _SCHEMA_SQL.strip().split(";"): stmt = stmt.strip() if stmt: conn.execute(text(stmt)) for seed_path in sorted(glob(path.join(path.dirname(__file__), "seed/*.sql"))): with open(seed_path) as f: for stmt in f.read().strip().split(";"): stmt = stmt.strip() if stmt: conn.execute(text(stmt)) with mock.patch("trigger.utils.rds.engine", engine): yield engine