Files
WebApi/tests/test_imports_ados2_document.py

148 lines
6.4 KiB
Python

"""What this module covers: filling `tea.Ados2`'s item columns from the ADOS-2 score table of a PDF read from a SQL
source (`DocumentConnector` with `sql`, the score-table extractor of `extraction.nlp.score_tables`) and merging them
with `on_conflict=upsert` into the row the hospital's table import created, which keeps its header.
Fixtures: `client`, a Flask app over a throwaway TEA database (`conftest.wire_domain`); `hospital`, a SQLite file
standing for the hospital with one ADOS-2 row whose evaluation PDF is a two-page report, prose first and the
Module 2 score table second.
"""
import base64
import io
import json
import sqlite3
import pytest
from sqlalchemy import create_engine, text
# Module 2 rows as the evaluation prints them: description, algorithm score, column.
_ROWS = [
("Señalar", "1", "ado_sa_a6"),
("Gestos descriptivos, convencionales, instrumentales o informativos", "0", "ado_sa_a7"),
("Contacto visual inusual", "2", "ado_sa_b1"),
("Expresiones faciales dirigidas a otros", "1", "ado_sa_b2"),
("Disfrute compartido durante la interacción", "0", "ado_sa_b3"),
("Mostrar", "2", "ado_sa_b5"),
("Iniciación espontánea de la atención conjunta", "1", "ado_sa_b6"),
("Características de las iniciaciones sociales", "1", "ado_sa_b8"),
("Cantidad de comunicación social recíproca", "S/D", "ado_sa_b11"),
("Calidad general de la relación", "2", "ado_sa_b12"),
("Uso estereotipado o idiosincrásico de palabras o frases", "1", "ado_rrb_a4"),
("Interés sensorial inusual en los materiales de juego o en las personas", "0", "ado_rrb_d1"),
("Manierismos de manos y dedos y otros manierismos complejos", "2", "ado_rrb_d2"),
("Intereses inusualmente repetitivos o comportamientos estereotipados", "1", "ado_rrb_d4"),
]
def _evaluation_pdf() -> bytes:
from reportlab.pdfgen.canvas import Canvas
buffer = io.BytesIO()
pdf = Canvas(buffer, pagesize=(612, 792))
pdf.setFont("Helvetica", 10)
pdf.drawString(72, 720, "Evaluación psicológica. Se observa afectación social en el juego libre.")
pdf.showPage()
pdf.setFont("Helvetica", 10)
y = 720
def row(caption, score=None):
nonlocal y
pdf.drawString(76, y, caption)
if score is not None:
pdf.drawCentredString(512, y, score)
y -= 20
row("Afectación Social (AS)")
for caption, score, _ in _ROWS[:10]:
row(caption, score)
social = sum(int(s) for _, s, _ in _ROWS[:10] if s != "S/D")
row("TOTAL DE AFECTACIÓN SOCIAL", str(social))
row("Comportamiento restringido y repetitivo (CRR)")
for caption, score, _ in _ROWS[10:]:
row(caption, score)
restricted = sum(int(s) for _, s, _ in _ROWS[10:])
row("PUNTAJE TOTAL DE COMPORTAMIENTO RESTRINGIDO Y REPETITIVO (CRR)", str(restricted))
row("PUNTUACIÓN TOTAL GLOBAL (AS + CRR)", str(social + restricted))
pdf.showPage()
pdf.save()
return buffer.getvalue()
@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
@pytest.fixture
def hospital(tmp_path):
"""The hospital: `ados2` with one header row and no items, and the ADOS-2 order holding the evaluation PDF."""
url = f"sqlite:///{tmp_path / 'hospital.db'}"
with create_engine(url).begin() as conn:
conn.execute(text("CREATE TABLE ados2 (ado_id TEXT, ado_pac_id INTEGER, ado_ord_id TEXT)"))
conn.execute(text("CREATE TABLE ordenes_estudio (ord_id TEXT, ord_pdf_blob BLOB)"))
conn.execute(text("INSERT INTO ados2 VALUES ('ADO-1', 7, 'ORD-1')"))
conn.execute(text("INSERT INTO ordenes_estudio VALUES ('ORD-1', :pdf)"), {"pdf": _evaluation_pdf()})
return url
def _json_source(records: list[dict]) -> dict:
return {
"source_type": "json",
"target": "tea.Ados2",
"column_mapping": {name: name for name in records[0]},
"payload": {"file_base64": base64.b64encode(json.dumps(records).encode()).decode()},
}
def _document_source(url: str) -> dict:
items = [column for _, _, column in _ROWS]
return {
"source_type": "document",
"target": "tea.Ados2",
"column_mapping": {name: name for name in ["ado_id", *items]},
"payload": {
"target": "tea.Ados2",
"sql": {
"connection_string": url,
"query": "select a.ado_id, a.ado_pac_id, o.ord_pdf_blob from ados2 a "
"join ordenes_estudio o on o.ord_id = a.ado_ord_id",
"column": "ord_pdf_blob",
"key_column": "ado_id",
"fields": {"ado_id": "ado_id", "ado_pac_id": "ado_pac_id"},
},
},
}
def test_the_evaluations_score_table_fills_the_items_of_the_existing_row(client, hospital, wire_domain):
"""Pins down: after the header row is imported, a `document` source over the hospital's ADOS-2 PDF, committed
with upsert, writes each item's algorithm score into its Module 2 column on that same row, leaves an `S/D` item
empty, and keeps the header (module, CSS, patient). Fails if the document's items stop reaching the columns,
the upsert creates a second row or blanks the header, or the module is read from the wrong item set."""
header = {"ado_id": "ADO-1", "ado_pac_id": 7, "ado_modulo": "MODULO_2", "ado_algoritmo": "Menor de 5 años",
"ado_css": 6, "ado_clasificacion": "AUTISMO"}
first = client.post("/imports/commit", json={"sources": [_json_source([header])], "on_conflict": "upsert"})
assert first.status_code == 200, first.get_json()
second = client.post("/imports/commit", json={"sources": [_document_source(hospital)], "on_conflict": "upsert"})
body = second.get_json()
assert second.status_code == 200, body
assert [(r["created"], r["updated"], r["rejected"]) for r in body["results"]] == [(0, 1, 0)]
from persistance import settings
path = settings.settings.tea_database_url.removeprefix("sqlite:///")
con = sqlite3.connect(path)
con.row_factory = sqlite3.Row
rows = con.execute("select * from ados2").fetchall()
assert len(rows) == 1
stored = dict(rows[0])
expected = {column: (None if score == "S/D" else int(score)) for _, score, column in _ROWS}
assert {column: stored[column] for column in expected} == expected
assert (stored["ado_modulo"], stored["ado_css"], stored["ado_pac_id"]) == ("MODULO_2", 6, 7)