"""Cover the analysis job routes with captured launches and saved job files. Fixtures: analysis_client supplies the Flask routes, a temporary job directory and EEG rows. Fails if scope or cluster options are lost, or persisted jobs change their API shape or order. """ import json import os import sys from types import SimpleNamespace import pytest from flask import Flask from sqlalchemy.pool import StaticPool from sqlmodel import Session, create_engine from core.tea.models import Eeg from persistance.tea import eeg_repository from webapi import detached_jobs from webapi.blueprints.governance import governance_bp URL = "/governance/tea/eeg/analyze-jobs" SUMMARY = {"pending": 3, "valid": 1, "not_valid": 1, "failed": 1} @pytest.fixture def analysis_client(tmp_path, monkeypatch): """Supply EEG IDs 1 and 2 (numeric) and two UUID ids, and capture child launches to detect invalid launches and lost options.""" monkeypatch.setenv("INDICADORES_DIR", str(tmp_path)) monkeypatch.delenv("DASK_SCHEDULER_ADDRESS", raising=False) monkeypatch.delenv("EEG_ANALYSIS_CLUSTER", raising=False) launches = [] engine = create_engine("sqlite://", poolclass=StaticPool) Eeg.__table__.create(engine) with Session(engine) as session: session.add_all([Eeg(eeg_id="1", eeg_estudio=b"edf"), Eeg(eeg_id="2"), Eeg(eeg_id="ed257fbd-61d5-4c9c-bb72-00c4ec550961", eeg_estudio=b"edf"), Eeg(eeg_id="a735a43f-376a-403a-b19f-13670130152a", eeg_estudio=b"edf")]) session.commit() def popen(argv, **kwargs): launches.append((argv[4:], kwargs["env"])) return SimpleNamespace(pid=os.getpid()) monkeypatch.setattr(detached_jobs.subprocess, "Popen", popen) monkeypatch.setattr(eeg_repository, "open_session", lambda: Session(engine)) app = Flask(__name__) app.register_blueprint(governance_bp, url_prefix="/governance") yield app.test_client(), launches engine.dispose() @pytest.mark.parametrize("body,flags", [ ({}, []), ({"all": False}, []), ({"all": True}, ["--all"]), ({"limit": 4}, ["--limit", "4"]), ({"ids": [1, 2]}, ["--ids", "1,2"]), ({"ids": ["ed257fbd-61d5-4c9c-bb72-00c4ec550961", "a735a43f-376a-403a-b19f-13670130152a"]}, ["--ids", "ed257fbd-61d5-4c9c-bb72-00c4ec550961,a735a43f-376a-403a-b19f-13670130152a"]), ]) def test_launch_scope(analysis_client, tmp_path, body, flags): """Pin scope flags, response fields and the progress directory. Fail if launch wiring changes.""" client, launches = analysis_client response = client.post(URL, json=body) assert response.status_code == 202 assert launches[0][0] == [sys.executable, "-m", "models", "tea", "analyze", *flags, "--cluster", "auto"] assert response.json.keys() == {"id", "iniciado", "estado", "codigo", "salida", "error", "cluster", "ids", "summary"} folder = tmp_path / "analisis_eeg" / response.json["id"] assert launches[0][1]["RUN_PROGRESS_DIR"] == str(folder) assert response.json["ids"] == ([str(i) for i in body["ids"]] if "ids" in body else None) assert response.json["cluster"] is response.json["summary"] is None @pytest.mark.parametrize("choice,mode,scheduler", [ ({"mode": "auto"}, "remote", "tcp://inherited:8786"), ({"mode": "local"}, "local", None), ({"mode": "sync"}, "sync", "tcp://inherited:8786"), ({"mode": "remote"}, "remote", "tcp://inherited:8786"), ({"mode": "remote", "scheduler": "tcp://chosen:8786"}, "remote", "tcp://chosen:8786"), ]) def test_cluster_choice(analysis_client, monkeypatch, choice, mode, scheduler): """Pin the cluster flag and training-style child environment. Fail if either loses the requested choice.""" client, launches = analysis_client monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", "remote") monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://inherited:8786") response = client.post(URL, json={"cluster": choice}) assert response.status_code == 202 argv, env = launches[0] assert argv[-2:] == ["--cluster", choice["mode"]] assert env["EEG_ANALYSIS_CLUSTER"] == mode assert env.get("DASK_SCHEDULER_ADDRESS") == scheduler assert response.json["cluster"] == (dict(choice, scheduler=scheduler) if mode == choice["mode"] == "remote" else choice) assert os.environ["DASK_SCHEDULER_ADDRESS"] == "tcp://inherited:8786" @pytest.mark.parametrize("body", [ [], {"all": 1}, {"limit": 0}, {"limit": True}, {"ids": []}, {"ids": [True]}, {"ids": None}, {"ids": ["a,b"]}, {"ids": [" "]}, {"ids": ["x" * 65]}, {"ids": [1], "all": True}, {"ids": [1], "limit": 2}, {"all": True, "limit": 2}, {"cluster": {"mode": "remote"}}, {"cluster": {"mode": "invalid"}}, ]) def test_invalid_options(analysis_client, body): """Pin 400 for invalid options. Fail if malformed scopes or cluster choices launch a child.""" client, launches = analysis_client assert client.post(URL, json=body).status_code == 400 assert not launches def test_unknown_eeg_ids(analysis_client): """Pin 404 and the missing IDs. Fail if an unknown EEG reaches the child.""" client, launches = analysis_client response = client.post(URL, json={"ids": [1, 99, 98]}) assert response.status_code == 404 assert "98, 99" in response.json["error"] assert not launches def test_refuses_second_analysis(analysis_client): """Pin the running-job conflict. Fail if a blank request can launch a concurrent analysis.""" client, launches = analysis_client assert client.post(URL).status_code == 202 assert client.post(URL).status_code == 409 assert len(launches) == 1 def test_saved_jobs_report_summary_and_list_newest_first(analysis_client, tmp_path): """Pin summary parsing after exit and descending job order. Fail if a running job exposes counts.""" client, _ = analysis_client older, newer = "20260101T000000-aaaaaa", "20260102T000000-bbbbbb" for job_id in (newer, older): folder = tmp_path / "analisis_eeg" / job_id folder.mkdir(parents=True) (folder / "job.json").write_text(json.dumps({"id": job_id, "pid": os.getpid(), "iniciado": job_id})) (folder / "stdout.log").write_text(f"analysis output\nsummary: {json.dumps(SUMMARY)}\n") if job_id == older: (folder / "exit").write_text("1\n") jobs = client.get(URL).json assert [job["id"] for job in jobs] == [newer, older] assert jobs[0]["estado"] == "en_curso" and jobs[0]["summary"] is None assert jobs[1]["estado"] == "fallido" and jobs[1]["summary"] == SUMMARY assert client.get(f"{URL}/{older}").json == jobs[1] assert client.get(f"{URL}/unknown").status_code == 404