File size: 7,096 Bytes
4a0825f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import pytest
import json
import os
from unittest.mock import patch
from src.utils.auth import create_dev_token

def test_health_check(client_main):
    response = client_main.get("/")
    assert response.status_code == 200
    assert response.json() == {"status": "healthy", "message": "Medical AI Backend is running"}

def test_seed_patient_data(client_main, clean_db):
    patient_id = "test-patient"
    response = client_main.post(f"/patient/seed?patient_id={patient_id}")
    assert response.status_code == 200
    assert response.json()["status"] == "success"

    # Verify seed data exists in DB
    patient = clean_db.db["patients"].get(patient_id)
    assert patient is not None
    observations = clean_db._get_data("observations", {"patient_id": patient_id})
    assert len(observations) == 3

def test_get_patient_summary(client_main, clean_db):
    patient_id = "summary-patient"
    # Seed data
    client_main.post(f"/patient/seed?patient_id={patient_id}")

    # Fetch summary
    response = client_main.get(f"/patient/{patient_id}")
    assert response.status_code == 200
    summary = response.json()
    assert summary["patient"] == "Demo Patient"
    assert len(summary["recent_observations"]) == 3

def test_set_llm_provider(client_main):
    response = client_main.post("/config/llm?provider=openrouter")
    assert response.status_code == 200
    assert response.json() == {"status": "success", "provider": "openrouter"}

def test_process_pipeline_standard(client_main, clean_db):
    patient_id = "patient-standard"
    client_main.post(f"/patient/seed?patient_id={patient_id}")

    payload = {
        "prompt": "Hi, I have a slight headache.",
        "patient_id": patient_id,
        "mode": "Standard Triage"
    }
    response = client_main.post("/process", json=payload)
    assert response.status_code == 200
    data = response.json()
    assert "messages" in data
    assert "final_state" in data
    assert "session_id" in data

    # Verify communications were saved (persistence node)
    session_id = data["session_id"]
    comms = clean_db._get_data("communications", {"session_id": session_id})
    assert len(comms) > 0

def test_process_pipeline_cdm(client_main, clean_db):
    patient_id = "patient-cdm"
    client_main.post(f"/patient/seed?patient_id={patient_id}")

    payload = {
        "prompt": "How are my blood sugar trends looking?",
        "patient_id": patient_id,
        "mode": "CDM Proactive"
    }
    response = client_main.post("/process", json=payload)
    assert response.status_code == 200
    data = response.json()
    assert "messages" in data
    assert "final_state" in data
    assert data["final_state"]["trend_analysis"] != ""

def test_process_stream(client_main, clean_db):
    patient_id = "patient-stream"
    client_main.post(f"/patient/seed?patient_id={patient_id}")

    payload = {
        "prompt": "Hello",
        "patient_id": patient_id,
        "mode": "Standard Triage"
    }
    response = client_main.post("/process_stream", json=payload)
    assert response.status_code == 200
    assert "text/event-stream" in response.headers["content-type"]
    
    # Read SSE events
    events = []
    for line in response.iter_lines():
        if line.startswith("data: "):
            event_data = json.loads(line[6:])
            events.append(event_data)

    assert len(events) > 0
    node_events = [e for e in events if e["type"] == "node"]
    assert len(node_events) > 0
    
    end_events = [e for e in events if e["type"] == "end"]
    assert len(end_events) == 1
    assert "final_state" in end_events[0]

def test_mcp_endpoint(client_main, clean_db):
    # Test MCP list_tools
    req = {"method": "list_tools", "params": {}, "id": 1}
    response = client_main.post("/mcp", json=req)
    assert response.status_code == 200
    res_data = response.json()
    assert "result" in res_data
    tools = res_data["result"]
    assert any(t["name"] == "analyze_health_trends" for t in tools)

    # Test MCP call_tool
    patient_id = "mcp-patient"
    client_main.post(f"/patient/seed?patient_id={patient_id}")
    call_req = {
        "method": "call_tool",
        "params": {"name": "analyze_health_trends", "arguments": {"patient_id": patient_id}},
        "id": 2
    }
    response2 = client_main.post("/mcp", json=call_req)
    assert response2.status_code == 200
    res_data2 = response2.json()
    assert "result" in res_data2
    analysis, _ = res_data2["result"]
    assert "Trend Analysis Report" in analysis

def test_fhir_rest_endpoints(client_main, clean_db):
    patient_id = "fhir-rest-patient"
    client_main.post(f"/patient/seed?patient_id={patient_id}")

    # Patient
    res = client_main.get(f"/Patient/{patient_id}")
    assert res.status_code == 200
    assert res.json()["resourceType"] == "Patient"

    # Observation
    res_obs = client_main.get(f"/Observation?patient={patient_id}")
    assert res_obs.status_code == 200
    assert isinstance(res_obs.json(), list)
    assert len(res_obs.json()) == 3

# App.py endpoints (Authenticated)
def test_authenticated_endpoints(client_app, clean_db):
    patient_id = "auth-patient-123"
    token = create_dev_token(patient_id)
    headers = {"Authorization": f"Bearer {token}"}

    # 1. Seed data
    res_seed = client_app.post("/patient/seed", headers=headers)
    assert res_seed.status_code == 200
    assert res_seed.json()["status"] == "success"

    # 2. Get Summary
    res_sum = client_app.get("/patient/summary", headers=headers)
    assert res_sum.status_code == 200
    assert res_sum.json()["patient"] == "Authenticated Patient"

    # 3. Process request
    payload = {
        "prompt": "I need some support.",
        "mode": "Standard Triage"
    }
    res_proc = client_app.post("/process", json=payload, headers=headers)
    assert res_proc.status_code == 200
    proc_data = res_proc.json()
    session_id = proc_data["session_id"]
    assert session_id is not None

    # 4. List Sessions
    res_sess = client_app.get("/sessions", headers=headers)
    assert res_sess.status_code == 200
    assert len(res_sess.json()) > 0
    assert any(s["id"] == session_id for s in res_sess.json())

    # 5. Get Session History
    res_hist = client_app.get(f"/sessions/{session_id}/history", headers=headers)
    assert res_hist.status_code == 200
    assert len(res_hist.json()) > 0

def test_clinician_feedback_score(client_app):
    token = create_dev_token("feedback-user")
    headers = {"Authorization": f"Bearer {token}"}
    payload = {
        "trace_id": "test-trace-123",
        "score": 5,
        "feedback": "Excellent response quality."
    }
    
    csv_file = "clinician_scores.csv"
    if os.path.exists(csv_file):
        os.remove(csv_file)

    try:
        response = client_app.post("/feedback/score", json=payload, headers=headers)
        assert response.status_code == 200
        assert response.json() == {"status": "success", "message": "Score saved successfully"}
        assert os.path.exists(csv_file)
    finally:
        if os.path.exists(csv_file):
            os.remove(csv_file)