114 lines
4.7 KiB
Python
114 lines
4.7 KiB
Python
"""Migración 0014 (Pieza N): recrea `alerta` para admitir el estado `historica` con filas
|
|
existentes y llaves foráneas activas; idempotente si una corrida anterior quedó a medias."""
|
|
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
import sqlalchemy as sa
|
|
from alembic import command
|
|
from alembic.config import Config
|
|
from alembic.migration import MigrationContext
|
|
from alembic.operations import Operations
|
|
|
|
RAIZ = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def _config(url: str) -> Config:
|
|
cfg = Config(str(RAIZ / "alembic.ini"))
|
|
cfg.set_main_option("sqlalchemy.url", url)
|
|
return cfg
|
|
|
|
|
|
def _sembrar(conn: sa.Connection) -> int:
|
|
def insertar(sql: str, **params) -> int:
|
|
return conn.execute(sa.text(sql + " RETURNING id"), params).scalar_one()
|
|
|
|
base = "created_at, created_by"
|
|
ahora = "'2026-10-06 12:00:00', 'pytest'"
|
|
tenant = insertar(
|
|
f"INSERT INTO tenant ({base}, clave, nombre, regimen, actividad_vulnerable, uma_vigente, "
|
|
f"ventana_meses, fecha_corte) VALUES ({ahora}, 'demo', 'Demo', 'LFPIORPI', 'Art. 17', "
|
|
"117.31, 6, '2026-08-31')"
|
|
)
|
|
cliente = insertar(
|
|
f"INSERT INTO cliente ({base}, tenant_id, id_externo, tipo_persona) "
|
|
f"VALUES ({ahora}, :t, 'c1', 'fisica')",
|
|
t=tenant,
|
|
)
|
|
regla = insertar(
|
|
f"INSERT INTO regla_alerta ({base}, tenant_id, valid_from, version, clave, familia, "
|
|
"nombre, criterio_texto, evaluable_con_datos, requiere_expediente, tipo_evaluacion, "
|
|
f"nivel, vigente_desde, aprobado_por) VALUES ({ahora}, :t, '2026-10-06', 'v2', 'A-01', "
|
|
"'A', 'Umbral', 'monto', 1, 0, 'credito', 'critica', '2026-10-06', 'especialista')",
|
|
t=tenant,
|
|
)
|
|
for estado in ("nueva", "cerrada"):
|
|
insertar(
|
|
f"INSERT INTO alerta ({base}, tenant_id, regla_id, cliente_id, nivel, estado) "
|
|
f"VALUES ({ahora}, :t, :r, :c, 'critica', :e)",
|
|
t=tenant,
|
|
r=regla,
|
|
c=cliente,
|
|
e=estado,
|
|
)
|
|
return tenant
|
|
|
|
|
|
@pytest.mark.filterwarnings("ignore::DeprecationWarning")
|
|
def test_0014_recrea_alerta_con_filas_y_admite_el_estado_historico(tmp_path: Path) -> None:
|
|
url = f"sqlite:///{tmp_path / 'a.db'}"
|
|
cfg = _config(url)
|
|
command.upgrade(cfg, "0013")
|
|
engine = sa.create_engine(url)
|
|
with engine.begin() as conn:
|
|
tenant = _sembrar(conn)
|
|
command.upgrade(cfg, "0014")
|
|
with engine.connect() as conn:
|
|
estados = conn.execute(sa.text("SELECT estado FROM alerta ORDER BY id")).scalars().all()
|
|
assert estados == ["nueva", "cerrada"]
|
|
assert conn.execute(sa.text("PRAGMA foreign_key_check")).fetchall() == []
|
|
assert conn.execute(sa.text("SELECT clave_actividad_sat FROM tenant")).scalar_one() == "MPC"
|
|
conn.execute(sa.text("UPDATE alerta SET estado = 'historica' WHERE estado = 'nueva'"))
|
|
with pytest.raises(sa.exc.IntegrityError):
|
|
conn.execute(sa.text("UPDATE alerta SET estado = 'otro' WHERE estado = 'cerrada'"))
|
|
conn.rollback()
|
|
with engine.begin() as conn:
|
|
conn.execute(sa.text("UPDATE alerta SET estado = 'historica' WHERE estado = 'nueva'"))
|
|
conn.execute(
|
|
sa.text(
|
|
"INSERT INTO aviso (created_at, created_by, tenant_id, periodo, tipo, estado, "
|
|
"origen) VALUES ('2026-10-06', 'p', :t, '202608', 'normal', 'borrador', "
|
|
"'plataforma')"
|
|
),
|
|
{"t": tenant},
|
|
)
|
|
command.downgrade(cfg, "0013")
|
|
with engine.connect() as conn:
|
|
assert conn.execute(sa.text("SELECT estado FROM alerta ORDER BY id")).scalars().all() == [
|
|
"cerrada",
|
|
"cerrada",
|
|
]
|
|
engine.dispose()
|
|
|
|
|
|
@pytest.mark.filterwarnings("ignore::DeprecationWarning")
|
|
def test_0014_se_retoma_si_la_restriccion_ya_no_esta(tmp_path: Path) -> None:
|
|
url = f"sqlite:///{tmp_path / 'b.db'}"
|
|
cfg = _config(url)
|
|
command.upgrade(cfg, "0013")
|
|
engine = sa.create_engine(url)
|
|
with engine.begin() as conn:
|
|
_sembrar(conn)
|
|
with engine.connect().execution_options(isolation_level="AUTOCOMMIT") as conn:
|
|
conn.exec_driver_sql("PRAGMA foreign_keys = OFF")
|
|
ops = Operations(MigrationContext.configure(conn))
|
|
with ops.batch_alter_table("alerta", recreate="always") as batch_op:
|
|
batch_op.drop_constraint("ck_alerta_estado", type_="check")
|
|
conn.exec_driver_sql("CREATE TABLE _alembic_tmp_alerta (id INTEGER)")
|
|
command.upgrade(cfg, "0014")
|
|
with engine.connect() as conn:
|
|
assert conn.execute(sa.text("SELECT count(*) FROM alerta")).scalar_one() == 2
|
|
with pytest.raises(sa.exc.IntegrityError):
|
|
conn.execute(sa.text("UPDATE alerta SET estado = 'otro'"))
|
|
engine.dispose()
|