14dff24f85
How: `SourceMappingRepository` (`source_mapping_repository` in cacu, cama and tea) lists systems and mappings, adds a missing system, seeds only the forms with no row yet, adds one mapping after running the caller's check against the stored rows of the same form in the same session, and closes a row's validity once. Implications: a deploy never changes a stored mapping; the rule that the mapping is a function stays with the caller, which runs it on every write.
90 lines
4.6 KiB
Python
90 lines
4.6 KiB
Python
"""What this module covers: `SourceMappingRepository` over CaMa's `cat_sistema_fuente` and `cat_mapeo`: seeding only
|
|
adds forms that have no row, `add` runs the caller's check against the rows of the same form in its session, and
|
|
`close` ends a row's validity once.
|
|
|
|
Fixtures: `repo`, an in-memory SQLite database (foreign keys on) with CaMa's tables, one study, result and two values, and the
|
|
catalog's own source system.
|
|
"""
|
|
|
|
from datetime import date, datetime, timezone
|
|
|
|
import pytest
|
|
from core.cama.indicadores.models import CatEstudio, CatMapeo, CatResultado, CatSistemaFuente, CatValor
|
|
from sqlalchemy import create_engine, event
|
|
from sqlalchemy.exc import IntegrityError
|
|
from sqlmodel import Session, SQLModel
|
|
|
|
from persistance.edges.silver import SourceMappingRepository
|
|
|
|
AHORA = datetime(2026, 11, 13, 12, 0, tzinfo=timezone.utc)
|
|
|
|
|
|
@pytest.fixture
|
|
def repo():
|
|
motor = create_engine("sqlite://")
|
|
# SQLite checks foreign keys only when asked; the other engines always do.
|
|
event.listen(motor, "connect", lambda conexion, _: conexion.execute("PRAGMA foreign_keys=ON"))
|
|
SQLModel.metadata.create_all(motor, tables=[t.__table__ for t in (CatEstudio, CatResultado, CatValor,
|
|
CatSistemaFuente, CatMapeo)])
|
|
with Session(motor) as sesion:
|
|
sesion.add(CatEstudio(estudio_id="biopsia", etiqueta="Biopsia"))
|
|
sesion.add(CatResultado(resultado_id="biopsia.her2", estudio_id="biopsia", etiqueta="HER2", tipo_valor="codigo"))
|
|
sesion.add_all([CatValor(resultado_id="biopsia.her2", valor_id=v, etiqueta=v, orden=i)
|
|
for i, v in enumerate(("H2", "H3"), start=1)])
|
|
sesion.commit()
|
|
repositorio = SourceMappingRepository(lambda: Session(motor, expire_on_commit=False), CatSistemaFuente, CatMapeo)
|
|
repositorio.ensure_system(CatSistemaFuente(sistema_fuente_id="catalogo", etiqueta="Catálogo",
|
|
vigente_desde=date(1900, 1, 1)))
|
|
return repositorio
|
|
|
|
|
|
def mapeo(forma: str, valor: str, *, por: str = "catalogo", desde: date = date(1900, 1, 1)) -> CatMapeo:
|
|
return CatMapeo(sistema_fuente_id="catalogo", clase="valor", forma=forma, forma_normalizada=forma.upper(),
|
|
resultado_id="biopsia.her2", valor_id=valor, vigente_desde=desde, registrado_por=por,
|
|
registrado_en=AHORA)
|
|
|
|
|
|
def test_seeding_adds_only_forms_without_a_row(repo):
|
|
"""Pins down: a deploy's seed never touches a stored row: a form already mapped, even to another code by a
|
|
person, keeps its row, and only new forms are added. Fails if `seed` merges or replaces rows, which would undo
|
|
a curator's change on every deploy."""
|
|
repo.add(mapeo("3+", "H2", por="curador"))
|
|
assert repo.seed([mapeo("3+", "H3"), mapeo("Positivo (3+)", "H3")]) == 1
|
|
assert {(m.forma, m.valor_id, m.registrado_por) for m in repo.forms()} == {
|
|
("3+", "H2", "curador"), ("Positivo (3+)", "H3", "catalogo")}
|
|
assert repo.seed([mapeo("3+", "H3")]) == 0
|
|
assert repo.ensure_system(CatSistemaFuente(sistema_fuente_id="catalogo", etiqueta="Otro",
|
|
vigente_desde=date(2000, 1, 1))) is False
|
|
|
|
|
|
def test_add_runs_the_check_against_the_same_form(repo):
|
|
"""Pins down: `add` hands the caller's check the stored rows of the same form, and a check that raises leaves
|
|
nothing written. Fails if the check runs on other forms or after the insert."""
|
|
repo.add(mapeo("3+", "H3"))
|
|
repo.add(mapeo("Positivo", "H3"))
|
|
vistas = []
|
|
|
|
def rechaza(misma_forma, nueva):
|
|
vistas.extend(m.forma for m in misma_forma)
|
|
raise ValueError("ambigua")
|
|
|
|
with pytest.raises(ValueError, match="ambigua"):
|
|
repo.add(mapeo("3+", "H2", desde=date(2027, 1, 1)), check=rechaza)
|
|
assert vistas == ["3+"]
|
|
assert len(repo.forms(forma_normalizada="3+")) == 1
|
|
|
|
|
|
def test_close_ends_a_row_once_and_the_schema_rejects_a_bad_row(repo):
|
|
"""Pins down: `close` sets `vigente_hasta` and a second close keeps the first end; a value outside `cat_valor`
|
|
or an end before the start is rejected by the database itself. Fails if `close` overwrites an end or a
|
|
constraint of `reglas_de_mapeo` is lost."""
|
|
fila = repo.add(mapeo("3+", "H3"))
|
|
assert repo.close(fila.mapeo_id, date(2026, 12, 31)).vigente_hasta == date(2026, 12, 31)
|
|
assert repo.close(fila.mapeo_id, date(2027, 6, 30)).vigente_hasta == date(2026, 12, 31)
|
|
with pytest.raises(IntegrityError):
|
|
repo.add(mapeo("H4", "H4"))
|
|
malo = mapeo("Equívoco", "H2", desde=date(2027, 1, 1))
|
|
malo.vigente_hasta = date(2026, 1, 1)
|
|
with pytest.raises(IntegrityError):
|
|
repo.add(malo)
|