234 lines
9.9 KiB
Python
234 lines
9.9 KiB
Python
import pytest
|
|
from pydantic import ValidationError
|
|
|
|
from webapi.imports.mapping.column_matcher import ColumnMatcher
|
|
from webapi.imports.schemas.cacu.paciente import PacienteImportSchema
|
|
from webapi.imports.schemas.classify import ErrorCategory, classify_error
|
|
from webapi.imports.schemas.service import validate_rows
|
|
from webapi.imports.schemas.tea.pacientes import PacientesImportSchema
|
|
|
|
|
|
def test_paciente_schema_required_field_missing():
|
|
with pytest.raises(ValidationError) as excinfo:
|
|
PacienteImportSchema(pac_sexo="F")
|
|
errors = excinfo.value.errors()
|
|
assert any(e["loc"] == ("pac_id_hospital",) for e in errors)
|
|
|
|
|
|
def test_paciente_schema_coerces_sexo_alias():
|
|
schema = PacienteImportSchema(pac_id_hospital="H-1", pac_sexo="f", pac_fecha_nacimiento="1990-01-15")
|
|
assert schema.pac_sexo == "Femenino"
|
|
|
|
schema2 = PacienteImportSchema(pac_id_hospital="H-2", pac_sexo="MASCULINO", pac_fecha_nacimiento="1990-01-15")
|
|
assert schema2.pac_sexo == "Masculino"
|
|
|
|
|
|
def test_paciente_schema_rejects_unknown_sexo():
|
|
with pytest.raises(ValidationError):
|
|
# pac_sexo has no enum constraint on the storage model, but this is
|
|
# still a plain string field; feed something structurally invalid
|
|
# (a date field) to prove type validation happens
|
|
PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento="not-a-date")
|
|
|
|
|
|
def test_paciente_schema_coerces_date_from_iso_string():
|
|
schema = PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento="2020-01-15")
|
|
assert schema.pac_fecha_nacimiento.isoformat() == "2020-01-15"
|
|
|
|
|
|
def test_paciente_schema_coerces_date_from_datetime_object():
|
|
from datetime import datetime
|
|
|
|
schema = PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento=datetime(2020, 1, 15, 10, 30))
|
|
assert schema.pac_fecha_nacimiento.isoformat() == "2020-01-15"
|
|
|
|
|
|
def test_tea_pacientes_schema_is_fully_optional():
|
|
schema = PacientesImportSchema()
|
|
assert schema.pac_id_hospital is None
|
|
|
|
|
|
def test_tea_pacientes_schema_coerces_sexo_from_bare_enum_no_alias_dict():
|
|
schema = PacientesImportSchema(pac_sexo="f")
|
|
assert schema.pac_sexo == "F"
|
|
|
|
|
|
def test_tea_pacientes_schema_coerces_parentesco():
|
|
schema = PacientesImportSchema(pac_parentesco="hijo")
|
|
assert schema.pac_parentesco == "HIJO"
|
|
|
|
|
|
def test_classify_error_missing():
|
|
try:
|
|
PacienteImportSchema(pac_sexo="F")
|
|
except ValidationError as exc:
|
|
classified = [classify_error(e) for e in exc.errors()]
|
|
assert any(c.category == ErrorCategory.MISSING and c.field == "pac_id_hospital" for c in classified)
|
|
|
|
|
|
def test_classify_error_type_invalid():
|
|
try:
|
|
PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento="not-a-date")
|
|
except ValidationError as exc:
|
|
classified = [classify_error(e) for e in exc.errors()]
|
|
assert any(c.category == ErrorCategory.TYPE_INVALID for c in classified)
|
|
|
|
|
|
def test_validate_rows_never_aborts_on_a_bad_row():
|
|
rows = [
|
|
{"pac_id_hospital": "H-1", "pac_sexo": "F", "pac_fecha_nacimiento": "1990-01-15"},
|
|
{"pac_sexo": "M"}, # missing required fields
|
|
{"pac_id_hospital": "H-3", "pac_fecha_nacimiento": "1990-01-15"},
|
|
]
|
|
result = validate_rows(PacienteImportSchema, rows)
|
|
assert result.total_rows == 3
|
|
assert result.valid_count == 2
|
|
assert result.error_count == 1
|
|
assert result.rejected[0].row_index == 1
|
|
|
|
|
|
def test_column_matcher_exact_normalized_synonym_fuzzy_none():
|
|
matcher = ColumnMatcher()
|
|
targets = ["pac_id_hospital", "pac_sexo", "pac_fecha_nacimiento"]
|
|
|
|
suggestions = matcher.suggest(
|
|
["pac_id_hospital", "Sexo", "fecha_nacimiento", "columna_sin_relacion_xyz"], targets
|
|
)
|
|
by_source = {s.source_column: s for s in suggestions}
|
|
|
|
assert by_source["pac_id_hospital"].reason == "exact"
|
|
assert by_source["pac_id_hospital"].target_field == "pac_id_hospital"
|
|
|
|
assert by_source["Sexo"].reason == "synonym"
|
|
assert by_source["Sexo"].target_field == "pac_sexo"
|
|
|
|
assert by_source["fecha_nacimiento"].reason in ("synonym", "fuzzy")
|
|
assert by_source["fecha_nacimiento"].target_field == "pac_fecha_nacimiento"
|
|
|
|
assert by_source["columna_sin_relacion_xyz"].target_field is None
|
|
assert by_source["columna_sin_relacion_xyz"].reason == "none"
|
|
|
|
|
|
def test_column_matcher_enforces_one_to_one():
|
|
matcher = ColumnMatcher()
|
|
# two source columns that would both match "pac_sexo" exactly-ish
|
|
suggestions = matcher.suggest(["pac_sexo", "sexo"], ["pac_sexo"])
|
|
matched_targets = [s.target_field for s in suggestions if s.target_field]
|
|
assert matched_targets == ["pac_sexo"] # only the first claims it
|
|
|
|
|
|
def test_coerce_date_accepts_iso_day_first_and_timestamps_but_not_impossible_dates():
|
|
from datetime import date, datetime
|
|
|
|
from webapi.imports.schemas.coercion import coerce_date
|
|
|
|
assert coerce_date("1990-01-15") == date(1990, 1, 15)
|
|
assert coerce_date("15/01/1990") == date(1990, 1, 15)
|
|
assert coerce_date("15-01-1990") == date(1990, 1, 15)
|
|
assert coerce_date("1990-01-15 00:00:00") == date(1990, 1, 15)
|
|
assert coerce_date(datetime(1990, 1, 15, 8, 30)) == date(1990, 1, 15)
|
|
assert coerce_date(" ") is None
|
|
with pytest.raises(ValueError, match="no es una fecha válida"):
|
|
coerce_date("31/02/1990")
|
|
|
|
|
|
def test_catalog_is_case_insensitive_accepts_member_names_and_rejects_unknowns():
|
|
from core.cacu.enums import SEXO_BIOLOGICO_ALIAS, SexoBiologico
|
|
from webapi.imports.schemas.coercion import Catalog, coerce_alias
|
|
|
|
catalog = Catalog(SexoBiologico, SEXO_BIOLOGICO_ALIAS)
|
|
assert coerce_alias(" femenino ", catalog) == "Femenino"
|
|
assert coerce_alias("m", catalog) == "Masculino"
|
|
assert coerce_alias("", catalog) is None
|
|
with pytest.raises(ValueError, match="no está en el catálogo"):
|
|
coerce_alias("X", catalog)
|
|
|
|
|
|
def test_birads_subcategories_from_reports_are_not_rejected_as_out_of_catalog():
|
|
"""`extraction.nlp.vocabulary.CLINICAL_TERMS` extracts BI-RADS 4A/4B/4C
|
|
from narrative text (a standard ACR BI-RADS subcategory), but the schema
|
|
only models the base B0-B6 categories; without an alias for them, every
|
|
such report was silently unimportable."""
|
|
from core.cama.mastografia.enums import BIRADS, BIRADS_ALIAS
|
|
from webapi.imports.schemas.coercion import Catalog, coerce_alias
|
|
|
|
catalog = Catalog(BIRADS, BIRADS_ALIAS)
|
|
for value in ("4A", "BI-RADS 4B", "bi-rads 4c"):
|
|
assert coerce_alias(value, catalog) == "B4"
|
|
|
|
|
|
def test_postal_code_restores_leading_zero_from_numeric_sources():
|
|
from webapi.imports.schemas.coercion import coerce_postal_code
|
|
|
|
assert coerce_postal_code(1000) == "01000"
|
|
assert coerce_postal_code(64000.0) == "64000"
|
|
assert coerce_postal_code(" 01000 ") == "01000"
|
|
assert coerce_postal_code("") is None
|
|
|
|
|
|
def test_column_matcher_handles_accents_prefixes_and_global_one_to_one():
|
|
matcher = ColumnMatcher()
|
|
targets = ["pac_id_hospital", "pac_sexo", "pac_codigo_postal", "pac_fecha_nacimiento"]
|
|
by_source = {
|
|
s.source_column: s
|
|
for s in matcher.suggest(["Fech nacim", "Género", "C.P.", "Expediente", "fecha_nacimiento"], targets)
|
|
}
|
|
assert by_source["Género"].target_field == "pac_sexo"
|
|
assert by_source["C.P."].target_field == "pac_codigo_postal"
|
|
assert by_source["Expediente"].target_field == "pac_id_hospital"
|
|
# The synonym "fecha_nacimiento" wins pac_fecha_nacimiento even
|
|
# though the weaker fuzzy "Fech nacim" comes first in the file.
|
|
assert by_source["fecha_nacimiento"].target_field == "pac_fecha_nacimiento"
|
|
assert by_source["Fech nacim"].target_field is None
|
|
|
|
|
|
def test_column_matcher_matches_names_without_the_table_prefix():
|
|
suggestion = ColumnMatcher().suggest(["hemoglobina_g_dl", "birads"], ["hemoglobina_g_dl", "mast_birads"])
|
|
assert [(s.target_field, s.reason) for s in suggestion] == [("hemoglobina_g_dl", "exact"), ("mast_birads", "unprefixed")]
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"target, source, expected",
|
|
[
|
|
# Match on shared meaning, not shared suffixes ("solicitaDO" vs "solicitaNTE").
|
|
("cacu.OrdenesEstudio", "Estudio solicitado", "ord_tipo_estudio"),
|
|
("cacu.OrdenesEstudio", "Paciente", "pac_id_hospital"),
|
|
("cacu.NotaMedica", "Servicio", "nm_especialidad"),
|
|
("cacu.NotaMedica", "Fecha consulta", "nm_fecha"),
|
|
("cacu.NotaMedica", "Peso (kg)", "nm_masa_corporal"),
|
|
# Flattened JSON paths match by their last segment; unprefixed fields by their words.
|
|
("cacu.BiometriaHematica", "paciente.expediente", "pac_id_hospital"),
|
|
("cacu.BiometriaHematica", "resultados.hemoglobina", "hemoglobina_g_dl"),
|
|
("cacu.BiopsiaCervical", "Fecha de reporte", "bx_fecha_reporte"),
|
|
],
|
|
)
|
|
def test_column_matcher_real_world_headers(target, source, expected):
|
|
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
|
|
|
fields = list(ENTITY_REGISTRY[target].schema.model_fields)
|
|
assert ColumnMatcher().suggest([source], fields)[0].target_field == expected
|
|
|
|
|
|
def test_column_matcher_does_not_guess_from_shared_letters_alone():
|
|
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
|
|
|
fields = list(ENTITY_REGISTRY["cacu.NotaMedica"].schema.model_fields)
|
|
assert ColumnMatcher().suggest(["Observaciones del servicio xyz", "Clave única"], fields)[1].target_field is None
|
|
|
|
|
|
def test_catalog_for_exposes_field_catalog_and_errors_stay_on_field():
|
|
from webapi.imports.schemas.coercion import Catalog
|
|
|
|
catalog = PacienteImportSchema.catalog_for("pac_sexo")
|
|
assert isinstance(catalog, Catalog)
|
|
assert catalog.choices["F"] == "Femenino"
|
|
assert PacienteImportSchema.catalog_for("pac_codigo_postal") is None
|
|
|
|
with pytest.raises(ValidationError) as excinfo:
|
|
PacienteImportSchema(pac_id_hospital="H-1", pac_sexo="X", pac_fecha_nacimiento="1990-01-15")
|
|
(error,) = excinfo.value.errors()
|
|
classified = classify_error(error)
|
|
assert classified.field == "pac_sexo"
|
|
assert classified.category == ErrorCategory.OUT_OF_CATALOG
|
|
assert "no está en el catálogo" in classified.message
|