Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a6dad8cd91 | |||
| 03bbb09b47 | |||
| 2441a049ea | |||
| 4eb45405a3 |
@@ -77,6 +77,40 @@ def catalogo_desde_toml(ruta: Path, *, tablas: TablasKit) -> Catalogo:
|
||||
return Catalogo(estudios, resultados, valores)
|
||||
|
||||
|
||||
def add_resultado(
|
||||
proyecto: str, *, estudio_id: str, nombre: str, etiqueta: str, tipo_valor: str, estudio_etiqueta: str | None = None
|
||||
) -> str:
|
||||
"""Appends a new `resultado_id` to the project's TOML (not to the
|
||||
database): a `[estudio.resultados.nombre]` table, and the `[estudio]`
|
||||
table too if it didn't exist yet. The file stays the source: the next
|
||||
`catalogo_desde_toml` already brings it, and whoever syncs the table
|
||||
writes it.
|
||||
|
||||
Idempotent: if the resultado is already in the file, nothing is
|
||||
written and its `resultado_id` is returned as is. `nombre` must be a
|
||||
valid TOML key (whoever discovers the field builds it, e.g. from a
|
||||
slug of the text found).
|
||||
"""
|
||||
if tipo_valor not in TIPOS_DE_VALOR:
|
||||
raise CatalogoInvalido(f"{estudio_id}.{nombre}: tipo_valor {tipo_valor!r} no es uno de {', '.join(TIPOS_DE_VALOR)}.")
|
||||
ruta = ruta_de_catalogo(proyecto)
|
||||
existentes = _leer(ruta)
|
||||
resultado_id = f"{estudio_id}.{nombre}"
|
||||
if estudio_id in existentes and nombre in existentes[estudio_id].get("resultados", {}):
|
||||
return resultado_id
|
||||
blocks = []
|
||||
if estudio_id not in existentes:
|
||||
blocks.append(f'\n[{estudio_id}]\netiqueta = "{_escape(estudio_etiqueta or estudio_id)}"\n')
|
||||
blocks.append(f'\n[{estudio_id}.resultados.{nombre}]\netiqueta = "{_escape(etiqueta)}"\ntipo_valor = "{tipo_valor}"\n')
|
||||
with Path(ruta).open("a", encoding="utf-8") as archivo:
|
||||
archivo.write("".join(blocks))
|
||||
return resultado_id
|
||||
|
||||
|
||||
def _escape(text: str) -> str:
|
||||
return text.replace("\\", "\\\\").replace('"', '\\"')
|
||||
|
||||
|
||||
def codigos_hospital(proyecto: str) -> dict[str, str]:
|
||||
"""Código del hospital -> `estudio_id`, del catálogo del proyecto.
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"""`add_resultado`: adds a new field to a project's catalog TOML file on
|
||||
disk, for a caller (`webapi.imports.schemas.catalog_matching`) that found a
|
||||
field no catalog entry matches closely enough. Each test pins down one
|
||||
rule of that append; fails if any of them regresses into losing data or
|
||||
duplicating an entry that's already there.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from indicadores_kit.registry import catalogos
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def catalogo_file(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
|
||||
def escribir(contenido: str) -> None:
|
||||
(tmp_path / "prueba.toml").write_text(contenido, encoding="utf-8")
|
||||
|
||||
return escribir
|
||||
|
||||
|
||||
def test_a_new_resultado_is_appended_under_its_existing_estudio(catalogo_file):
|
||||
catalogo_file('[citologia]\netiqueta = "Citología"\n')
|
||||
|
||||
resultado_id = catalogos.add_resultado(
|
||||
"prueba", estudio_id="citologia", nombre="nuevo_campo", etiqueta="Nuevo campo", tipo_valor="texto"
|
||||
)
|
||||
|
||||
assert resultado_id == "citologia.nuevo_campo"
|
||||
leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba"))
|
||||
assert leido["citologia"]["etiqueta"] == "Citología" # what was already there survives
|
||||
assert leido["citologia"]["resultados"]["nuevo_campo"] == {"etiqueta": "Nuevo campo", "tipo_valor": "texto"}
|
||||
|
||||
|
||||
def test_a_resultado_of_an_unknown_estudio_also_creates_the_estudio(catalogo_file):
|
||||
catalogo_file("")
|
||||
|
||||
catalogos.add_resultado(
|
||||
"prueba",
|
||||
estudio_id="documento_externo",
|
||||
nombre="campo",
|
||||
etiqueta="Campo",
|
||||
tipo_valor="fecha",
|
||||
estudio_etiqueta="Documento externo",
|
||||
)
|
||||
|
||||
leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba"))
|
||||
assert leido["documento_externo"]["etiqueta"] == "Documento externo"
|
||||
assert leido["documento_externo"]["resultados"]["campo"]["tipo_valor"] == "fecha"
|
||||
|
||||
|
||||
def test_adding_the_same_resultado_twice_does_not_touch_the_file(catalogo_file):
|
||||
"""Fails if re-discovering the same field on a later row duplicates it
|
||||
or rewrites what a human already edited in the file."""
|
||||
original = '[citologia]\netiqueta = "Citología"\n\n[citologia.resultados.campo]\netiqueta = "Campo"\ntipo_valor = "texto"\n'
|
||||
catalogo_file(original)
|
||||
|
||||
catalogos.add_resultado("prueba", estudio_id="citologia", nombre="campo", etiqueta="Otra cosa", tipo_valor="numero")
|
||||
|
||||
assert catalogos.ruta_de_catalogo("prueba").read_text(encoding="utf-8") == original
|
||||
|
||||
|
||||
def test_an_unknown_tipo_valor_is_rejected(catalogo_file):
|
||||
catalogo_file("")
|
||||
with pytest.raises(catalogos.CatalogoInvalido):
|
||||
catalogos.add_resultado("prueba", estudio_id="x", nombre="y", etiqueta="Y", tipo_valor="no_existe")
|
||||
|
||||
|
||||
def test_a_quote_in_a_label_does_not_break_the_file(catalogo_file):
|
||||
"""Fails if a caption or label read off a document (arbitrary text)
|
||||
produces TOML the next `catalogo_desde_toml` can't parse."""
|
||||
catalogo_file("")
|
||||
catalogos.add_resultado(
|
||||
"prueba", estudio_id="nota", nombre="campo", etiqueta='Dx: "sospechoso"', tipo_valor="texto"
|
||||
)
|
||||
leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba"))
|
||||
assert leido["nota"]["resultados"]["campo"]["etiqueta"] == 'Dx: "sospechoso"'
|
||||
Reference in New Issue
Block a user