150 lines
5.3 KiB
Python
150 lines
5.3 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).
|
|
|
|
The `base`/`base_de` family (below `ANIO`) is for `webapi.orchestration`:
|
|
una base del dominio por prueba, migrada por el paso `migrate`, con el staging
|
|
sintético del kit.
|
|
"""
|
|
import os
|
|
import tempfile
|
|
from dataclasses import dataclass, replace
|
|
from importlib import import_module
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
from sqlalchemy import create_engine
|
|
from sqlmodel import Session
|
|
|
|
from webapi.orchestration.reference.rules import RUTA_PARAMETROS
|
|
from webapi.orchestration import Context, run
|
|
from webapi.orchestration.connection import point_to
|
|
from webapi.orchestration.repositories import repositories_of
|
|
|
|
# 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")
|
|
# The import log and the indicator queue write files; keep them out of the tree.
|
|
_STATE_DIR = tempfile.mkdtemp(prefix="webapi-tests-")
|
|
os.environ.setdefault("WEBAPI_REPORT_DIR", os.path.join(_STATE_DIR, "reportes"))
|
|
os.environ.setdefault("INDICADORES_DIR", os.path.join(_STATE_DIR, "indicadores"))
|
|
|
|
ANIO = 2025
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Base:
|
|
"""El proyecto, su contexto (con los repositorios de Persistance) y su dominio en Persistance."""
|
|
|
|
proyecto: str
|
|
ctx: Context
|
|
dominio: object
|
|
motor: object
|
|
|
|
def run(self, *pasos: str, **cambios) -> dict:
|
|
"""Corre estos pasos (en el orden del ciclo) con el contexto cambiado. Devuelve el resumen de cada una."""
|
|
return {p.name: p.summary for p in run(replace(self.ctx, **cambios), only=pasos)}
|
|
|
|
def staging(self):
|
|
"""Una sesión sobre la base, para cambiar el staging como lo haría la ingesta."""
|
|
return Session(self.motor)
|
|
|
|
|
|
def base_de(proyecto: str, carpeta, datos=None) -> Base:
|
|
"""A migrated domain database in `carpeta`, with the kit's synthetic staging or, with `datos`, what it inserts."""
|
|
url = f"sqlite:///{carpeta / f'{proyecto}.db'}"
|
|
point_to(proyecto, url)
|
|
manifest = os.environ.get("DBT_MANIFEST")
|
|
ctx = Context(proyecto, ANIO, ANIO, dbt_manifest=Path(manifest) if manifest else None, repos=repositories_of(proyecto))
|
|
run(ctx, only=["migrate"])
|
|
motor = create_engine(url)
|
|
with Session(motor) as sesion:
|
|
(datos or import_module(f"staging.{proyecto}").insertar)(sesion)
|
|
sesion.commit()
|
|
return Base(proyecto, ctx, import_module(f"persistance.{proyecto}"), motor)
|
|
|
|
|
|
@pytest.fixture(params=["cacu", "cama"])
|
|
def proyecto(request):
|
|
return request.param
|
|
|
|
|
|
@pytest.fixture
|
|
def base(proyecto, tmp_path):
|
|
base = base_de(proyecto, tmp_path)
|
|
yield base
|
|
base.motor.dispose()
|
|
|
|
|
|
@pytest.fixture
|
|
def sin_supresion(tmp_path):
|
|
"""`parametros.toml` con umbral de supresión 1, para ver los conteos pequeños del fixture."""
|
|
ruta = tmp_path / "parametros.toml"
|
|
ruta.write_text(RUTA_PARAMETROS.read_text(encoding="utf-8").replace("valor = 5", "valor = 1"), encoding="utf-8")
|
|
return ruta
|
|
|
|
|
|
@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")
|
|
|
|
|
|
# Indicator-route tests (vendored from the fork's WebApi tests): the kit's
|
|
# demonstration database, seeded into a temporary SQLite file per domain.
|
|
SEMESTRES = ["2025-S1", "2025-S2"]
|
|
MESES = ["2025-01", "2025-02", "2025-03"]
|
|
|
|
|
|
def cliente_de(proyecto: str, tmp_path_factory):
|
|
"""Yields a client over a temporary SQLite database the cycle loaded from the kit's synthetic staging."""
|
|
carpeta = tmp_path_factory.mktemp(proyecto)
|
|
base = base_de(proyecto, carpeta)
|
|
base.run("catalogs", "load", "views", "registry", "definitions", "event_models", allow_undecided=True)
|
|
try:
|
|
from webapi import create_app
|
|
|
|
app = create_app()
|
|
app.config.update(TESTING=True)
|
|
with app.test_client() as cliente:
|
|
yield cliente
|
|
finally:
|
|
base.motor.dispose()
|