Files
WebApi/tests/conftest.py

57 lines
1.9 KiB
Python

"""Shared test wiring.
`persistance.settings.settings` is a module-level singleton and the
`persistance.db.get_<domain>_engine` functions are `@lru_cache`d, so changing
`<DOMAIN>_DATABASE_URL` alone has no effect once an engine exists.
`wire_domain` resets all three (env var, singleton, cache).
"""
import os
import tempfile
from pathlib import Path
import pytest
# Tests use throwaway SQLite files as "arbitrary SQL sources"; production
# excludes sqlite by default (see webapi.imports.connectors.sql_policy).
os.environ.setdefault("WEBAPI_SQL_ALLOWED_DIALECTS", "sqlite,mysql,mariadb,postgresql,mssql,oracle")
@pytest.fixture(scope="module")
def wire_domain():
"""Factory fixture: `wire_domain("cacu")` points the domain at a fresh temp
SQLite file for this module and returns its path. Temp files are removed
when the module finishes."""
created_paths: list[str] = []
def _wire(domain: str) -> str:
db_path = tempfile.NamedTemporaryFile(suffix=".db", delete=False).name
url = f"sqlite:///{db_path}"
os.environ[f"{domain.upper()}_DATABASE_URL"] = url
from persistance import db as persistance_db
from persistance import settings as persistance_settings
setattr(persistance_settings.settings, f"{domain}_database_url", url)
getattr(persistance_db, f"get_{domain}_engine").cache_clear()
created_paths.append(db_path)
_migrate(domain)
return db_path
yield _wire
for path in created_paths:
os.unlink(path)
def _migrate(domain: str) -> None:
"""Builds the schema with the Alembic migrations rather than
`metadata.create_all`, so tests run against the deployed schema and a
broken migration fails the suite."""
from alembic import command
from alembic.config import Config
import persistance
ini = Path(persistance.__file__).parent / domain / "alembic.ini"
command.upgrade(Config(str(ini)), "head")