Files
Roberto Treviño Cervantes ae1ee4633f absorb Orquestacion into webapi.orquestacion
Orquestacion was a separate uv package with exactly one consumer
(webapi.indicadores_vivos) and no independent deployment: the Dockerfile
already copied it straight into this image and ran one uv sync for
everything. Folding it in removes a redundant pyproject.toml/uv.lock/venv
without losing the standalone CLI (python -m webapi.orquestacion ciclo/
confirmar-riesgos) or its test suite, which now runs as part of this
project's own pytest run.

417 tests pass (416 unchanged + the merged orquestacion suite); verified
live in a built image, where the indicadores worker completed a full
cacu/cama/tea cycle against webapi.orquestacion.ejecutor.
2026-10-31 00:51:41 -06:00

157 lines
5.5 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.orquestacion`:
una base del dominio por prueba, migrada por el paso `migrar`, 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 indicadores_kit.registry.parametros import RUTA_PARAMETROS
from webapi.orquestacion import Contexto, correr
from webapi.orquestacion.conexion import apuntar
from webapi.orquestacion.repositorios import repositorios_de
# 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: Contexto
dominio: object
motor: object
def correr(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.nombre: p.resumen for p in correr(replace(self.ctx, **cambios), solo=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) -> Base:
url = f"sqlite:///{carpeta / f'{proyecto}.db'}"
apuntar(proyecto, url)
ctx = Contexto(proyecto, ANIO, ANIO, repos=repositorios_de(proyecto))
correr(ctx, solo=["migrar"])
motor = create_engine(url)
with Session(motor) as sesion:
import_module(f"indicadores_kit.{proyecto}.fixtures").insertar(sesion)
sesion.commit()
return Base(proyecto, ctx, import_module(f"persistance.{proyecto}"), motor)
@pytest.fixture(params=["cacu", "cama", "tea"])
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 seeded with the kit's demonstration data."""
from indicadores_kit.demostracion import base_de_prueba
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:
base_de_prueba(obtener_motor(), proyecto)
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()