-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_application_map.py
More file actions
357 lines (305 loc) Β· 14.9 KB
/
test_application_map.py
File metadata and controls
357 lines (305 loc) Β· 14.9 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
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
"""
Application Map ν΅ν© ν
μ€νΈ
Frontend β Backend β Cosmos DB β External APIs
μ 체 μ°κ²°μ΄ Application Insightsμ Application Mapμ μ λλ‘ νμλλμ§ ν
μ€νΈ
"""
import asyncio
import logging
import sys
import time
from typing import Dict, List, Optional, Tuple
import httpx
# λ‘κΉ
μ€μ
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class ApplicationMapTester:
"""Application Map ν
μ€νΈ ν΄λμ€"""
def __init__(self, backend_url: str = "http://localhost:8000"):
self.backend_url = backend_url
self.test_results: List[Dict] = []
def generate_operation_id(self, prefix: str = "") -> str:
"""κ³ μ ν Operation ID μμ±"""
timestamp = int(time.time() * 1000)
suffix = hash(f"{prefix}{timestamp}") % 100000
return f"{timestamp}-{suffix:05d}"
def create_trace_headers(self, operation_id: str) -> Dict[str, str]:
"""W3C Trace Context + Application Insights ν€λ μμ±"""
return {
"traceparent": f"00-{operation_id.zfill(32)}-{operation_id[:16].zfill(16)}-01",
"Request-Id": f"|{operation_id}.",
"Request-Context": "appId=cid-v1:etf-agent-frontend",
"User-Agent": "Mozilla/5.0 (React App) ETF-Agent-Frontend/0.1.0",
"Content-Type": "application/json",
}
async def check_health(self) -> bool:
"""λ°±μλ μλ² μν νμΈ"""
print("\n" + "=" * 80)
print("π₯ λ°±μλ μλ² μν νμΈ")
print("=" * 80)
try:
async with httpx.AsyncClient(timeout=5.0) as client:
response = await client.get(f"{self.backend_url}/health")
if response.status_code == 200:
data = response.json()
print(f"β
λ°±μλ μλ² μ μ μλ")
print(f" μν: {data.get('status', 'unknown')}")
print(f" νμμ€ν¬ν: {data.get('timestamp', 'N/A')}")
return True
else:
print(f"β λ°±μλ μλ² μλ΅ μ€λ₯: {response.status_code}")
return False
except httpx.ConnectError:
print(f"β λ°±μλ μλ² μ°κ²° μ€ν¨")
print(f" λ€μ λͺ
λ ΉμΌλ‘ μλ²λ₯Ό μμνμΈμ:")
print(f" source .venv/bin/activate && uvicorn src.main:app --reload")
return False
except Exception as e:
print(f"β μκΈ°μΉ μμ μ€λ₯: {e}")
return False
async def test_endpoint(
self,
endpoint: str,
description: str,
method: str = "GET",
json_data: Optional[Dict] = None
) -> Tuple[bool, Dict]:
"""κ°λ³ μλν¬μΈνΈ ν
μ€νΈ"""
operation_id = self.generate_operation_id(endpoint)
headers = self.create_trace_headers(operation_id)
print(f"\nπ‘ {description}")
print(f" Endpoint: {endpoint}")
print(f" Method: {method}")
print(f" Operation ID: {operation_id[:20]}...")
result = {
"endpoint": endpoint,
"description": description,
"operation_id": operation_id,
"success": False,
"status_code": None,
"duration_ms": None,
"error": None,
"response_summary": None,
}
try:
async with httpx.AsyncClient(timeout=30.0) as client:
start_time = time.time()
if method == "GET":
response = await client.get(
f"{self.backend_url}{endpoint}",
headers=headers
)
elif method == "POST":
response = await client.post(
f"{self.backend_url}{endpoint}",
headers=headers,
json=json_data or {}
)
else:
raise ValueError(f"Unsupported method: {method}")
duration_ms = (time.time() - start_time) * 1000
result["status_code"] = response.status_code
result["duration_ms"] = round(duration_ms, 2)
if response.status_code == 200:
result["success"] = True
# μλ΅ λ°μ΄ν° λΆμ
try:
data = response.json()
if isinstance(data, dict):
# κ²°κ³Ό νλͺ© μ κ³μ°
item_count = 0
for key in ['etfs', 'items', 'results', 'news', 'data']:
if key in data and isinstance(data[key], list):
item_count = len(data[key])
break
result["response_summary"] = f"{item_count} items" if item_count > 0 else "success"
elif isinstance(data, list):
result["response_summary"] = f"{len(data)} items"
else:
result["response_summary"] = "success"
except:
result["response_summary"] = "success"
print(f" β
μ±κ³΅: {response.status_code}")
print(f" β±οΈ μλ΅ μκ°: {duration_ms:.2f}ms")
print(f" π κ²°κ³Ό: {result['response_summary']}")
else:
result["error"] = f"HTTP {response.status_code}"
print(f" β μ€λ₯: {response.status_code}")
print(f" μλ΅: {response.text[:100]}")
except httpx.TimeoutException:
result["error"] = "Timeout"
print(f" β° νμμμ")
except Exception as e:
result["error"] = str(e)
print(f" β μμ² μ€ν¨: {e}")
self.test_results.append(result)
return result["success"], result
async def run_all_tests(self):
"""λͺ¨λ ν
μ€νΈ μ€ν"""
print("\n" + "=" * 80)
print("π§ͺ Application Map ν΅ν© ν
μ€νΈ μμ")
print("=" * 80)
# 1. μλ² μν νμΈ
if not await self.check_health():
print("\nβ λ°±μλ μλ²κ° μ€ν μ€μ΄μ§ μμ΅λλ€. ν
μ€νΈλ₯Ό μ€λ¨ν©λλ€.")
return False
# 2. ν
μ€νΈ μΌμ΄μ€ μ μ
test_cases = [
# ETF API ν
μ€νΈ
("/api/etf/list?limit=5", "ETF λͺ©λ‘ μ‘°ν", "GET", None),
# λ΄μ€ API ν
μ€νΈ
("/api/news/market?category=general&limit=5", "μμ₯ λ΄μ€ μ‘°ν", "GET", None),
("/api/news/global?sources=all&limit=5", "κΈλ‘λ² λ΄μ€ μ‘°ν", "GET", None),
# μ£Όμ API ν
μ€νΈ
("/api/stocks/search?q=AAPL", "μ£Όμ κ²μ (AAPL)", "GET", None),
("/api/stocks/search?q=MSFT", "μ£Όμ κ²μ (MSFT)", "GET", None),
# μ±ν
API ν
μ€νΈ (Semantic Kernel + Cosmos DB + External APIs)
("/api/chat/", "AI μ±ν
- AAPL λΆμ", "POST", {"message": "AAPL μ£Όμμ λν΄ μλ €μ€"}),
("/api/chat/", "AI μ±ν
- ETF μΆμ²", "POST", {"message": "κΈ°μ μ£Ό ETF μΆμ²ν΄μ€"}),
]
# 3. κ° ν
μ€νΈ μ€ν
print("\n" + "=" * 80)
print("π API μλν¬μΈνΈ ν
μ€νΈ")
print("=" * 80)
success_count = 0
for endpoint, description, method, json_data in test_cases:
success, _ = await self.test_endpoint(endpoint, description, method, json_data)
if success:
success_count += 1
# μμ² κ° κ°κ²© (ν
λ λ©νΈλ¦¬ μ²λ¦¬ μκ°)
await asyncio.sleep(0.5)
# 4. κ²°κ³Ό μμ½
total_tests = len(test_cases)
print("\n" + "=" * 80)
print("π ν
μ€νΈ κ²°κ³Ό μμ½")
print("=" * 80)
print(f"\nμ΄ ν
μ€νΈ: {total_tests}")
print(f"μ±κ³΅: {success_count}")
print(f"μ€ν¨: {total_tests - success_count}")
print(f"μ±κ³΅λ₯ : {(success_count / total_tests * 100):.1f}%")
# μ€ν¨ν ν
μ€νΈ μμΈ μ 보
failed_tests = [r for r in self.test_results if not r["success"]]
if failed_tests:
print("\nβ μ€ν¨ν ν
μ€νΈ:")
for test in failed_tests:
print(f" - {test['description']}")
print(f" Endpoint: {test['endpoint']}")
print(f" μ€λ₯: {test['error']}")
# 5. ν
λ λ©νΈλ¦¬ μ μ‘ λκΈ°
print("\nβ³ ν
λ λ©νΈλ¦¬ μ μ‘ λκΈ° μ€ (10μ΄)...")
await asyncio.sleep(10)
# 6. Application Map νμΈ κ°μ΄λ
self.print_verification_guide()
return success_count == total_tests
def print_verification_guide(self):
"""Application Map νμΈ κ°μ΄λ μΆλ ₯"""
print("\n" + "=" * 80)
print("π Application Insightsμμ νμΈνκΈ°")
print("=" * 80)
print("\n1οΈβ£ Application Map 보기:")
print(" Azure Portal β Application Insights 리μμ€")
print(" β μΌμͺ½ λ©λ΄ β Application map")
print("\n2οΈβ£ μμ μ°κ²° ꡬ쑰:")
print("")
print(" ββββββββββββββββββββββββ")
print(" β Browser (Frontend) β β React App")
print(" β etf-agent-frontend β")
print(" ββββββββββββ¬ββββββββββββ")
print(" β HTTP Requests")
print(" β (traceparent, Request-Id)")
print(" βΌ")
print(" ββββββββββββββββββββββββ")
print(" β etf-agent β β FastAPI Backend")
print(" β (Backend API) β")
print(" ββββββββββββ¬ββββββββββββ")
print(" β")
print(" βββββββββββββββββββββββ¬ββββββββββββββββββββββ")
print(" β β β")
print(" βΌ βΌ βΌ")
print(" ββββββββββββββββββββ ββββββββββββββββββββ ββββββββββββββββββββ")
print(" β COSMOS β β yfinance API β β RSS Feeds β")
print(" β (Cosmos DB) β β (External) β β (External) β")
print(" ββββββββββββββββββββ ββββββββββββββββββββ ββββββββββββββββββββ")
print("")
print("3οΈβ£ κ° λ
Έλ νμΈ μ¬ν:")
print(" β λ
Έλ μ΄λ¦μ΄ μ¬λ°λ₯΄κ² νμλλμ§")
print(" β μ°κ²°μ (νμ΄ν)μ΄ κ·Έλ €μ Έ μλμ§")
print(" β μμ² μ, νκ· μλ΅ μκ°μ΄ νμλλμ§")
print(" β μ€ν¨ν μμ²μ΄ μλ€λ©΄ λΉ¨κ°μμΌλ‘ νμλλμ§")
print("\n4οΈβ£ KQL μΏΌλ¦¬λ‘ μμΈ νμΈ:")
print("")
print(" # Frontend β Backend μμ² μΆμ ")
print(" requests")
print(" | where timestamp > ago(1h)")
print(" | where customDimensions.['http.request_context'] contains 'frontend'")
print(" | project timestamp, name, url, duration, success,")
print(" operation_Id, request_id = customDimensions.['http.request_id']")
print(" | order by timestamp desc")
print("")
print(" # Backend β Cosmos DB μμ‘΄μ±")
print(" dependencies")
print(" | where timestamp > ago(1h)")
print(" | where target == 'COSMOS'")
print(" | summarize Count = count(), AvgDuration = avg(duration)")
print(" by name, type")
print(" | order by Count desc")
print("")
print(" # End-to-End νΈλμμ
(Frontend β Backend β Dependencies)")
print(" let timeRange = ago(1h);")
print(" requests")
print(" | where timestamp > timeRange")
print(" | extend operation_Id")
print(" | join kind=inner (")
print(" dependencies")
print(" | where timestamp > timeRange")
print(" | extend operation_Id")
print(" ) on operation_Id")
print(" | project ")
print(" timestamp,")
print(" RequestName = name,")
print(" DependencyType = type1,")
print(" DependencyTarget = target,")
print(" RequestDuration = duration,")
print(" DependencyDuration = duration1,")
print(" TotalDuration = duration + duration1,")
print(" Success = success and success1")
print(" | order by timestamp desc")
print("")
print("5οΈβ£ Live Metrics νμΈ:")
print(" Application Insights β Live Metrics")
print(" β μ€μκ°μΌλ‘ μμ²/μλ΅/μμ‘΄μ± νμΈ κ°λ₯")
print("")
print("=" * 80)
async def main():
"""λ©μΈ ν¨μ"""
print("\nπ Application Map ν΅ν© ν
μ€νΈ λꡬ")
print("=" * 80)
print("μ΄ λꡬλ λ€μμ ν
μ€νΈν©λλ€:")
print(" - Frontend β Backend μ°κ²° (W3C Trace Context)")
print(" - Backend β Cosmos DB μ°κ²° (peer.service)")
print(" - Backend β External APIs μ°κ²°")
print(" - Application Map λ
Έλ λ° μ°κ²° νμ")
print("=" * 80)
# ν
μ€ν° μμ± λ° μ€ν
tester = ApplicationMapTester()
success = await tester.run_all_tests()
# μ’
λ£ μ½λ
if success:
print("\nβ
λͺ¨λ ν
μ€νΈκ° μ±κ³΅μ μΌλ‘ μλ£λμμ΅λλ€!")
sys.exit(0)
else:
print("\nβ οΈ μΌλΆ ν
μ€νΈκ° μ€ν¨νμ΅λλ€. μμ κ²°κ³Όλ₯Ό νμΈνμΈμ.")
sys.exit(1)
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\n\nβ οΈ μ¬μ©μμ μν΄ ν
μ€νΈκ° μ€λ¨λμμ΅λλ€.")
sys.exit(1)
except Exception as e:
print(f"\n\nβ μκΈ°μΉ μμ μ€λ₯ λ°μ: {e}")
import traceback
traceback.print_exc()
sys.exit(1)