File size: 17,168 Bytes
5b6f681 | 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 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 | #!/usr/bin/env python3
"""
🧪 Test Suite para la Interfaz Web del Transformer
Pruebas automatizadas para verificar funcionalidad y rendimiento
"""
import requests
import json
import time
import sys
import argparse
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Dict, List, Tuple
class WebInterfaceTestSuite:
def __init__(self, api_url: str = "http://127.0.0.1:8000", web_url: str = "http://localhost:8080"):
self.api_url = api_url
self.web_url = web_url
self.session = requests.Session()
self.test_results = []
def log_test(self, test_name: str, passed: bool, message: str = "", duration: float = 0):
"""Registra resultado de un test"""
status = "✅ PASS" if passed else "❌ FAIL"
result = {
"test": test_name,
"passed": passed,
"message": message,
"duration": duration
}
self.test_results.append(result)
print(f"{status} {test_name} ({duration:.2f}s) - {message}")
def test_api_health(self) -> bool:
"""Test: API Health Check"""
start_time = time.time()
try:
response = self.session.get(f"{self.api_url}/health", timeout=5)
duration = time.time() - start_time
if response.status_code == 200:
data = response.json()
if data.get("status") == "healthy":
self.log_test("API Health Check", True, "API respondiendo correctamente", duration)
return True
else:
self.log_test("API Health Check", False, "Estado de salud inválido", duration)
return False
else:
self.log_test("API Health Check", False, f"Status code: {response.status_code}", duration)
return False
except Exception as e:
duration = time.time() - start_time
self.log_test("API Health Check", False, f"Error: {str(e)}", duration)
return False
def test_web_interface_loading(self) -> bool:
"""Test: Carga de la interfaz web"""
start_time = time.time()
try:
response = self.session.get(self.web_url, timeout=10)
duration = time.time() - start_time
if response.status_code == 200:
if "Transformer" in response.text and "sentiment" in response.text.lower():
self.log_test("Web Interface Loading", True, "Interfaz cargada correctamente", duration)
return True
else:
self.log_test("Web Interface Loading", False, "Contenido incorrecto", duration)
return False
else:
self.log_test("Web Interface Loading", False, f"Status code: {response.status_code}", duration)
return False
except Exception as e:
duration = time.time() - start_time
self.log_test("Web Interface Loading", False, f"Error: {str(e)}", duration)
return False
def test_single_prediction(self) -> bool:
"""Test: Predicción individual"""
start_time = time.time()
test_text = "I love this amazing product!"
try:
payload = {"text": test_text}
response = self.session.post(f"{self.api_url}/predict", json=payload, timeout=10)
duration = time.time() - start_time
if response.status_code == 200:
data = response.json()
if "sentiment" in data and "confidence" in data:
sentiment = data["sentiment"]
confidence = data["confidence"]
if sentiment in ["POSITIVE", "NEGATIVE"] and 0 <= confidence <= 1:
self.log_test("Single Prediction", True, f"Sentiment: {sentiment}, Confidence: {confidence:.3f}", duration)
return True
else:
self.log_test("Single Prediction", False, "Formato de respuesta inválido", duration)
return False
else:
self.log_test("Single Prediction", False, "Campos faltantes en respuesta", duration)
return False
else:
self.log_test("Single Prediction", False, f"Status code: {response.status_code}", duration)
return False
except Exception as e:
duration = time.time() - start_time
self.log_test("Single Prediction", False, f"Error: {str(e)}", duration)
return False
def test_batch_prediction(self) -> bool:
"""Test: Predicción por lotes"""
start_time = time.time()
test_texts = [
"This is amazing!",
"I hate this product.",
"It's okay, nothing special."
]
try:
payload = {"texts": test_texts}
response = self.session.post(f"{self.api_url}/predict/batch", json=payload, timeout=15)
duration = time.time() - start_time
if response.status_code == 200:
data = response.json()
if "predictions" in data and len(data["predictions"]) == len(test_texts):
predictions = data["predictions"]
valid_predictions = all(
"sentiment" in pred and "confidence" in pred
for pred in predictions
)
if valid_predictions:
self.log_test("Batch Prediction", True, f"Procesados {len(predictions)} textos", duration)
return True
else:
self.log_test("Batch Prediction", False, "Predicciones inválidas", duration)
return False
else:
self.log_test("Batch Prediction", False, "Formato de respuesta incorrecto", duration)
return False
else:
self.log_test("Batch Prediction", False, f"Status code: {response.status_code}", duration)
return False
except Exception as e:
duration = time.time() - start_time
self.log_test("Batch Prediction", False, f"Error: {str(e)}", duration)
return False
def test_probabilities_endpoint(self) -> bool:
"""Test: Endpoint de probabilidades"""
start_time = time.time()
test_text = "This movie is fantastic!"
try:
payload = {"text": test_text}
response = self.session.post(f"{self.api_url}/predict/probabilities", json=payload, timeout=10)
duration = time.time() - start_time
if response.status_code == 200:
data = response.json()
if "probabilities" in data:
probs = data["probabilities"]
if "POSITIVE" in probs and "NEGATIVE" in probs:
total_prob = probs["POSITIVE"] + probs["NEGATIVE"]
if abs(total_prob - 1.0) < 0.01: # Tolerancia de flotantes
self.log_test("Probabilities Endpoint", True, f"Probs: {probs}", duration)
return True
else:
self.log_test("Probabilities Endpoint", False, f"Probabilidades no suman 1: {total_prob}", duration)
return False
else:
self.log_test("Probabilities Endpoint", False, "Clases de probabilidad faltantes", duration)
return False
else:
self.log_test("Probabilities Endpoint", False, "Campo 'probabilities' faltante", duration)
return False
else:
self.log_test("Probabilities Endpoint", False, f"Status code: {response.status_code}", duration)
return False
except Exception as e:
duration = time.time() - start_time
self.log_test("Probabilities Endpoint", False, f"Error: {str(e)}", duration)
return False
def test_model_info(self) -> bool:
"""Test: Información del modelo"""
start_time = time.time()
try:
response = self.session.get(f"{self.api_url}/model/info", timeout=5)
duration = time.time() - start_time
if response.status_code == 200:
data = response.json()
required_fields = ["model_name", "model_type", "num_parameters"]
if all(field in data for field in required_fields):
self.log_test("Model Info", True, f"Modelo: {data.get('model_name')}", duration)
return True
else:
self.log_test("Model Info", False, "Campos requeridos faltantes", duration)
return False
else:
self.log_test("Model Info", False, f"Status code: {response.status_code}", duration)
return False
except Exception as e:
duration = time.time() - start_time
self.log_test("Model Info", False, f"Error: {str(e)}", duration)
return False
def test_web_static_files(self) -> bool:
"""Test: Archivos estáticos de la web"""
start_time = time.time()
static_files = [
"/styles.css",
"/app.js",
"/config.json"
]
failed_files = []
for file_path in static_files:
try:
response = self.session.get(f"{self.web_url}{file_path}", timeout=5)
if response.status_code != 200:
failed_files.append(file_path)
except Exception:
failed_files.append(file_path)
duration = time.time() - start_time
if not failed_files:
self.log_test("Web Static Files", True, f"Todos los archivos cargados ({len(static_files)})", duration)
return True
else:
self.log_test("Web Static Files", False, f"Archivos fallidos: {failed_files}", duration)
return False
def test_performance_load(self, num_requests: int = 10) -> bool:
"""Test: Rendimiento bajo carga"""
start_time = time.time()
test_text = "Performance test text"
def make_request():
try:
payload = {"text": test_text}
response = self.session.post(f"{self.api_url}/predict", json=payload, timeout=10)
return response.status_code == 200
except Exception:
return False
try:
with ThreadPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(make_request) for _ in range(num_requests)]
results = [future.result() for future in as_completed(futures)]
duration = time.time() - start_time
success_rate = sum(results) / len(results)
avg_response_time = duration / num_requests
if success_rate >= 0.9: # 90% de éxito
self.log_test("Performance Load", True, f"Success rate: {success_rate:.1%}, Avg time: {avg_response_time:.3f}s", duration)
return True
else:
self.log_test("Performance Load", False, f"Success rate: {success_rate:.1%} (< 90%)", duration)
return False
except Exception as e:
duration = time.time() - start_time
self.log_test("Performance Load", False, f"Error: {str(e)}", duration)
return False
def test_error_handling(self) -> bool:
"""Test: Manejo de errores"""
start_time = time.time()
# Test con texto vacío
try:
payload = {"text": ""}
response = self.session.post(f"{self.api_url}/predict", json=payload, timeout=5)
empty_text_handled = response.status_code in [400, 422]
except Exception:
empty_text_handled = False
# Test con texto muy largo
try:
payload = {"text": "a" * 10000}
response = self.session.post(f"{self.api_url}/predict", json=payload, timeout=5)
long_text_handled = response.status_code in [400, 422, 200] # Puede ser manejado o procesado
except Exception:
long_text_handled = False
# Test con payload inválido
try:
response = self.session.post(f"{self.api_url}/predict", json={"invalid": "payload"}, timeout=5)
invalid_payload_handled = response.status_code in [400, 422]
except Exception:
invalid_payload_handled = False
duration = time.time() - start_time
if empty_text_handled and long_text_handled and invalid_payload_handled:
self.log_test("Error Handling", True, "Errores manejados correctamente", duration)
return True
else:
failed_tests = []
if not empty_text_handled: failed_tests.append("empty_text")
if not long_text_handled: failed_tests.append("long_text")
if not invalid_payload_handled: failed_tests.append("invalid_payload")
self.log_test("Error Handling", False, f"Fallos: {failed_tests}", duration)
return False
def run_all_tests(self) -> Dict:
"""Ejecuta todos los tests"""
print("🧪 Iniciando Test Suite para Interfaz Web")
print("=" * 60)
tests = [
self.test_api_health,
self.test_web_interface_loading,
self.test_single_prediction,
self.test_batch_prediction,
self.test_probabilities_endpoint,
self.test_model_info,
self.test_web_static_files,
self.test_performance_load,
self.test_error_handling
]
total_tests = len(tests)
passed_tests = 0
for test in tests:
if test():
passed_tests += 1
time.sleep(0.5) # Pausa entre tests
print("\n" + "=" * 60)
print(f"📊 RESUMEN DE TESTS")
print(f"Total: {total_tests}")
print(f"Passed: {passed_tests}")
print(f"Failed: {total_tests - passed_tests}")
print(f"Success Rate: {passed_tests/total_tests:.1%}")
if passed_tests == total_tests:
print("🎉 ¡TODOS LOS TESTS PASARON!")
else:
print("⚠️ Algunos tests fallaron. Revisar logs arriba.")
return {
"total": total_tests,
"passed": passed_tests,
"failed": total_tests - passed_tests,
"success_rate": passed_tests / total_tests,
"details": self.test_results
}
def generate_report(self, output_file: str = "test_report.json"):
"""Genera reporte detallado en JSON"""
report = {
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
"api_url": self.api_url,
"web_url": self.web_url,
"summary": {
"total_tests": len(self.test_results),
"passed": sum(1 for r in self.test_results if r["passed"]),
"failed": sum(1 for r in self.test_results if not r["passed"]),
"success_rate": sum(1 for r in self.test_results if r["passed"]) / len(self.test_results) if self.test_results else 0
},
"test_details": self.test_results
}
with open(output_file, "w", encoding="utf-8") as f:
json.dump(report, f, indent=2, ensure_ascii=False)
print(f"📄 Reporte guardado en: {output_file}")
def main():
parser = argparse.ArgumentParser(description="Test Suite para Interfaz Web del Transformer")
parser.add_argument("--api-url", default="http://127.0.0.1:8000", help="URL de la API")
parser.add_argument("--web-url", default="http://localhost:8080", help="URL de la interfaz web")
parser.add_argument("--report", default="test_report.json", help="Archivo de reporte")
parser.add_argument("--load-test", type=int, default=10, help="Número de requests para test de carga")
args = parser.parse_args()
# Crear suite de tests
test_suite = WebInterfaceTestSuite(args.api_url, args.web_url)
# Ejecutar tests
results = test_suite.run_all_tests()
# Generar reporte
test_suite.generate_report(args.report)
# Exit code según resultados
exit_code = 0 if results["passed"] == results["total"] else 1
sys.exit(exit_code)
if __name__ == "__main__":
main() |