"""What this module covers: `POST /governance/tea/eeg/preview`, which analyses one EDF (and an ADOS-2 report) in memory and answers a patient-summary bundle without writing to any database, and the `EegPreview` class behind it. Fixtures: `app_client`, the real app over an empty migrated TEA database, with its engine so the tests can count rows; `edf`, a synthetic two-minute EDF from `models/tests/tea/synth_edf.py` (too short to be a valid study, so only its quality part is answered); `ados2_pdf`, a one-page report with a Module 2 score table drawn with reportlab. """ import importlib.util import io from pathlib import Path import pytest from sqlalchemy import text SYNTH = Path(__file__).resolve().parents[2] / "models" / "tests" / "tea" / "synth_edf.py" URL = "/governance/tea/eeg/preview" ROWS = [("Señalar", "1"), ("Gestos descriptivos, convencionales, instrumentales o informativos", "0"), ("Contacto visual inusual", "2"), ("Expresiones faciales dirigidas a otros", "1"), ("Disfrute compartido durante la interacción", "0"), ("Mostrar", "2"), ("Iniciación espontánea de la atención conjunta", "1"), ("Características de las iniciaciones sociales", "1"), ("Calidad general de la relación", "2"), ("Uso estereotipado o idiosincrásico de palabras o frases", "1"), ("Manierismos de manos y dedos y otros manierismos complejos", "2"), ("Intereses inusualmente repetitivos o comportamientos estereotipados", "1")] @pytest.fixture(scope="module") def edf() -> bytes: """A synthetic two-minute EDF, the same file for every test.""" spec = importlib.util.spec_from_file_location("synth_edf", SYNTH) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module.edf_bytes(minutes=2) @pytest.fixture(scope="module") def ados2_pdf() -> bytes: """A report whose Module 2 table lists twelve items with their algorithm scores.""" from reportlab.pdfgen.canvas import Canvas buffer = io.BytesIO() pdf = Canvas(buffer, pagesize=(612, 792)) pdf.setFont("Helvetica", 10) y = 720 for caption, score in [("Afectación Social (AS)", None), *ROWS[:8], ("TOTAL DE AFECTACIÓN SOCIAL", "7"), ("Comportamiento restringido y repetitivo (CRR)", None), *ROWS[8:], ("PUNTAJE TOTAL DE COMPORTAMIENTO RESTRINGIDO Y REPETITIVO (CRR)", "6"), ("PUNTUACIÓN TOTAL GLOBAL (AS + CRR)", "13")]: pdf.drawString(76, y, caption) if score is not None: pdf.drawCentredString(512, y, score) y -= 20 pdf.showPage() pdf.save() return buffer.getvalue() @pytest.fixture def app_client(tmp_path): """The real app over an empty migrated TEA database; yields (client, engine).""" from conftest import base_de from webapi import create_app base = base_de("tea", tmp_path, datos=lambda session: None) app = create_app() app.config.update(TESTING=True) try: with app.test_client() as client: yield client, base.motor finally: base.motor.dispose() def _post(client, **files): return client.post(URL, data={k: (io.BytesIO(v), name) for k, (name, v) in files.items()}, content_type="multipart/form-data") def _types(response): return [e["resource"]["resourceType"] for e in response.json["bundle"]["entry"]] def test_an_edf_is_analysed_and_nothing_is_stored(app_client, edf, monkeypatch): """Pins the summary bundle (report with its quality observations) and zero rows written to `eeg`, `eeg_criterio` and `eeg_metrica`. Fails if the route stores the recording, or answers without the EEG's report.""" client, engine = app_client monkeypatch.delenv("TEA_ALTERACIONES_VALIDADAS", raising=False) response = _post(client, edf=("estudio.edf", edf)) assert response.status_code == 200, response.json assert "DiagnosticReport" in _types(response) and "Procedure" in _types(response) assert "Observation" in _types(response) with engine.connect() as connection: for table in ("eeg", "eeg_criterio", "eeg_metrica"): assert connection.execute(text(f"select count(*) from {table}")).scalar() == 0 def test_a_file_that_is_not_an_edf_is_refused(app_client): """Pins 400 for a recording MNE cannot open and for a missing field. Fails if either answers 200 or 500.""" client, _ = app_client assert _post(client, edf=("estudio.edf", b"no es un edf")).status_code == 400 assert client.post(URL, data={}, content_type="multipart/form-data").status_code == 400 def test_without_a_report_the_bundle_has_no_ados2(app_client, edf): """Pins that the ADOS-2 observation appears only with a readable report. Fails if one is invented.""" client, _ = app_client response = _post(client, edf=("estudio.edf", edf)) assert [e for e in response.json["bundle"]["entry"] if e["resource"]["id"].startswith("ados2-")] == [] def test_an_unreadable_report_gives_a_notice_not_an_error(app_client, edf): """Pins 200 plus a Spanish notice when the attached PDF has no ADOS-2 table. Fails if the route answers 500, drops the EEG, or says nothing about the report.""" client, _ = app_client from reportlab.pdfgen.canvas import Canvas buffer = io.BytesIO() pdf = Canvas(buffer) pdf.drawString(72, 700, "Nota clinica sin tabla") pdf.showPage() pdf.save() response = _post(client, edf=("estudio.edf", edf), ados2=("informe.pdf", buffer.getvalue())) assert response.status_code == 200 assert any("ADOS-2" in aviso for aviso in response.json["avisos"]) assert "DiagnosticReport" in _types(response) def test_without_an_age_the_css_is_not_invented(app_client, edf, ados2_pdf): """Pins the notice when the report gives no CSS and the EDF no age. Fails if a CSS is made up or the notice is lost.""" client, _ = app_client response = _post(client, edf=("estudio.edf", edf), ados2=("informe.pdf", ados2_pdf)) assert response.status_code == 200 assert any("CSS" in aviso for aviso in response.json["avisos"]) def test_a_report_that_is_not_a_pdf_is_refused(app_client, edf): """Pins 400 for an ADOS-2 file that is not a PDF. Fails if text is handed to the document extraction.""" client, _ = app_client assert _post(client, edf=("estudio.edf", edf), ados2=("informe.pdf", b"texto")).status_code == 400 def test_the_ados2_report_is_read_and_scored(app_client, edf, ados2_pdf, monkeypatch): """Pins that the table's items and module reach the bundle's ADOS-2 observation, scored by the platform's scorer at the age the analysis used. Fails if the report is ignored, or its items are lost, or nothing is scored.""" import dataclasses from models.tea.eeg import analyze real = analyze.measure monkeypatch.setattr(analyze, "measure", lambda *args: dataclasses.replace(real(*args), age_months=30.0)) client, engine = app_client response = _post(client, edf=("estudio.edf", edf), ados2=("informe.pdf", ados2_pdf)) assert response.status_code == 200, response.json ados2 = [e["resource"] for e in response.json["bundle"]["entry"] if e["resource"]["id"].startswith("ados2-")] assert len(ados2) == 1 and len(ados2[0]["component"]) > 10, response.json["avisos"] with engine.connect() as connection: assert connection.execute(text("select count(*) from ados2")).scalar() == 0 def test_alterations_are_listed_although_the_validation_flag_is_off(monkeypatch): """Pins `show_alterations=True` over the environment gate in the FHIR builder. Fails if a preview of a valid EEG hides its metrics because `TEA_ALTERACIONES_VALIDADAS` is unset.""" from webapi.fhir import tea monkeypatch.delenv("TEA_ALTERACIONES_VALIDADAS", raising=False) eeg = {"procedimiento_id": "p", "fecha_eeg": "2026-01-01", "calidad": "BUENO", "valido": 1, "nivel": None, "duracion_min": 5, "edad_meses": 24.0, "canales": 19} metric = {"procedimiento_id": "p", "metrica": "ritmo_posterior", "valor": 7.0, "grupo_edad_eeg": "24 meses", "ref_min": 6.0, "ref_mediana": 7.5, "ref_max": 9.0, "modelo": None, "valor_z": -0.4, "estado": "normal"} hidden = tea.eeg_resources(eeg, "x", [metric], [], True) shown = tea.eeg_resources(eeg, "x", [metric], [], True, show_alterations=True) assert len(shown) == len(hidden) + 1