195 lines
8.1 KiB
Python
195 lines
8.1 KiB
Python
"""Migración 0013: la marca heredada del antiguo especialista sale de los valores guardados."""
|
|
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
import sqlalchemy as sa
|
|
from alembic import command
|
|
from alembic.config import Config
|
|
|
|
RAIZ = Path(__file__).resolve().parents[1]
|
|
MARCA = "CHM"
|
|
|
|
|
|
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) -> tuple[int, 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')"
|
|
)
|
|
modelo = insertar(
|
|
f"INSERT INTO modelo_riesgo ({base}, tenant_id, valid_from, version, nombre, "
|
|
f"vigente_desde, aprobado_por, justificacion, validacion_omitida) VALUES ({ahora}, :t, "
|
|
f"'2026-10-06', 'v2', 'Modelo EBR v2 (esquema {MARCA}, octubre 2026)', '2026-10-06', "
|
|
f"'{MARCA} Compliance', 'Transcrito del Excel de {MARCA}', 0)",
|
|
t=tenant,
|
|
)
|
|
lote = insertar(
|
|
f"INSERT INTO lote_carga ({base}, tenant_id, tipo, archivo_hash, usuario) "
|
|
f"VALUES ({ahora}, :t, 'esquema_{MARCA.lower()}', 'abc', 'pytest')",
|
|
t=tenant,
|
|
)
|
|
cliente = insertar(
|
|
f"INSERT INTO cliente ({base}, tenant_id, id_externo, tipo_persona) "
|
|
f"VALUES ({ahora}, :t, 'c1', 'fisica')",
|
|
t=tenant,
|
|
)
|
|
# Filas que referencian al lote (como en producción): la migración recrea `lote_carga` y
|
|
# con las llaves foráneas activas el DROP de la tabla vieja fallaba.
|
|
credito = insertar(
|
|
f"INSERT INTO credito ({base}, tenant_id, id_externo, cliente_id, monto, "
|
|
f"fecha_disposicion, status) VALUES ({ahora}, :t, 'cr1', :c, 1000, '2026-01-01', 'activo')",
|
|
t=tenant,
|
|
c=cliente,
|
|
)
|
|
insertar(
|
|
f"INSERT INTO transaccion ({base}, tenant_id, credito_id, fecha_pago, total, tipo, "
|
|
f"lote_carga_id) VALUES ({ahora}, :t, :cr, '2026-02-01', 100, 'PAGO', :l)",
|
|
t=tenant,
|
|
cr=credito,
|
|
l=lote,
|
|
)
|
|
insertar(
|
|
f"INSERT INTO carga_fila ({base}, tenant_id, lote_carga_id, registro, fila, estado, "
|
|
f"huella, datos) VALUES ({ahora}, :t, :l, 'clientes', 2, 'aceptada', 'h1', '{{}}')",
|
|
t=tenant,
|
|
l=lote,
|
|
)
|
|
insertar(
|
|
f"INSERT INTO pep ({base}, tenant_id, valid_from, persona_id, tipo, fuente) "
|
|
f"VALUES ({ahora}, :t, '2026-10-06', :c, 'nacional', 'declarada_por_{MARCA}')",
|
|
t=tenant,
|
|
c=cliente,
|
|
)
|
|
return tenant, modelo
|
|
|
|
|
|
@pytest.mark.filterwarnings("ignore::DeprecationWarning")
|
|
def test_0013_reescribe_identificadores_y_textos_y_recrea_la_restriccion(tmp_path: Path) -> None:
|
|
url = f"sqlite:///{tmp_path / 'm.db'}"
|
|
cfg = _config(url)
|
|
command.upgrade(cfg, "0012")
|
|
engine = sa.create_engine(url)
|
|
with engine.begin() as conn:
|
|
_, modelo = _sembrar(conn)
|
|
command.upgrade(cfg, "0013")
|
|
with engine.connect() as conn:
|
|
fila = conn.execute(
|
|
sa.text("SELECT nombre, aprobado_por, justificacion FROM modelo_riesgo WHERE id = :m"),
|
|
{"m": modelo},
|
|
).one()
|
|
assert fila == (
|
|
"Modelo EBR v2 (esquema de origen, octubre 2026)",
|
|
"especialista",
|
|
"Transcrito del Excel de origen",
|
|
)
|
|
assert conn.execute(sa.text("SELECT tipo FROM lote_carga")).scalar_one() == "esquema_origen"
|
|
assert conn.execute(sa.text("SELECT fuente FROM pep")).scalar_one() == "declarada_en_origen"
|
|
# La restricción nueva admite el valor nuevo y rechaza el viejo.
|
|
with pytest.raises(sa.exc.IntegrityError):
|
|
conn.execute(
|
|
sa.text(
|
|
"INSERT INTO lote_carga (created_at, created_by, tenant_id, tipo, "
|
|
"archivo_hash, usuario) VALUES ('2026-10-06', 'pytest', 1, "
|
|
f"'esquema_{MARCA.lower()}', 'x', 'p')"
|
|
)
|
|
)
|
|
command.downgrade(cfg, "0012")
|
|
with engine.connect() as conn:
|
|
assert (
|
|
conn.execute(sa.text("SELECT tipo FROM lote_carga")).scalar_one()
|
|
== f"esquema_{MARCA.lower()}"
|
|
)
|
|
assert (
|
|
conn.execute(sa.text("SELECT fuente FROM pep")).scalar_one() == f"declarada_por_{MARCA}"
|
|
)
|
|
engine.dispose()
|
|
|
|
|
|
def _conteos(conn: sa.Connection) -> tuple[int, int, int]:
|
|
return (
|
|
conn.execute(sa.text("SELECT count(*) FROM lote_carga")).scalar_one(),
|
|
conn.execute(sa.text("SELECT count(*) FROM carga_fila")).scalar_one(),
|
|
conn.execute(sa.text("SELECT count(*) FROM transaccion")).scalar_one(),
|
|
)
|
|
|
|
|
|
@pytest.mark.filterwarnings("ignore::DeprecationWarning")
|
|
def test_0013_conserva_las_filas_que_referencian_al_lote_y_las_llaves_foraneas(
|
|
tmp_path: Path,
|
|
) -> None:
|
|
url = f"sqlite:///{tmp_path / 'r.db'}"
|
|
cfg = _config(url)
|
|
command.upgrade(cfg, "0012")
|
|
engine = sa.create_engine(url)
|
|
with engine.begin() as conn:
|
|
_sembrar(conn)
|
|
antes = _conteos(conn)
|
|
command.upgrade(cfg, "0013")
|
|
with engine.connect() as conn:
|
|
assert _conteos(conn) == antes == (1, 1, 1)
|
|
assert conn.execute(sa.text("PRAGMA foreign_key_check")).fetchall() == []
|
|
assert conn.execute(sa.text("SELECT tipo FROM lote_carga")).scalar_one() == "esquema_origen"
|
|
# Las llaves foráneas siguen activas y apuntan a la tabla recreada.
|
|
with pytest.raises(sa.exc.IntegrityError):
|
|
conn.execute(sa.text("PRAGMA foreign_keys = ON"))
|
|
conn.execute(
|
|
sa.text(
|
|
"INSERT INTO carga_fila (created_at, created_by, tenant_id, lote_carga_id, "
|
|
"registro, fila, estado, huella) VALUES ('2026-10-06', 'p', 1, 999, 'x', 1, "
|
|
"'aceptada', 'h2')"
|
|
)
|
|
)
|
|
command.downgrade(cfg, "0012")
|
|
with engine.connect() as conn:
|
|
assert _conteos(conn) == antes
|
|
engine.dispose()
|
|
|
|
|
|
@pytest.mark.filterwarnings("ignore::DeprecationWarning")
|
|
def test_0013_se_retoma_si_una_corrida_anterior_quedo_a_medias(tmp_path: Path) -> None:
|
|
"""Producción quedó con los UPDATE aplicados y, en el peor caso, la restricción ya quitada
|
|
(DDL no transaccional en SQLite): la migración vuelve a correr sin error."""
|
|
from alembic.migration import MigrationContext
|
|
from alembic.operations import Operations
|
|
|
|
url = f"sqlite:///{tmp_path / 'm.db'}"
|
|
cfg = _config(url)
|
|
command.upgrade(cfg, "0012")
|
|
engine = sa.create_engine(url)
|
|
with engine.begin() as conn:
|
|
_sembrar(conn)
|
|
conn.execute(sa.text("UPDATE pep SET fuente = 'declarada_en_origen'"))
|
|
conn.execute(sa.text("UPDATE modelo_riesgo SET aprobado_por = 'especialista'"))
|
|
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("lote_carga", recreate="always") as batch_op:
|
|
batch_op.drop_constraint("ck_lote_carga_tipo", type_="check")
|
|
# y la tabla temporal de un intento fallido
|
|
conn.exec_driver_sql("CREATE TABLE _alembic_tmp_lote_carga (id INTEGER)")
|
|
command.upgrade(cfg, "0013")
|
|
with engine.connect() as conn:
|
|
assert _conteos(conn) == (1, 1, 1)
|
|
assert conn.execute(sa.text("SELECT tipo FROM lote_carga")).scalar_one() == "esquema_origen"
|
|
assert conn.execute(sa.text("SELECT fuente FROM pep")).scalar_one() == "declarada_en_origen"
|
|
with pytest.raises(sa.exc.IntegrityError): # la restricción quedó puesta
|
|
conn.execute(
|
|
sa.text(
|
|
"INSERT INTO lote_carga (created_at, created_by, tenant_id, tipo, "
|
|
"archivo_hash, usuario) VALUES ('2026-10-06', 'p', 1, 'otro', 'x', 'p')"
|
|
)
|
|
)
|
|
engine.dispose()
|