forked from sanjayram-a/IBM-project
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_api_integration.py
More file actions
218 lines (178 loc) Β· 8.41 KB
/
Copy pathtest_api_integration.py
File metadata and controls
218 lines (178 loc) Β· 8.41 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
214
215
216
217
218
#!/usr/bin/env python3
"""
Test script for verifying free medical API integrations
Tests the new MedicalAPIDrugService and its endpoints
"""
import asyncio
import json
import time
import requests
from datetime import datetime
DEFAULT_SERVER_URL = "http://localhost:8000"
class APITester:
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}")
async def test_health_endpoint(self):
"""Test the health check endpoint"""
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", True, "API drugs service is operational")
return True
else:
self.log_result("Health Check", False, f"API drugs service status: {api_drugs_status}")
return False
else:
self.log_result("Health Check", False, f"Status code: {response.status_code}")
return False
except Exception as e:
self.log_result("Health Check", False, f"Error: {str(e)}")
return False
async def test_drug_stats_endpoint(self):
"""Test the drug statistics endpoint"""
try:
url = f"{self.server_url}/drug-stats"
response = requests.get(url, timeout=10)
if response.status_code == 200:
data = response.json()
# Check for expected fields
api_services = data.get("api_services", [])
data_sources = data.get("data_sources", [])
if len(api_services) >= 3:
self.log_result("Drug Stats", True, f"Found {len(api_services)} API services: {', '.join(api_services[:3])}")
return True
else:
self.log_result("Drug Stats", False, f"Only found {len(api_services)} API services")
return False
else:
self.log_result("Drug Stats", False, f"Status code: {response.status_code}")
return False
except Exception as e:
self.log_result("Drug Stats", False, f"Error: {str(e)}")
return False
async def test_comprehensive_drug_search(self, drug_name="aspirin"):
"""Test comprehensive drug search with API integration"""
try:
url = f"{self.server_url}/api-drug-info"
payload = {"drug_name": drug_name, "use_api": True}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers, timeout=30)
if response.status_code == 200:
data = response.json()
# Check key fields
sources_used = data.get("sources_used", [])
confidence_score = data.get("confidence_score", 0)
data_quality = data.get("data_quality", "")
success_msg = f"Found data from {len(sources_used)} sources"
if sources_used:
success_msg += f": {', '.join(sources_used)}"
self.log_result("Comprehensive Drug Search", True, success_msg)
# Additional checks
if confidence_score > 0.7:
print(f" π High confidence score: {confidence_score:.2f}")
elif confidence_score > 0.5:
print(f" π Moderate confidence score: {confidence_score:.2f}")
else:
print(f" π Low confidence score: {confidence_score:.2f}")
print(f" π Data quality: {data_quality}")
# Show some sample data if available
brand_name = data.get("brand_name", [])
if brand_name and brand_name[0]:
print(f" π Brand name: {brand_name[0][:50]}")
return True
else:
error_data = response.json() if response.text else {}
error_msg = error_data.get("detail", f"HTTP {response.status_code}")
self.log_result("Comprehensive Drug Search", False, f"Error: {error_msg}")
return False
except requests.exceptions.Timeout:
self.log_result("Comprehensive Drug Search", False, "Request timed out (APIs may be slow)")
return False
except Exception as e:
self.log_result("Comprehensive Drug Search", False, f"Error: {str(e)}")
return False
async def test_api_search_endpoint(self, drug_name="ibuprofen"):
"""Test the dedicated API search endpoint"""
try:
url = f"{self.server_url}/api-drug-search/{drug_name}"
response = requests.get(url, timeout=20)
if response.status_code == 200:
data = response.json()
comprehensive_results = data.get("comprehensive_results", [])
if comprehensive_results:
self.log_result("API Search Endpoint", True, f"Found {len(comprehensive_results)} comprehensive results")
# Show first result details
first_result = comprehensive_results[0]
search_method = first_result.get("search_method", "unknown")
print(f" π Search method: {search_method}")
return True
else:
self.log_result("API Search Endpoint", False, "No comprehensive results found")
return False
else:
error_msg = f"HTTP {response.status_code}"
self.log_result("API Search Endpoint", False, error_msg)
return False
except requests.exceptions.Timeout:
self.log_result("API Search Endpoint", False, "Request timed out")
return False
except Exception as e:
self.log_result("API Search Endpoint", False, f"Error: {str(e)}")
return False
def print_summary(self):
"""Print test summary"""
print("\n" + "="*60)
print("π§ͺ API INTEGRATION TEST SUMMARY")
print("="*60)
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π Integration successfully implemented!")
print("π‘ Free medical APIs are working:")
print(" β’ OpenFDA API - FDA drug labeling data")
print(" β’ PubChem API - Chemical structure and properties")
print(" β’ RxNorm API - Standardized drug names")
if successful_tests == total_tests:
print("\nπ ALL TESTS PASSED - Ready for production!")
else:
print("\nβ All tests failed - Check server startup and network connectivity")
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 API integration tests"""
print("π Starting Free Medical API Integration Tests")
print("This will test the newly integrated OpenFDA, PubChem, and RxNorm APIs")
print("-" * 60)
# Give server a moment to start up
print("β³ Waiting for server to initialize...")
time.sleep(3)
tester = APITester()
# Run tests
print("\nπ Running API integration tests...\n")
await tester.test_health_endpoint()
await tester.test_drug_stats_endpoint()
await tester.test_comprehensive_drug_search("aspirin")
await tester.test_api_search_endpoint("ibuprofen")
# Print final summary
tester.print_summary()
if __name__ == "__main__":
asyncio.run(main())