Files
WebApi/tests/test_imports_relacion_ados2.py

140 lines
8.4 KiB
Python

"""What this module covers: the ADOS-2 association model's import targets (`tea.RelacionAdos2` and
`tea.RelacionAdos2Paciente`): their registration in `/imports/targets` with the natural keys the tables' unique
constraints define, the upsert merge on those keys through the import service (a re-import updates in place
instead of duplicating), and the schemas' validations (probabilities and q within [0, 1], the confidence
interval's order, the outcome code per level, the cataloged biomarker and level, the bounded key columns).
Fixtures: `client`, a Flask app over a throwaway TEA database (`conftest.wire_domain`).
"""
import base64
import json
import pytest
@pytest.fixture(scope="module")
def client(wire_domain):
wire_domain("tea")
from webapi import create_app
app = create_app()
app.config.update(TESTING=True)
with app.test_client() as test_client:
yield test_client
def _json_source(records: list[dict], *, target: str) -> dict:
raw = json.dumps(records).encode()
return {
"source_type": "json",
"target": target,
"column_mapping": {name: name for name in records[0]},
"payload": {"file_base64": base64.b64encode(raw).decode()},
}
# One item row (an item meaning code) and one domain row (the total CSS) of a fitted model version, as the `tea`
# library writes them.
_MODELO_ITEM = {
"rel_id": "rel-1", "rel_version": "0.9.0", "rel_nivel": "item", "rel_validado": 0, "rel_n_cohorte": 42,
"rel_biomarcador": "RITMO_POSTERIOR", "rel_zona": "occipital", "rel_tipo": "item",
"rel_resultado": "ados2_item_11", "rel_evento": ">=1", "rel_or": 3.5, "rel_ic_inf": 1.4, "rel_ic_sup": 8.7,
"rel_q": 0.02,
}
_MODELO_DOMINIO = {
"rel_id": "rel-2", "rel_version": "0.9.0", "rel_nivel": "item", "rel_validado": 0, "rel_n_cohorte": 42,
"rel_biomarcador": "RITMO_POSTERIOR", "rel_zona": "occipital", "rel_tipo": "dominio",
"rel_resultado": "CSS", "rel_evento": ">=8", "rel_or": 0.8, "rel_ic_inf": 0.4, "rel_ic_sup": 1.6,
"rel_q": 0.3,
}
# The probabilities of one EEG for both association rows, by the model.
_PACIENTE_1 = {"rap_id": "rap-1", "rap_rel_id": "rel-1", "rap_eeg_id": "eeg-1", "rap_valor_z": -2.5,
"rap_probabilidad": 0.81, "rap_probabilidad_referencia": 0.22}
_PACIENTE_2 = {"rap_id": "rap-2", "rap_rel_id": "rel-2", "rap_eeg_id": "eeg-1", "rap_valor_z": -2.5,
"rap_probabilidad": 0.35, "rap_probabilidad_referencia": 0.4}
def test_targets_list_the_association_tables_with_their_natural_keys(client):
"""Pins down: `/imports/targets` exposes both association tables with the conflict fields of the tables' unique
constraints (uq_relacion_ados2, uq_relacion_ados2_paciente), so `on_conflict=upsert` merges on them, and lists
them as fields to map. Fails if a target is deregistered or its conflict fields drift from the constraints."""
targets = {t["key"]: t for t in client.get("/imports/targets").get_json()["targets"]}
modelo, paciente = targets["tea.RelacionAdos2"], targets["tea.RelacionAdos2Paciente"]
assert modelo["conflict_fields"] == ["rel_version", "rel_biomarcador", "rel_zona", "rel_resultado"]
assert paciente["conflict_fields"] == ["rap_rel_id", "rap_eeg_id"]
assert {"rel_version", "rel_biomarcador", "rel_zona", "rel_resultado"} <= {f["name"] for f in modelo["fields"]}
assert {"rap_rel_id", "rap_eeg_id"} <= {f["name"] for f in paciente["fields"]}
def test_model_and_patient_rows_import_and_reimport_upserts_on_the_natural_keys(client):
"""Pins down: both tables load through the import service and a second import of the same rows updates in
place (created 0, nothing duplicated), keeping the value the later import carried. Fails if the conflict
fields stop matching the natural key (rows would duplicate) or the upsert stops updating."""
fuentes = [_json_source([_MODELO_ITEM, _MODELO_DOMINIO], target="tea.RelacionAdos2"),
_json_source([_PACIENTE_1, _PACIENTE_2], target="tea.RelacionAdos2Paciente")]
body = client.post("/imports/commit", json={"sources": fuentes, "on_conflict": "upsert"}).get_json()
assert [(r["target"], r["created"], r["updated"], r["rejected"]) for r in body["results"]] == [
("tea.RelacionAdos2", 2, 0, 0), ("tea.RelacionAdos2Paciente", 2, 0, 0)]
cambiada = {**_PACIENTE_1, "rap_probabilidad": 0.55}
otra_vez = [_json_source([_MODELO_ITEM, _MODELO_DOMINIO], target="tea.RelacionAdos2"),
_json_source([cambiada, _PACIENTE_2], target="tea.RelacionAdos2Paciente")]
body = client.post("/imports/commit", json={"sources": otra_vez, "on_conflict": "upsert"}).get_json()
assert [(r["created"], r["updated"], r["rejected"]) for r in body["results"]] == [(0, 2, 0), (0, 2, 0)]
filas = client.get("/data/tea.RelacionAdos2Paciente", query_string={"limit": 500}).get_json()["rows"]
assert len(filas) == 2
assert next(f for f in filas if f["rap_id"] == "rap-1")["rap_probabilidad"] == 0.55
def test_invalid_model_rows_are_rejected(client):
"""Pins down: a model row with an out-of-range q, a non-positive odds ratio, an inverted confidence
interval, an unknown level or biomarker, an outcome code that doesn't match its level (`CSS` as an item, a
domain code instead of `CSS`), or an over-long key is rejected, none of it written. Fails if the schema loses one of those validations (the staging is
permissive; without them nothing else catches them)."""
casos = [
{**_MODELO_ITEM, "rel_id": "rel-m1", "rel_version": "v" * 33},
{**_MODELO_ITEM, "rel_id": "rel-m2", "rel_version": "0.9.1", "rel_q": 1.5},
{**_MODELO_ITEM, "rel_id": "rel-m3", "rel_version": "0.9.2", "rel_or": 0},
{**_MODELO_ITEM, "rel_id": "rel-m4", "rel_version": "0.9.3", "rel_ic_inf": 9.0, "rel_ic_sup": 4.0},
{**_MODELO_ITEM, "rel_id": "rel-m5", "rel_version": "0.9.4", "rel_nivel": "itemm"},
{**_MODELO_ITEM, "rel_id": "rel-m6", "rel_version": "0.9.5", "rel_tipo": "item", "rel_resultado": "CSS"},
{**_MODELO_ITEM, "rel_id": "rel-m7", "rel_version": "0.9.6", "rel_biomarcador": "ritmo posterior"},
{**_MODELO_DOMINIO, "rel_id": "rel-m8", "rel_version": "0.9.7", "rel_resultado": "SA"},
]
body = client.post("/imports/commit", json={"sources": [_json_source(casos, target="tea.RelacionAdos2")],
"on_conflict": "upsert"}).get_json()
resultado = body["results"][0]
assert resultado["created"] == 0 and resultado["rejected"] == len(casos)
campos = {e["field"] for e in resultado["errors"]}
assert {"rel_version", "rel_q", "rel_or", "rel_nivel", "rel_biomarcador", "<entre campos>"} <= campos
filas = client.get("/data/tea.RelacionAdos2", query_string={"limit": 500}).get_json()["rows"]
assert not [f for f in filas if f["rel_id"].startswith("rel-m")]
def test_per_module_column_code_is_rejected_as_an_item_outcome(client):
"""Pins down: an item outcome given as a module's column code (`sa_b9`, a different item in each module) is
rejected with a cross-field error. Fails if the schema accepts column codes again, which would break the
natural key and the observed-outcome join across modules."""
fila = {**_MODELO_ITEM, "rel_id": "rel-c1", "rel_version": "0.9.8", "rel_resultado": "sa_b9"}
body = client.post("/imports/commit", json={"sources": [_json_source([fila], target="tea.RelacionAdos2")],
"on_conflict": "upsert"}).get_json()
resultado = body["results"][0]
assert (resultado["created"], resultado["rejected"]) == (0, 1)
assert {e["field"] for e in resultado["errors"]} == {"<entre campos>"}
def test_invalid_patient_rows_are_rejected(client):
"""Pins down: a probability outside [0, 1] (the model's or the reference's) is rejected. Fails if the
Bounded validation loosens, since a probability over 1 would silently skew what the screen shows."""
buena = {**_PACIENTE_1, "rap_id": "rap-ok", "rap_rel_id": "rel-9"}
casos = [buena,
{**buena, "rap_id": "rap-m1", "rap_probabilidad": 1.2},
{**buena, "rap_id": "rap-m2", "rap_probabilidad_referencia": -0.1}]
body = client.post("/imports/commit", json={"sources": [_json_source(casos, target="tea.RelacionAdos2Paciente")],
"on_conflict": "upsert"}).get_json()
resultado = body["results"][0]
assert (resultado["created"], resultado["rejected"]) == (1, 2)
assert {e["field"] for e in resultado["errors"]} == {"rap_probabilidad", "rap_probabilidad_referencia"}