anderson-ufrj commited on
Commit
43117ee
·
1 Parent(s): dbf0a5e

test: add models communication test

Browse files
Files changed (1) hide show
  1. test_models_communication.py +235 -0
test_models_communication.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ 🧪 Teste de Comunicação Backend ↔ Models
4
+ Verifica se os repositórios estão conversando via API
5
+ """
6
+
7
+ import asyncio
8
+ import sys
9
+ import os
10
+ import httpx
11
+ import json
12
+ from datetime import datetime
13
+
14
+ # Add src to path
15
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
16
+
17
+ from src.tools.models_client import ModelsClient
18
+ from src.core.config import Settings
19
+
20
+ # Test configuration
21
+ MODELS_API_URL = "https://neural-thinker-cidadao-ai-models.hf.space"
22
+ BACKEND_API_URL = "https://neural-thinker-cidadao-ai-backend.hf.space"
23
+
24
+ async def test_models_api_direct():
25
+ """🔍 TESTE 1: Acesso direto à API de Modelos"""
26
+ print("=" * 60)
27
+ print("🔍 TESTE 1: MODELS API - ACESSO DIRETO")
28
+ print("=" * 60)
29
+
30
+ try:
31
+ async with httpx.AsyncClient(timeout=30.0) as client:
32
+ # Test root endpoint
33
+ print(f"📡 Testando: {MODELS_API_URL}")
34
+ response = await client.get(f"{MODELS_API_URL}/")
35
+
36
+ if response.status_code == 200:
37
+ data = response.json()
38
+ print("✅ Models API está ONLINE!")
39
+ print(f" 📊 API: {data.get('api', 'N/A')}")
40
+ print(f" 🔢 Versão: {data.get('version', 'N/A')}")
41
+ print(f" 📋 Status: {data.get('status', 'N/A')}")
42
+ print(f" 🔗 Endpoints: {list(data.get('endpoints', {}).keys())}")
43
+ return True
44
+ else:
45
+ print(f"❌ Models API retornou status: {response.status_code}")
46
+ return False
47
+
48
+ except Exception as e:
49
+ print(f"❌ Erro ao conectar Models API: {str(e)}")
50
+ return False
51
+
52
+ async def test_models_health():
53
+ """🏥 TESTE 2: Health check da API de Modelos"""
54
+ print("\n" + "=" * 60)
55
+ print("🏥 TESTE 2: MODELS API - HEALTH CHECK")
56
+ print("=" * 60)
57
+
58
+ try:
59
+ async with httpx.AsyncClient(timeout=30.0) as client:
60
+ response = await client.get(f"{MODELS_API_URL}/health")
61
+
62
+ if response.status_code == 200:
63
+ data = response.json()
64
+ print("✅ Health check OK!")
65
+ print(f" 📊 Status: {data.get('status', 'N/A')}")
66
+ print(f" 🤖 Modelos carregados: {data.get('models_loaded', 'N/A')}")
67
+ return True
68
+ else:
69
+ print(f"❌ Health check falhou: {response.status_code}")
70
+ return False
71
+
72
+ except Exception as e:
73
+ print(f"❌ Erro no health check: {str(e)}")
74
+ return False
75
+
76
+ async def test_backend_to_models():
77
+ """🔄 TESTE 3: Backend chamando Models via Client"""
78
+ print("\n" + "=" * 60)
79
+ print("🔄 TESTE 3: BACKEND → MODELS VIA CLIENT")
80
+ print("=" * 60)
81
+
82
+ try:
83
+ # Initialize client with explicit URL
84
+ async with ModelsClient(base_url=MODELS_API_URL) as client:
85
+
86
+ # Test anomaly detection
87
+ print("🧠 Testando detecção de anomalias...")
88
+
89
+ # Sample data for testing
90
+ test_data = {
91
+ "transaction_amount": 150000.00,
92
+ "vendor_name": "Tech Solutions LTDA",
93
+ "contract_type": "informática",
94
+ "transaction_date": "2024-08-18"
95
+ }
96
+
97
+ result = await client.detect_anomaly(test_data)
98
+
99
+ if result:
100
+ print("✅ Comunicação Backend → Models OK!")
101
+ print(f" 🎯 Resultado: {result}")
102
+ return True
103
+ else:
104
+ print("❌ Nenhum resultado retornado")
105
+ return False
106
+
107
+ except Exception as e:
108
+ print(f"❌ Erro na comunicação: {str(e)}")
109
+ return False
110
+
111
+ async def test_models_specific_endpoints():
112
+ """🎯 TESTE 4: Endpoints específicos de modelos"""
113
+ print("\n" + "=" * 60)
114
+ print("🎯 TESTE 4: ENDPOINTS ESPECÍFICOS DE MODELOS")
115
+ print("=" * 60)
116
+
117
+ endpoints_to_test = [
118
+ "/models/anomaly/detect",
119
+ "/models/pattern/analyze",
120
+ "/models/spectral/analyze"
121
+ ]
122
+
123
+ results = {}
124
+
125
+ async with httpx.AsyncClient(timeout=30.0) as client:
126
+ for endpoint in endpoints_to_test:
127
+ try:
128
+ url = f"{MODELS_API_URL}{endpoint}"
129
+ print(f"📡 Testando: {endpoint}")
130
+
131
+ # Sample request data
132
+ test_payload = {
133
+ "data": [1, 2, 3, 4, 5],
134
+ "params": {"threshold": 0.8}
135
+ }
136
+
137
+ response = await client.post(url, json=test_payload)
138
+
139
+ if response.status_code == 200:
140
+ print(f" ✅ {endpoint} - OK")
141
+ results[endpoint] = "OK"
142
+ elif response.status_code == 422:
143
+ print(f" ⚠️ {endpoint} - Schema validation (normal)")
144
+ results[endpoint] = "Schema OK"
145
+ else:
146
+ print(f" ❌ {endpoint} - Status: {response.status_code}")
147
+ results[endpoint] = f"Error: {response.status_code}"
148
+
149
+ except Exception as e:
150
+ print(f" ❌ {endpoint} - Erro: {str(e)}")
151
+ results[endpoint] = f"Exception: {str(e)}"
152
+
153
+ return results
154
+
155
+ async def test_backend_api_integration():
156
+ """🏛️ TESTE 5: Backend API usando Models internamente"""
157
+ print("\n" + "=" * 60)
158
+ print("🏛️ TESTE 5: BACKEND API - INTEGRAÇÃO COM MODELS")
159
+ print("=" * 60)
160
+
161
+ try:
162
+ async with httpx.AsyncClient(timeout=30.0) as client:
163
+ # Test investigation endpoint (should use models internally)
164
+ print("🔍 Testando investigação (usa models internamente)...")
165
+
166
+ payload = {
167
+ "query": "Analisar contratos de informática com valores suspeitos",
168
+ "data_source": "contracts",
169
+ "max_results": 10
170
+ }
171
+
172
+ response = await client.post(
173
+ f"{BACKEND_API_URL}/api/agents/zumbi/investigate",
174
+ json=payload
175
+ )
176
+
177
+ if response.status_code == 200:
178
+ data = response.json()
179
+ print("✅ Backend API funcionando!")
180
+ print(f" 🔍 Status: {data.get('status', 'N/A')}")
181
+ print(f" 📊 Anomalias: {data.get('anomalies_found', 'N/A')}")
182
+ print(f" ⏱️ Tempo: {data.get('processing_time_ms', 'N/A')}ms")
183
+ return True
184
+ else:
185
+ print(f"❌ Backend API erro: {response.status_code}")
186
+ return False
187
+
188
+ except Exception as e:
189
+ print(f"❌ Erro no Backend API: {str(e)}")
190
+ return False
191
+
192
+ async def run_communication_tests():
193
+ """🚀 Executar todos os testes de comunicação"""
194
+ print("🧪 TESTE DE COMUNICAÇÃO CIDADÃO.AI BACKEND ↔ MODELS")
195
+ print("🕐 Iniciado em:", datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
196
+ print()
197
+
198
+ results = {
199
+ "models_api_direct": await test_models_api_direct(),
200
+ "models_health": await test_models_health(),
201
+ "backend_to_models": await test_backend_to_models(),
202
+ "models_endpoints": await test_models_specific_endpoints(),
203
+ "backend_integration": await test_backend_api_integration()
204
+ }
205
+
206
+ # Summary
207
+ print("\n" + "=" * 60)
208
+ print("📊 RESUMO DOS TESTES")
209
+ print("=" * 60)
210
+
211
+ total_tests = len(results)
212
+ passed_tests = sum(1 for v in results.values() if v is True or (isinstance(v, dict) and any("OK" in str(val) for val in v.values())))
213
+
214
+ for test_name, result in results.items():
215
+ status = "✅ PASSOU" if result is True else "📊 DETALHES" if isinstance(result, dict) else "❌ FALHOU"
216
+ print(f" {test_name}: {status}")
217
+
218
+ if isinstance(result, dict):
219
+ for endpoint, endpoint_result in result.items():
220
+ emoji = "✅" if "OK" in str(endpoint_result) else "❌"
221
+ print(f" {emoji} {endpoint}: {endpoint_result}")
222
+
223
+ print(f"\n🎯 RESULTADO GERAL: {passed_tests}/{total_tests} testes funcionais")
224
+
225
+ if passed_tests == total_tests:
226
+ print("🎉 COMUNICAÇÃO BACKEND ↔ MODELS TOTALMENTE FUNCIONAL!")
227
+ elif passed_tests > 0:
228
+ print("⚠️ COMUNICAÇÃO PARCIALMENTE FUNCIONAL - Verificar issues")
229
+ else:
230
+ print("❌ COMUNICAÇÃO NÃO FUNCIONAL - Verificar deployment")
231
+
232
+ return results
233
+
234
+ if __name__ == "__main__":
235
+ asyncio.run(run_communication_tests())