-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_dosage_api_fallback.py
More file actions
213 lines (171 loc) Β· 8.23 KB
/
Copy pathtest_dosage_api_fallback.py
File metadata and controls
213 lines (171 loc) Β· 8.23 KB
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
#!/usr/bin/env python3
"""
Test script for verifying dosage service API fallback functionality
Tests the newly enhanced DosageService with API integration for unknown drugs
"""
import asyncio
import json
import time
import requests
from datetime import datetime
DEFAULT_SERVER_URL = "http://localhost:8000"
class DosageAPITester:
def __init__(self, server_url=DEFAULT_SERVER_URL):
self.server_url = server_url
self.test_results = []
def log_result(self, test_name, success, message=""):
result = {
"test": test_name,
"success": success,
"message": message,
"timestamp": datetime.now().isoformat()
}
self.test_results.append(result)
status = "β
" if success else "β"
print(f"{status} {test_name}: {message}")
def test_known_drug_dosage(self):
"""Test dosage calculation for a known drug (acetaminophen)"""
try:
url = f"{self.server_url}/age-dosage"
payload = {
"drug_name": "acetaminophen",
"patient_age": 25,
"weight": 70.0,
"indication": "pain relief",
"kidney_function": "normal"
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers, timeout=30)
if response.status_code == 200:
data = response.json()
# Check for expected fields
required_fields = ['drug_name', 'recommended_dose', 'unit', 'frequency', 'age_group']
if all(field in data for field in required_fields):
self.log_result("Known Drug Dosage", True,
f"Found dosage data from {data.get('data_source', 'unknown')}")
print(f" π Dosage: {data.get('recommended_dose')} {data.get('unit')}")
print(f" π
Frequency: {data.get('frequency')}")
print(f" π Data Source: {data.get('data_source', 'local_database')}")
print(f" π Confidence: {data.get('confidence_level', 'high')}")
return True
else:
self.log_result("Known Drug Dosage", False, f"HTTP {response.status_code}: {response.text}")
return False
except Exception as e:
self.log_result("Known Drug Dosage", False, f"Error: {str(e)}")
return False
def test_unknown_drug_dosage_api_fallback(self, drug_name):
"""Test dosage API fallback for an unknown drug"""
try:
url = f"{self.server_url}/age-dosage"
payload = {
"drug_name": drug_name,
"patient_age": 25,
"weight": 70.0,
"indication": "pain relief",
"kidney_function": "normal"
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers, timeout=45)
if response.status_code == 200:
data = response.json()
# Check if this is API-derived data
data_source = data.get('data_source', '')
if 'api_derived' in data_source or 'api_estimated' in str(data_source):
self.log_result(f"API Fallback: {drug_name}", True,
f"API-derived dosage estimation successful")
print(f" π API Dosage: {data.get('recommended_dose')} {data.get('unit')}")
print(f" π
API Frequency: {data.get('frequency')}")
print(f" π Data Source: {data_source}")
print(f" π Confidence: {data.get('confidence_level', 'moderate')}")
# Show warnings if any
warnings = data.get('warnings', [])
if warnings:
print(f" β οΈ Warnings: {warnings}")
return True
else:
self.log_result(f"API Fallback: {drug_name}", False,
".2f")
except requests.exceptions.Timeout:
self.log_result(f"API Fallback: {drug_name}", False, "Request timed out (API may be slow)")
return False
except Exception as e:
self.log_result(f"API Fallback: {drug_name}", False, f"Error: {str(e)}")
return False
def test_health_check_api_integration(self):
"""Test that API service is integrated in health check"""
try:
url = f"{self.server_url}/health"
response = requests.get(url, timeout=10)
if response.status_code == 200:
data = response.json()
services = data.get("services", {})
api_drugs_status = services.get("api_drugs", "not_found")
if api_drugs_status == "operational":
self.log_result("Health Check API Integration", True,
"API drugs service is operational and integrated")
# Check that dosage service is also operational
dosage_status = services.get("dosage_calculation", "not_found")
if dosage_status == "operational":
print(" π Dosage service is operational")
return True
else:
print(f" β οΈ Dosage service status: {dosage_status}")
return True # Still consider test passed if API is integrated
else:
self.log_result("Health Check API Integration", False,
f"API drugs service status: {api_drugs_status}")
except Exception as e:
self.log_result("Health Check API Integration", False, f"Error: {str(e)}")
return False
def print_summary(self):
"""Print test summary"""
print("\n" + "="*70)
print("π§ͺ DOSAGE SERVICE API FALLBACK TEST SUMMARY")
print("="*70)
successful_tests = sum(1 for result in self.test_results if result["success"])
total_tests = len(self.test_results)
print(f"β
Successful: {successful_tests}/{total_tests}")
if successful_tests > 0:
print("\nπ Dosage API Integration successfully implemented!")
print("π‘ When local dosage data isn't available:")
print(" β’ Automatically falls back to API data")
print(" β’ Generates estimated dosage based on drug usage")
print(" β’ Provides clear warnings about estimation method")
if successful_tests == total_tests:
print("\nπ ALL TESTS PASSED - API fallback working correctly!")
else:
print("\nβ οΈ Some tests failed - API fallback partially working")
else:
print("\nβ All tests failed - Check API integration")
print("\nπ Detailed Results:")
for result in self.test_results:
status = "β
" if result["success"] else "β"
print(f" {status} {result['test']}: {result['message']}")
async def main():
"""Run all dosage API fallback tests"""
print("π Starting Dosage Service API Fallback Tests")
print("This will test the enhanced dosage service with API integration")
print("Testing drugs that were previously returning 404 errors:")
print(" β’ Enzoflam (pain relief)")
print(" β’ Pan-D (pancreatic enzymes)")
print(" β’ Hexigel Gum Paint (local anesthetic)")
print("-" * 70)
# Give server a moment to initialize
print("β³ Waiting for server to initialize...")
time.sleep(5)
tester = DosageAPITester()
# Run tests
print("\nπ Running dosage API fallback tests...\n")
# First test health check
tester.test_health_check_api_integration()
# Test known drug (should use local data)
tester.test_known_drug_dosage()
# Test unknown drugs (should use API fallback)
tester.test_unknown_drug_dosage_api_fallback("enzoflam")
tester.test_unknown_drug_dosage_api_fallback("pan-d")
tester.test_unknown_drug_dosage_api_fallback("hexigel gum paint")
# Print final summary
tester.print_summary()
if __name__ == "__main__":
asyncio.run(main())