File size: 9,444 Bytes
7094511 |
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 |
#!/usr/bin/env python3
"""
Script de teste do sistema de testes massivos
"""
import sys
import os
import asyncio
import logging
# Adiciona path do projeto
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def test_imports():
"""Testa se todos os imports funcionam"""
print("🔍 Testando imports...")
try:
from testes.test_runner import MassiveTestRunner
print(" ✅ MassiveTestRunner")
from testes.test_validator import TestValidator
print(" ✅ TestValidator")
from testes.report_generator import ReportGenerator
print(" ✅ ReportGenerator")
from utils.config import AVAILABLE_MODELS
print(" ✅ AVAILABLE_MODELS")
return True
except Exception as e:
print(f" ❌ Erro no import: {e}")
return False
def test_validator():
"""Testa o sistema de validação"""
print("\n🔍 Testando validador...")
try:
from testes.test_validator import TestValidator
validator = TestValidator()
print(" ✅ Validator inicializado")
# Teste de validação por keyword
result = validator._validate_with_keyword(
"A resposta contém 150 usuários no total",
"150 usuários"
)
if result['valid'] and result['score'] == 100:
print(" ✅ Validação por keyword funcionando")
else:
print(f" ❌ Validação por keyword falhou: {result}")
return False
# Teste de sintaxe SQL
sql_result = validator.validate_sql_syntax("SELECT * FROM usuarios WHERE idade > 18")
if sql_result['valid']:
print(" ✅ Validação de sintaxe SQL funcionando")
else:
print(f" ❌ Validação SQL falhou: {sql_result}")
return False
return True
except Exception as e:
print(f" ❌ Erro no validator: {e}")
return False
def test_report_generator():
"""Testa o gerador de relatórios"""
print("\n🔍 Testando gerador de relatórios...")
try:
from testes.report_generator import ReportGenerator
generator = ReportGenerator()
print(" ✅ ReportGenerator inicializado")
# Dados de teste
test_results = {
'session_info': {
'id': 'test_session',
'question': 'Teste de pergunta',
'validation_method': 'keyword'
},
'group_results': [
{
'group_id': 1,
'group_config': {
'sql_model_name': 'GPT-4o-mini',
'processing_enabled': False,
'processing_model_name': None
},
'total_tests': 5,
'successful_tests': 4,
'valid_responses': 3,
'success_rate': 80.0,
'validation_rate': 60.0,
'response_consistency': 75.0,
'sql_consistency': 80.0,
'avg_execution_time': 5.2
}
],
'individual_results': [
{
'group_id': 1,
'iteration': 1,
'sql_model': 'GPT-4o-mini',
'processing_enabled': False,
'success': True,
'validation': {'valid': True, 'score': 85}
}
],
'summary': {
'total_groups': 1,
'total_tests': 5,
'overall_success_rate': 80.0,
'overall_validation_rate': 60.0,
'best_performing_group': {
'group_id': 1,
'group_config': {'sql_model_name': 'GPT-4o-mini'},
'validation_rate': 60.0
},
'most_consistent_group': {
'group_id': 1,
'group_config': {'sql_model_name': 'GPT-4o-mini'},
'response_consistency': 75.0
}
}
}
# Testa criação de DataFrames
group_df = generator._create_group_summary_dataframe(test_results)
individual_df = generator._create_individual_results_dataframe(test_results)
general_df = generator._create_general_summary_dataframe(test_results)
if len(group_df) > 0 and len(individual_df) > 0 and len(general_df) > 0:
print(" ✅ DataFrames criados com sucesso")
else:
print(" ❌ Erro na criação de DataFrames")
return False
return True
except Exception as e:
print(f" ❌ Erro no report generator: {e}")
return False
async def test_runner_basic():
"""Testa funcionalidades básicas do runner"""
print("\n🔍 Testando runner básico...")
try:
from testes.test_runner import MassiveTestRunner
runner = MassiveTestRunner(max_workers=2)
print(" ✅ MassiveTestRunner inicializado")
# Testa cálculo de consistência
items = ["resposta A", "resposta A", "resposta B", "resposta A"]
consistency = runner._calculate_consistency(items)
expected = 3/4 # 3 "resposta A" de 4 total
if abs(consistency - expected) < 0.01:
print(" ✅ Cálculo de consistência funcionando")
else:
print(f" ❌ Consistência incorreta: esperado {expected}, obtido {consistency}")
return False
# Testa status
status = runner.get_status()
if 'current_status' in status and status['current_status'] == 'idle':
print(" ✅ Status funcionando")
else:
print(f" ❌ Status incorreto: {status}")
return False
return True
except Exception as e:
print(f" ❌ Erro no runner: {e}")
return False
def test_flask_app():
"""Testa se o app Flask pode ser importado"""
print("\n🔍 Testando Flask app...")
try:
from testes.app_teste import app
print(" ✅ Flask app importado")
# Testa se as rotas estão definidas
routes = [rule.rule for rule in app.url_map.iter_rules()]
expected_routes = ['/', '/api/models', '/api/create_test_session']
for route in expected_routes:
if route in routes:
print(f" ✅ Rota {route} definida")
else:
print(f" ❌ Rota {route} não encontrada")
return False
return True
except Exception as e:
print(f" ❌ Erro no Flask app: {e}")
return False
def test_agentgraph_integration():
"""Testa integração com AgentGraph"""
print("\n🔍 Testando integração com AgentGraph...")
try:
from utils.config import AVAILABLE_MODELS, validate_config
# Testa se modelos estão disponíveis
if len(AVAILABLE_MODELS) > 0:
print(f" ✅ {len(AVAILABLE_MODELS)} modelos disponíveis")
else:
print(" ❌ Nenhum modelo disponível")
return False
# Testa validação de config (pode falhar se APIs não configuradas)
try:
validate_config()
print(" ✅ Configuração válida")
except Exception as e:
print(f" ⚠️ Configuração incompleta: {e}")
print(" 💡 Configure as APIs no .env para funcionalidade completa")
return True
except Exception as e:
print(f" ❌ Erro na integração: {e}")
return False
async def main():
"""Função principal de teste"""
print("🧪 TESTE DO SISTEMA DE TESTES MASSIVOS")
print("=" * 50)
tests = [
("Imports", test_imports),
("Validator", test_validator),
("Report Generator", test_report_generator),
("Runner Básico", test_runner_basic),
("Flask App", test_flask_app),
("Integração AgentGraph", test_agentgraph_integration)
]
passed = 0
total = len(tests)
for test_name, test_func in tests:
print(f"\n📋 {test_name}")
print("-" * 30)
try:
if asyncio.iscoroutinefunction(test_func):
result = await test_func()
else:
result = test_func()
if result:
passed += 1
print(f"✅ {test_name} PASSOU")
else:
print(f"❌ {test_name} FALHOU")
except Exception as e:
print(f"❌ {test_name} ERRO: {e}")
print("\n" + "=" * 50)
print(f"📊 RESULTADO FINAL: {passed}/{total} testes passaram")
if passed == total:
print("🎉 TODOS OS TESTES PASSARAM!")
print("🚀 Sistema pronto para uso!")
print("💡 Execute: python testes/run_tests.py")
else:
print("⚠️ Alguns testes falharam")
print("🔧 Verifique os erros acima")
print("=" * 50)
return passed == total
if __name__ == '__main__':
success = asyncio.run(main())
sys.exit(0 if success else 1)
|