-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_api_endpoints.py
More file actions
198 lines (169 loc) Β· 6.64 KB
/
test_api_endpoints.py
File metadata and controls
198 lines (169 loc) Β· 6.64 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
#!/usr/bin/env python3
"""
Comprehensive test script for API-migrated MCP server endpoints
Tests all 8 migrated tools with sample requests
"""
import asyncio
import httpx
import json
import sysdd
from typing import Dict, Any
# Test server configuration
TEST_SERVER = "http://localhost:8000"
class APIEndpointTester:
def __init__(self, base_url: str = TEST_SERVER):
self.base_url = base_url
self.client = None
self.test_results = {}
async def init_client(self):
"""Initialize HTTP client for testing"""
self.client = httpx.AsyncClient(timeout=30.0)
async def close_client(self):
"""Close HTTP client"""
if self.client:
await self.client.aclose()
async def test_endpoint(self, endpoint: str, payload: Dict[Any, Any], description: str) -> bool:
"""Test a single endpoint with given payload"""
try:
print(f"\nπ§ͺ Testing {endpoint}: {description}")
response = await self.client.post(f"{self.base_url}{endpoint}", json=payload)
if response.status_code == 200:
result = response.json()
# Check for error in response
if "error" in result:
print(f"β {endpoint} returned error: {result['error']}")
return False
# Basic validation
if endpoint == "/search_funds" and "results" in result:
print(f"β
{endpoint} SUCCESS: Found {result.get('count', 0)} funds")
elif endpoint == "/postgres_query" and "response" in result:
print(f"β
{endpoint} SUCCESS: Query executed")
elif endpoint == "/describe_schema" and ("schema" in result or "tables" in result):
print(f"β
{endpoint} SUCCESS: Schema described")
elif endpoint == "/analyze_performance" and "performance_data" in result:
print(f"β
{endpoint} SUCCESS: Analyzed {result.get('count', 0)} funds")
elif endpoint == "/sector_analysis" and "summary_data" in result:
print(f"β
{endpoint} SUCCESS: Sector analysis completed")
elif endpoint == "/correlate_performance" and "correlation_matrix" in result:
print(f"β
{endpoint} SUCCESS: Correlation analysis completed")
elif endpoint == "/nav_trend_analysis" and "trend_data" in result:
print(f"β
{endpoint} SUCCESS: NAV trend analysis completed")
elif endpoint == "/risk_return_scatter" and "plot_data" in result:
print(f"β
{endpoint} SUCCESS: Risk-return analysis completed")
else:
print(f"β οΈ {endpoint} PARTIAL: Response format unexpected")
print(f" Response keys: {list(result.keys())}")
return True
else:
print(f"β {endpoint} FAILED: HTTP {response.status_code}")
print(f" Response: {response.text[:200]}...")
return False
except Exception as e:
print(f"β {endpoint} ERROR: {str(e)}")
return False
async def run_all_tests(self):
"""Run comprehensive tests for all endpoints"""
print("π Starting API endpoint tests...")
await self.init_client()
# Test 1: Search Funds
await self.test_endpoint(
"/search_funds",
{
"fund_name": "nippon",
"limit": 5
},
"Search for Nippon funds"
)
# Test 2: Postgres Query (now general API query)
await self.test_endpoint(
"/postgres_query",
{
"query": "equity funds",
"limit": 10
},
"Search for equity funds"
)
# Test 3: Analyze Performance
await self.test_endpoint(
"/analyze_performance",
{
"fund_names": ["nippon", "icici"]
},
"Compare performance of specific funds"
)
# Test 4: Describe Schema
await self.test_endpoint(
"/describe_schema",
{
"data_type": "all"
},
"Get API schema information"
)
# Test 5: Sector Analysis
await self.test_endpoint(
"/sector_analysis",
{
"analysis_type": "asset_class",
"limit": 100
},
"Asset class distribution analysis"
)
# Test 6: Correlate Performance
await self.test_endpoint(
"/correlate_performance",
{
"asset_class": "Equity",
"time_period": "3year",
"min_funds": 5
},
"Correlation analysis for equity funds"
)
# Test 7: NAV Trend Analysis
await self.test_endpoint(
"/nav_trend_analysis",
{
"asset_class": "Equity",
"time_analysis": "performance_comparison",
"limit": 10
},
"NAV trend analysis for equity funds"
)
# Test 8: Risk Return Scatter
await self.test_endpoint(
"/risk_return_scatter",
{
"asset_class": "Equity",
"time_period": "3year",
"limit": 20
},
"Risk-return scatter analysis"
)
# Test 9: Health Check
await self.test_endpoint(
"/ping",
{},
"Health check endpoint"
)
await self.close_client()
print("\n" + "="*60)
print("π― API ENDPOINT TEST SUMMARY")
print("="*60)
print("All core endpoints tested with sample data")
print("β
Migration from PostgreSQL to Scripbox API complete!")
print("π Your MCP server is ready for production use")
async def main():
"""Main test runner"""
tester = APIEndpointTester()
try:
await tester.run_all_tests()
except KeyboardInterrupt:
print("\nπ Tests interrupted by user")
except Exception as e:
print(f"\nπ₯ Test runner error: {e}")
sys.exit(1)
if __name__ == "__main__":
print("π MCP Server API Endpoint Tester")
print("π§ Make sure your server is running on http://localhost:8000")
print("βΆοΈ Start server with: uvicorn main:app --reload")
print()
asyncio.run(main())