File size: 13,228 Bytes
c4f5f25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
"""
End-to-end integration tests for the complete workflow.
Tests the full pipeline from input to output with real services.
"""

import pytest
import asyncio
from unittest.mock import Mock, patch
from fastapi.testclient import TestClient
from src.main import create_app
from src.state import PatientInput
from src.workflow import create_guild


class TestEndToEndWorkflow:
    """Test complete end-to-end workflows."""

    @pytest.fixture
    def client(self):
        """Create test client."""
        app = create_app()
        return TestClient(app)

    @pytest.fixture
    def guild(self):
        """Create workflow guild for testing."""
        return create_guild()

    def test_complete_biomarker_analysis_workflow(self, client):
        """Test the complete biomarker analysis workflow via API."""
        # Input data
        payload = {
            "biomarkers": {
                "Glucose": 140,
                "HbA1c": 10.0,
                "Hemoglobin": 11.5,
                "MCV": 75
            },
            "patient_context": {
                "age": 45,
                "gender": "male",
                "symptoms": ["fatigue", "thirst"]
            }
        }

        # Make API call
        response = client.post("/analyze/structured", json=payload)
        
        # Verify response structure
        assert response.status_code == 200
        data = response.json()
        assert "analysis" in data
        assert "primary_findings" in data["analysis"]
        assert "critical_alerts" in data["analysis"]
        assert "recommendations" in data["analysis"]
        assert "biomarker_flags" in data["analysis"]
        
        # Verify content
        findings = data["analysis"]["primary_findings"]
        assert len(findings) > 0
        assert all("condition" in f for f in findings)
        assert all("confidence" in f for f in findings)
        
        # Verify biomarker flags
        flags = data["analysis"]["biomarker_flags"]
        assert len(flags) > 0
        glucose_flag = next((f for f in flags if f["name"] == "Glucose"), None)
        assert glucose_flag is not None
        assert glucose_flag["value"] == 140
        assert glucose_flag["status"] == "high"

    def test_medical_qa_workflow(self, client):
        """Test the medical Q&A workflow via API."""
        payload = {
            "question": "What are the symptoms of diabetes?",
            "context": {
                "patient_age": 45,
                "gender": "male"
            }
        }

        response = client.post("/ask", json=payload)
        
        assert response.status_code == 200
        data = response.json()
        assert "answer" in data
        assert "content" in data["answer"]
        assert "sources" in data["answer"]
        
        # Verify answer content
        assert len(data["answer"]["content"]) > 100
        assert "diabetes" in data["answer"]["content"].lower()
        
        # Verify sources
        sources = data["answer"]["sources"]
        assert len(sources) > 0
        assert all("title" in s for s in sources)
        assert all("snippet" in s for s in sources)

    def test_knowledge_base_search_workflow(self, client):
        """Test the knowledge base search workflow."""
        payload = {
            "query": "diabetes management guidelines",
            "top_k": 5
        }

        response = client.post("/search", json=payload)
        
        assert response.status_code == 200
        data = response.json()
        assert "results" in data
        assert "total_found" in data
        
        results = data["results"]
        assert len(results) > 0
        assert all("title" in r for r in results)
        assert all("score" in r for r in results)
        
        # Verify relevance
        assert any("diabetes" in r["title"].lower() for r in results)

    @pytest.mark.asyncio
    async def test_workflow_state_transitions(self, guild):
        """Test state transitions through the workflow."""
        # Create patient input
        patient_input = PatientInput(
            biomarkers={"Glucose": 140, "HbA1c": 10.0},
            patient_context={"age": 45, "gender": "male"},
            model_prediction={"disease": "Diabetes", "confidence": 0.9}
        )

        # Run workflow
        with patch('src.workflow.logger'):
            result = await guild.workflow.ainvoke(patient_input)
        
        # Verify final state
        assert "final_response" in result
        assert "agent_outputs" in result
        
        # Verify all agents executed
        agents = ["biomarker_analyzer", "disease_explainer", "biomarker_linker",
                 "clinical_guidelines", "confidence_assessor", "response_synthesizer"]
        
        for agent in agents:
            assert agent in result["agent_outputs"]
            assert result["agent_outputs"][agent] is not None

    def test_error_handling_workflow(self, client):
        """Test error handling in workflows."""
        # Test with invalid biomarkers
        payload = {
            "biomarkers": {
                "Glucose": "invalid",  # Should be number
                "HbA1c": 10.0
            }
        }

        response = client.post("/analyze/structured", json=payload)
        
        assert response.status_code == 422
        data = response.json()
        assert "detail" in data or "details" in data

    def test_concurrent_requests(self, client):
        """Test handling concurrent requests."""
        import threading
        import time

        results = []
        
        def make_request():
            payload = {
                "biomarkers": {"Glucose": 120, "HbA1c": 6.5},
                "patient_context": {"age": 30, "gender": "female"}
            }
            response = client.post("/analyze/structured", json=payload)
            results.append(response.status_code)
        
        # Create 5 concurrent requests
        threads = []
        for _ in range(5):
            thread = threading.Thread(target=make_request)
            threads.append(thread)
            thread.start()
        
        # Wait for all threads to complete
        for thread in threads:
            thread.join()
        
        # Verify all requests succeeded
        assert len(results) == 5
        assert all(status == 200 for status in results)

    @pytest.mark.asyncio
    async def test_streaming_response(self):
        """Test streaming response for real-time interaction."""
        from fastapi.testclient import TestClient
        from src.main import create_app
        
        app = create_app()
        client = TestClient(app)
        
        payload = {
            "question": "Explain what HbA1c means",
            "stream": True
        }
        
        with client.stream("POST", "/ask/stream", json=payload) as response:
            assert response.status_code == 200
            
            # Collect streaming chunks
            chunks = []
            for line in response.iter_lines():
                if line:
                    chunks.append(line.decode())
            
            # Verify streaming format
            assert len(chunks) > 0
            assert any("start" in chunk for chunk in chunks)
            assert any("token" in chunk for chunk in chunks)
            assert any("end" in chunk for chunk in chunks)

    def test_natural_language_extraction(self, client):
        """Test biomarker extraction from natural language."""
        payload = {
            "text": "My blood test shows glucose 140 mg/dL, HbA1c is 10%, and hemoglobin is 11.5 g/dL. I'm a 45-year-old male.",
            "extract_biomarkers": True
        }

        response = client.post("/analyze/natural", json=payload)
        
        assert response.status_code == 200
        data = response.json()
        assert "extracted_data" in data
        assert "analysis" in data
        
        # Verify extraction
        extracted = data["extracted_data"]
        assert "biomarkers" in extracted
        assert extracted["biomarkers"].get("Glucose") == 140
        assert extracted["biomarkers"].get("HbA1c") == 10.0
        assert extracted["biomarkers"].get("Hemoglobin") == 11.5
        
        # Verify patient context
        assert "patient_context" in extracted
        assert extracted["patient_context"].get("age") == 45
        assert extracted["patient_context"].get("gender") == "male"

    def test_confidence_scoring_consistency(self, client):
        """Test confidence scoring is consistent across runs."""
        payload = {
            "biomarkers": {
                "Glucose": 140,
                "HbA1c": 10.0
            },
            "patient_context": {
                "age": 45,
                "gender": "male"
            }
        }

        # Make multiple requests
        responses = []
        for _ in range(3):
            response = client.post("/analyze/structured", json=payload)
            assert response.status_code == 200
            responses.append(response.json())
        
        # Verify consistency in findings
        findings_0 = responses[0]["analysis"]["primary_findings"]
        for i in range(1, 3):
            findings_i = responses[i]["analysis"]["primary_findings"]
            assert len(findings_0) == len(findings_i)
            
            # Same conditions should be detected
            conditions_0 = {f["condition"] for f in findings_0}
            conditions_i = {f["condition"] for f in findings_i}
            assert conditions_0 == conditions_i

    def test_service_degradation(self, client):
        """Test graceful degradation when services are unavailable."""
        # This test would require mocking service unavailability
        # For now, we'll test the health endpoint shows service status
        
        response = client.get("/health/detailed")
        assert response.status_code == 200
        data = response.json()
        assert "services" in data
        
        # Services should report their status
        services = data["services"]
        expected_services = ["opensearch", "redis", "llm"]
        for service in expected_services:
            assert service in services
            assert services[service] in ["connected", "unavailable"]

    def test_input_validation_edge_cases(self, client):
        """Test input validation with edge cases."""
        test_cases = [
            # Empty biomarkers
            {"biomarkers": {}, "patient_context": {"age": 30}},
            # Extreme values
            {"biomarkers": {"Glucose": 9999, "HbA1c": 99.9}},
            # Negative values
            {"biomarkers": {"Glucose": -10, "HbA1c": 5.0}},
            # Zero values
            {"biomarkers": {"Glucose": 0, "HbA1c": 0}},
            # Very long context
            {"biomarkers": {"Glucose": 100}, 
             "patient_context": {"notes": "x" * 10000}}
        ]
        
        for payload in test_cases:
            response = client.post("/analyze/structured", json=payload)
            # Should either succeed or fail gracefully
            assert response.status_code in [200, 422]
            
            if response.status_code == 200:
                data = response.json()
                assert "analysis" in data

    @pytest.mark.asyncio
    async def test_workflow_performance_metrics(self, guild):
        """Test workflow performance and collect metrics."""
        import time
        
        patient_input = PatientInput(
            biomarkers={"Glucose": 140, "HbA1c": 10.0},
            patient_context={"age": 45, "gender": "male"}
        )
        
        # Measure execution time
        start_time = time.time()
        
        with patch('src.workflow.logger'):
            result = await guild.workflow.ainvoke(patient_input)
        
        end_time = time.time()
        execution_time = end_time - start_time
        
        # Verify performance
        assert execution_time < 10.0  # Should complete within 10 seconds
        assert "final_response" in result
        
        # Check for timing information in metadata if available
        if "metadata" in result:
            assert "processing_time" in result["metadata"]

    def test_cross_service_communication(self, client):
        """Test communication between different services."""
        # First, search for information
        search_payload = {
            "query": "diabetes complications",
            "top_k": 3
        }
        
        search_response = client.post("/search", json=search_payload)
        assert search_response.status_code == 200
        
        # Then use that information in a question
        if search_response.json()["results"]:
            first_result = search_response.json()["results"][0]
            question_payload = {
                "question": f"Based on {first_result['title']}, what are the main complications?"
            }
            
            answer_response = client.post("/ask", json=question_payload)
            assert answer_response.status_code == 200
            
            # Verify the answer references relevant information
            answer = answer_response.json()["answer"]["content"]
            assert len(answer) > 50