"""What this module covers: `CamaCohort.rows` (`webapi.cama_cohort`) and the `/cama/analisis`, `/cama/seguimiento` and `/cama/pacientes` routes over it: eligibility (BI-RADS 4-6, dated and known by the cutoff), the biopsy link (mammogram -> order -> report, never across patients or before the mammogram), pagination, export, patient detail and access control. Fixtures: `cohort_db`, an isolated SQLite engine with six synthetic patients' `Persona`/`Carga`/`Procedimiento`/ `Observacion` rows (`webapi.orchestration.tables.cama.TABLAS`), one load from 2025 and one from 2027; `client`, a minimal Flask app registering only the two CaMa blueprints over `cohort_db`, with an always-authorized access callback. """ from datetime import date, datetime, timezone import pytest from flask import Flask from sqlalchemy import create_engine from sqlalchemy.orm import Session from webapi.orchestration.tables.cama import TABLAS from webapi.cama_analysis import analysis from webapi.cama_cohort import CamaCohort from webapi.seguimiento_cama import blueprint_seguimiento_cama @pytest.fixture def cohort_db(): """Six eligible people, one linked biopsy and one biopsy without a link.""" t = TABLAS engine = create_engine('sqlite:///:memory:') for model in (t.Persona, t.Carga, t.Procedimiento, t.Observacion): model.__table__.create(engine) with Session(engine) as session: session.add_all([ t.Carga(carga_id=1, fuente='test', inicio=datetime(2025, 1, 1, tzinfo=timezone.utc)), t.Carga(carga_id=2, fuente='test', inicio=datetime(2027, 1, 1, tzinfo=timezone.utc)), ]) for patient in range(1, 7): session.add(t.Persona(pac_id=patient, pac_id_hospital=f'T-{patient}', fecha_nacimiento=date(1970, 1, 1))) session.add(t.Procedimiento(procedimiento_id=patient * 10, fuente_tabla='mastografia', fuente_id=str(patient), carga_id=1, pac_id=patient, estudio_id='mastografia', clase='toma', fecha=date(2025, 2, 1))) session.add(t.Procedimiento(procedimiento_id=patient * 10 + 1, padre_id=patient * 10, fuente_tabla='mastografia', fuente_id=str(patient), carga_id=1, pac_id=patient, estudio_id='mastografia', clase='reporte', fecha=date(2025, 2, 2))) session.add(t.Observacion(observacion_id=patient, procedimiento_id=patient * 10 + 1, carga_id=1, pac_id=patient, resultado_id='mastografia.birads', valor_fuente='B5')) for patient, parent, load in ((1, 10, 1), (2, None, 1), (3, 30, 2), (4, 40, 1)): report_date = date(2027, 2, 15) if patient == 4 else date(2025, 2, 15) session.add(t.Procedimiento(procedimiento_id=100 + patient * 2, padre_id=parent, fuente_tabla='biopsiamama', fuente_id=str(patient), carga_id=1, pac_id=patient, estudio_id='biopsia', clase='orden', fecha=date(2025, 2, 10))) session.add(t.Procedimiento(procedimiento_id=101 + patient * 2, padre_id=100 + patient * 2, fuente_tabla='biopsiamama', fuente_id=str(patient), carga_id=1, pac_id=patient, estudio_id='biopsia', clase='reporte', fecha=report_date)) session.add(t.Observacion(observacion_id=100 + patient, procedimiento_id=101 + patient * 2, carga_id=load, pac_id=patient, resultado_id='biopsia.grado', valor_fuente='BENIGNO')) session.commit() yield engine engine.dispose() @pytest.fixture def client(cohort_db): """Configure an explicitly synthetic reader and an authorized test principal.""" app = Flask(__name__) app.register_blueprint(analysis, url_prefix='/cama') app.register_blueprint(blueprint_seguimiento_cama(), url_prefix='/cama') def read(cutoff): with Session(cohort_db) as session: return CamaCohort(session).rows(cutoff) app.config.update(CAMA_COHORT_SYNTHETIC=True, CAMA_COHORT_READER=read, CAMA_COHORT_ACCESS=lambda req: True) return app.test_client() QUERY = '?cohorte=cama_birads_v1&escenario=diagnostico&corte=2026-10-20&meses=0&birads=BIRADS_5' def query(client, cutoff='2026-10-20'): revision = client.get('/cama/analisis/indicadores?corte=' + cutoff).get_json()['revision'] return QUERY.replace('2026-10-20', cutoff) + '&revision=' + revision def test_aggregate_list_detail_and_export_have_one_selection(client): """The published aggregate reconciles with pages, patient details and export.""" aggregate = client.get('/cama/analisis/indicadores?corte=2026-10-20').get_json() assert next(g for g in aggregate['grupos'] if g['codigo'] == 'BIRADS_5')['n'] == 6 selection = query(client) first = client.get('/cama/seguimiento' + selection + '&page_size=2').get_json() assert first['ventana'] == {'meses': 0, 'desde': '2025-02-01', 'hasta': '2026-10-20'} items = [] for page in (1, 2, 3): data = client.get('/cama/seguimiento' + selection + f'&page_size=2&page={page}').get_json() items.extend(data['items']) exported = client.get('/cama/seguimiento/exportacion' + selection).get_json() assert exported['items'] == items and exported['total_items'] == 6 for item in items: detail = client.get('/cama/pacientes/' + item['pac_id'] + selection).get_json() assert detail['item'] == item and detail['corte'] == aggregate['corte'] assert sum(item['biopsia'] == 'BENIGNO' for item in items) == 1 assert client.get('/cama/seguimiento' + selection).get_json()['items'] == items def test_rejects_unknown_and_suppressed_selections_and_denies_access(client): """Unknown filters and small groups cannot silently broaden patient access.""" selection = query(client) assert client.get('/cama/seguimiento' + selection + '&estadio=IV').status_code == 400 assert client.get('/cama/seguimiento' + selection.replace('BIRADS_5', 'BIRADS_4A')).status_code == 403 assert client.get('/cama/seguimiento' + selection.replace('cama_birads_v1', 'otra')).status_code == 400 assert client.get('/cama/seguimiento' + selection.replace(selection[-64:], '0' * 64)).status_code == 409 client.application.config['CAMA_COHORT_ACCESS'] = lambda req: False assert client.get('/cama/seguimiento' + selection).status_code == 403 assert client.get('/cama/seguimiento/exportacion' + selection).status_code == 403 assert client.get('/cama/pacientes/some-id' + selection).status_code == 403 def test_cutoff_excludes_later_clinical_and_load_dates(client): """A report or observation not yet known at the cutoff cannot appear.""" early = query(client, '2025-02-09') rows = client.get('/cama/seguimiento' + early).get_json()['items'] assert len(rows) == 6 and all(row['biopsia'] is None for row in rows) empty = query(client, '2025-02-01').replace('&birads=BIRADS_5', '') response = client.get('/cama/seguimiento' + empty).get_json() assert response['items'] == [] and response['ventana']['desde'] == '2025-02-01' def test_links_and_load_dates_are_distinct(client, cohort_db): """A missing link and a late load cannot supply a diagnosis before cutoff.""" ids = {i: str(i) for i in range(1, 5)} data = client.get('/cama/seguimiento' + query(client)).get_json() rows = {item['pac_id']: item for item in data['items']} assert rows[ids[1]]['biopsia'] == 'BENIGNO' assert rows[ids[2]]['biopsia'] is None and rows[ids[2]]['biopsia_fecha'] is None assert rows[ids[3]]['biopsia'] is None and rows[ids[3]]['biopsia_fecha'] == '2025-02-15' assert rows[ids[4]]['biopsia'] is None and rows[ids[4]]['biopsia_fecha'] is None later = client.get('/cama/seguimiento' + query(client, '2027-12-01')).get_json() rows_later = {item['pac_id']: item for item in later['items']} assert rows_later[ids[3]]['biopsia'] == 'BENIGNO' assert rows_later[ids[4]]['biopsia_fecha'] == '2027-02-15' assert set(rows) == set(rows_later) def test_full_application_registers_cohort_and_regular_followup(client): """The regular follow-up uses the configured reader instead of unrelated fixture rows.""" from webapi import create_app app = create_app() app.config.update(client.application.config) full = app.test_client() assert full.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 200 assert full.get('/cama/seguimiento?corte=2026-10-20&meses=0').get_json()['paginacion']['total_items'] == 6 assert full.get('/cama/seguimiento?meses=12&resultado=INVASOR').status_code == 400 def test_windows_and_disabled_provider(client): """Regular windows remain available and a missing reader returns unavailable.""" selection = query(client).replace('&meses=0', '&meses=1').replace('&birads=BIRADS_5', '') body = client.get('/cama/seguimiento' + selection).get_json() assert body['items'] == [] and body['ventana']['desde'] == '2026-09-21' client.application.config['CAMA_COHORT_READER'] = None assert client.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 503 def test_newer_noneligible_result_changes_revision_and_excludes_patient(client, cohort_db): """The latest reported result is selected before checking BI-RADS eligibility.""" previous = query(client) with Session(cohort_db) as session: session.add(TABLAS.Procedimiento(procedimiento_id=200, fuente_tabla='mastografia', fuente_id='new', carga_id=1, pac_id=6, estudio_id='mastografia', clase='toma', fecha=date(2025, 4, 1))) session.add(TABLAS.Procedimiento(procedimiento_id=201, padre_id=200, fuente_tabla='mastografia', fuente_id='new', carga_id=1, pac_id=6, estudio_id='mastografia', clase='reporte', fecha=date(2025, 4, 2))) session.add(TABLAS.Observacion(observacion_id=200, procedimiento_id=201, carga_id=1, pac_id=6, resultado_id='mastografia.birads', valor_fuente='B1')) session.commit() assert client.get('/cama/seguimiento' + previous).status_code == 409 aggregate = client.get('/cama/analisis/indicadores?corte=2026-10-20').get_json() assert next(g for g in aggregate['grupos'] if g['codigo'] == 'BIRADS_5')['n'] == 5 assert len(client.get('/cama/seguimiento' + query(client)).get_json()['items']) == 5 def test_cross_patient_links_and_observations_are_not_used(cohort_db): """A mismatched patient or an order before the mammogram cannot supply a result.""" with Session(cohort_db) as session: # The biopsy order is linked to patient 1's mammogram but belongs to patient 2. session.get(TABLAS.Procedimiento, 102).pac_id = 2 # Patient 3's otherwise linked biopsy order predates the mammogram. session.get(TABLAS.Procedimiento, 106).fecha = date(2025, 1, 1) # The BI-RADS observation belongs to a different patient. session.get(TABLAS.Observacion, 6).pac_id = 5 session.commit() reader = CamaCohort(session) rows = {row['pac_id']: row for row in reader.rows(date(2027, 12, 1))} assert '6' not in rows assert rows['1']['biopsia'] is None assert rows['3']['biopsia'] is None