Tabla histórica `identificacion` (JSON validado por tipo de persona, nombre de búsqueda, fuente captura o sintética) y en `documento`: sha256, nombre original, tamaño, tipo de contenido, fecha de emisión y subtipo. `cliente` no cambia.
124 lines
4.1 KiB
Python
124 lines
4.1 KiB
Python
"""Migración 0006: tabla `identificacion` y metadatos de archivo en `documento`."""
|
|
|
|
from pathlib import Path
|
|
|
|
import sqlalchemy as sa
|
|
from alembic import command
|
|
from alembic.config import Config
|
|
|
|
from app.models import Base
|
|
|
|
RAIZ = Path(__file__).resolve().parents[1]
|
|
COLUMNAS_NUEVAS = {
|
|
"sha256",
|
|
"nombre_original",
|
|
"tamano_bytes",
|
|
"tipo_contenido",
|
|
"fecha_emision",
|
|
"subtipo",
|
|
}
|
|
|
|
|
|
def _config(url: str) -> Config:
|
|
cfg = Config(str(RAIZ / "alembic.ini"))
|
|
cfg.set_main_option("sqlalchemy.url", url)
|
|
return cfg
|
|
|
|
|
|
def _columnas(engine: sa.Engine, tabla: str) -> set[str]:
|
|
return {c["name"] for c in sa.inspect(engine).get_columns(tabla)}
|
|
|
|
|
|
def test_upgrade_crea_identificacion_y_las_columnas_y_downgrade_las_quita(tmp_path) -> None:
|
|
url = f"sqlite:///{tmp_path / 'pld.db'}"
|
|
cfg = _config(url)
|
|
command.upgrade(cfg, "0005")
|
|
engine = sa.create_engine(url)
|
|
assert "identificacion" not in sa.inspect(engine).get_table_names()
|
|
assert not COLUMNAS_NUEVAS & _columnas(engine, "documento")
|
|
|
|
command.upgrade(cfg, "0006")
|
|
engine.dispose()
|
|
engine = sa.create_engine(url)
|
|
inspector = sa.inspect(engine)
|
|
assert "identificacion" in inspector.get_table_names()
|
|
assert COLUMNAS_NUEVAS <= _columnas(engine, "documento")
|
|
columnas = _columnas(engine, "identificacion")
|
|
assert {
|
|
"id",
|
|
"tenant_id",
|
|
"created_at",
|
|
"created_by",
|
|
"valid_from",
|
|
"valid_to",
|
|
"cliente_id",
|
|
"version",
|
|
"fuente",
|
|
"nombre_busqueda",
|
|
"datos",
|
|
} <= columnas
|
|
indices = {i["name"] for i in inspector.get_indexes("identificacion")}
|
|
assert {
|
|
"ix_identificacion_cliente_id",
|
|
"ix_identificacion_nombre_busqueda",
|
|
"ix_identificacion_tenant_id",
|
|
} <= indices
|
|
|
|
# La migración deja la base igual que los modelos (sin diferencias para autogenerate).
|
|
with engine.connect() as conn:
|
|
tablas_modelo = set(Base.metadata.tables)
|
|
tablas_base = set(sa.inspect(conn).get_table_names()) - {"alembic_version"}
|
|
assert tablas_modelo == tablas_base
|
|
|
|
command.downgrade(cfg, "0005")
|
|
engine.dispose()
|
|
engine = sa.create_engine(url)
|
|
assert "identificacion" not in sa.inspect(engine).get_table_names()
|
|
assert not COLUMNAS_NUEVAS & _columnas(engine, "documento")
|
|
command.upgrade(cfg, "head")
|
|
|
|
|
|
def test_el_check_de_fuente_rechaza_valores_fuera_del_catalogo(tmp_path) -> None:
|
|
url = f"sqlite:///{tmp_path / 'pld.db'}"
|
|
command.upgrade(_config(url), "head")
|
|
engine = sa.create_engine(url)
|
|
base = (
|
|
"created_at, created_by, tenant_id, valid_from, cliente_id, version, fuente, "
|
|
"nombre_busqueda, datos"
|
|
)
|
|
with engine.begin() as conn:
|
|
tenant = conn.execute(
|
|
sa.text(
|
|
"INSERT INTO tenant (created_at, created_by, nombre, regimen, "
|
|
"actividad_vulnerable, uma_vigente, ventana_meses, fecha_corte) VALUES "
|
|
"('2026-10-07', 'pytest', 'Demo', "
|
|
"'LFPIORPI', 'Art. 17', 117.31, 6, '2026-08-31') RETURNING id"
|
|
)
|
|
).scalar_one()
|
|
cliente = conn.execute(
|
|
sa.text(
|
|
"INSERT INTO cliente (created_at, created_by, tenant_id, id_externo, tipo_persona) "
|
|
"VALUES ('2026-10-07', 'pytest', :t, 'X1', 'fisica') RETURNING id"
|
|
),
|
|
{"t": tenant},
|
|
).scalar_one()
|
|
conn.execute(
|
|
sa.text(
|
|
f"INSERT INTO identificacion ({base}) VALUES ('2026-10-07', 'pytest', :t, "
|
|
"'2026-10-07', :c, 1, 'captura', 'Ana', '{}')"
|
|
),
|
|
{"t": tenant, "c": cliente},
|
|
)
|
|
try:
|
|
conn.execute(
|
|
sa.text(
|
|
f"INSERT INTO identificacion ({base}) VALUES ('2026-10-07', 'pytest', :t, "
|
|
"'2026-10-07', :c, 2, 'otra', 'Ana', '{}')"
|
|
),
|
|
{"t": tenant, "c": cliente},
|
|
)
|
|
except sa.exc.IntegrityError as exc:
|
|
assert "ck_identificacion_fuente" in str(exc)
|
|
else: # pragma: no cover
|
|
raise AssertionError("el CHECK de fuente no se aplicó")
|