Files
WebApi/tests/conftest.py
T
Roberto Treviño Cervantes f65d5f3f4d preliminary release
2026-10-29 12:12:28 -06:00

104 lines
3.8 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")
# 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"))
@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 sembrar_base(proyecto: str, motor) -> None:
"""La base de demostración del kit: staging sintético, carga y todos los indicadores calculados.
Lo mismo que hace `indicadores_kit.tea.fixtures.base_de_prueba` para
TEA: cada definición de `measures_de(proyecto)` queda calculada en los
periodos de 2025 que publica (`SEMESTRES`, y los doce meses si publica
meses).
"""
from indicadores_kit.demostracion import base_de_prueba
base_de_prueba(motor, proyecto)
def cliente_de(proyecto: str, tmp_path_factory):
"""Generador para la fixture `client` de un proyecto: una base SQLite temporal ya sembrada."""
from persistance import db
from persistance.settings import settings
ruta = tmp_path_factory.mktemp(proyecto) / f"{proyecto}.db"
obtener_motor = getattr(db, f"get_{proyecto}_engine")
with pytest.MonkeyPatch.context() as mp:
mp.setattr(settings, f"{proyecto}_database_url", f"sqlite:///{ruta}")
obtener_motor.cache_clear()
try:
sembrar_base(proyecto, obtener_motor())
from webapi import create_app
app = create_app()
app.config.update(TESTING=True)
with app.test_client() as cliente:
yield cliente
finally:
obtener_motor().dispose()
obtener_motor.cache_clear()