import pytest from pydantic import ValidationError from webapi.imports.mapping.column_matcher import suggest_mapping 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_cacu_paciente_keeps_her_date_of_death(): """Pins down: a CaCu patient's `pac_fecha_defuncion` is imported (the survival scenario's outcome), and an alive patient has none. Fails if the schema drops the column again: every CaCu death would be lost on import and the survival model would train with no deaths.""" from datetime import date dead = PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento="1960-03-01", pac_fecha_defuncion="2025-07-09") alive = PacienteImportSchema(pac_id_hospital="H-2", pac_fecha_nacimiento="1960-03-01") assert dead.pac_fecha_defuncion == date(2025, 7, 9) and alive.pac_fecha_defuncion is None def test_tea_pacientes_schema_is_fully_optional(): schema = PacientesImportSchema() assert schema.pac_id_hospital is None def test_tea_neuropediatrics_note_takes_icd10_with_or_without_the_dot(): """Pins down: the note's ICD-10 is upper-cased and accepted with or without its dot; anything else is rejected. Fails if the pattern of `neu_cie_codigo` changes.""" from webapi.imports.schemas.tea.evaluacion_neuropediatrica import EvaluacionNeuropediatricaImportSchema as Nota assert Nota(neu_cie_codigo=" f84.0 ").neu_cie_codigo == "F84.0" assert Nota(neu_cie_codigo="F840").neu_cie_codigo == "F840" with pytest.raises(ValidationError): Nota(neu_cie_codigo="autismo") 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(): targets = ["pac_id_hospital", "pac_sexo", "pac_fecha_nacimiento"] suggestions = suggest_mapping( ["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(): # two source columns that would both match "pac_sexo" exactly-ish suggestions = suggest_mapping(["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 catalog = Catalog(SexoBiologico, SEXO_BIOLOGICO_ALIAS) assert catalog.coerce(" femenino ") == "Femenino" assert catalog.coerce("m") == "Masculino" assert catalog.coerce("") is None with pytest.raises(ValueError, match="no está en el catálogo"): catalog.coerce("X") 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_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 catalog = Catalog(BIRADS, BIRADS_ALIAS) for value in ("4A", "BI-RADS 4B", "bi-rads 4c"): assert catalog.coerce(value) == "B4" def test_column_matcher_handles_accents_prefixes_and_global_one_to_one(): targets = ["pac_id_hospital", "pac_sexo", "pac_codigo_postal", "pac_fecha_nacimiento"] by_source = { s.source_column: s for s in suggest_mapping(["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 = suggest_mapping(["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 suggest_mapping([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 suggest_mapping(["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 def test_catalog_aliases_for_values_the_indicator_kit_uses(): """Hospital spellings the indicator kit's own synthetic sources use must not be rejected at import.""" from webapi.imports.schemas.cacu.biopsia_cervical import BiopsiaCervicalImportSchema from webapi.imports.schemas.cacu.citologia_cervical import CitologiaCervicalImportSchema from webapi.imports.schemas.cama.ordenes_estudio import OrdenesEstudioImportSchema as CamaOrdenes from webapi.imports.schemas.tea.ordenes_estudio import OrdenesEstudioImportSchema as TeaOrdenes assert BiopsiaCervicalImportSchema(pac_id_hospital="H", bx_cin_grado="CIN1").bx_cin_grado == "LIEBG" assert BiopsiaCervicalImportSchema(pac_id_hospital="H", bx_cin_grado="nic 3").bx_cin_grado == "LIEAG" cito = CitologiaCervicalImportSchema(pac_id_hospital="H", cit_celulas_escamosas="NEGATIVO") assert cito.cit_celulas_escamosas == "NORMAL" assert CamaOrdenes(pac_id_hospital="H", ord_numero_hospital=1, ord_tipo_estudio="MASTOGRAFIA").ord_tipo_estudio == "MASTOGRAFIA" assert TeaOrdenes(ord_tipo_estudio="electroencefalograma").ord_tipo_estudio == "EEG" assert TeaOrdenes(ord_tipo_estudio=" evaluacion_psicologica_tea ").ord_tipo_estudio == "ADOS2"