# Pipelines de tests autoreparables Las suites de tests tradicionales se rompen cuando cambia la UI. Los tests autoreparables usan la memoria de Synapse para aprender de fallos pasados y adaptarse — reduciendo tests inestables y la carga de mantenimiento. ## Concepto ``` ┌─────────┐ fails ┌──────────┐ store ┌──────────┐ │ Test │ ───────▶ │ Synapse │ ───────▶ │ Memories │ │ Run │ │ Memory │ │ (failures)│ └─────────┘ └──────────┘ └──────────┘ ▲ │ │ recall │ │ before next run │ └─────────────────────┘ ``` 1. El test se ejecuta 2. Si falla, almacena el fallo (qué salió mal, por qué, cómo arreglarlo) 3. Próxima ejecución: recupera los fallos relevantes antes de ejecutar 4. Aplica las correcciones conocidas automáticamente ## Implementación ### Paso 1: Wrapper de test Envuelva cada test con recall/store de memoria: ```python import requests from datetime import datetime URL = "https://synapse.schaefer.zone" MIND_KEY = "mk_..." def self_healing_test(test_name, test_fn): """Decorator: wrap a test with self-healing memory.""" def wrapper(): # 1. Recall past failures for this test past_failures = requests.get( f"{URL}/memory/search?q={test_name}+failure", headers={"Authorization": f"Bearer {MIND_KEY}"} ).json() # 2. Run test with failure context try: test_fn(known_failures=past_failures) except Exception as e: # 3. Store the failure store_failure(test_name, e, traceback.format_exc()) raise return wrapper def store_failure(test_name, error, traceback_str): requests.post(f"{URL}/memory", headers={"Authorization": f"Bearer {MIND_KEY}", "Content-Type": "application/json"}, json={ "category": "mistake", "key": f"test_failure_{test_name}_{datetime.now().isoformat()}", "content": f"Test: {test_name}\nError: {error}\nTrace:\n{traceback_str}", "tags": ["test", "failure", test_name], "priority": "high" }) ``` ### Paso 2: Lógica de test adaptativa Dentro del test, compruebe si hay fallos conocidos y aplique correcciones: ```python @self_healing_test def test_login_page(browser, known_failures=None): browser.goto("https://app.com/login") # Check if we've seen this page change before if known_failures and known_failures.get("results"): for failure in known_failures["results"]: if "button moved" in failure["content"].lower(): # Use accessibility label instead of coordinates browser.click(by_label="Login button") return # Default: use coordinates browser.click(x=150, y=400) ``` ### Paso 3: Estrategias de recuperación Almacene estrategias de recuperación como memorias: ```python def store_recovery(failure_type, strategy): requests.post(f"{URL}/memory", headers={"Authorization": f"Bearer {MIND_KEY}", "Content-Type": "application/json"}, json={ "category": "skill", "key": f"recovery_{failure_type}", "content": strategy, "tags": ["test", "recovery", failure_type], "priority": "high" }) # Store recoveries for common failures store_recovery("element_not_found", "When element not found by ID, try by CSS class, then by XPath, " "then by accessibility label. Take screenshot for debugging.") store_recovery("timeout", "Increase timeout to 30s. If still fails, check if page is loading " "dynamically — wait for specific element instead of fixed time.") store_recovery("stale_element", "Re-find element before each interaction. Don't cache element references " "across page transitions.") ``` ### Paso 4: Integración con CI ```yaml # .gitlab-ci.yml test:self-healing: script: - export SYNAPSE_MIND_KEY=$SYNAPSE_TEST_MIND_KEY - pytest tests/ --self-healing after_script: # Summarize new failures - python scripts/synapse_failure_summary.py ``` ### Paso 5: Dashboard de análisis de fallos ```python # Get all test failures from the last week r = requests.get( f"{URL}/memory/search?q=test+failure", headers={"Authorization": f"Bearer {MIND_KEY}"} ) # Group by test name failures = {} for mem in r.json().get("results", []): test_name = extract_test_name(mem["content"]) failures.setdefault(test_name, []).append(mem) # Report for test, fails in sorted(failures.items(), key=lambda x: -len(x[1])): print(f"{test}: {len(fails)} failures") ``` ## Mejores prácticas > [!TIP] > - **Almacene tracebacks** — contienen la línea exacta que falló > - **Etiquete por nombre de test** — habilita filtrado rápido > - **Use la categoría `mistake`** — separa de las memorias regulares > - **Establezca prioridad `high`** — los fallos nunca deben olvidarse > - **Limpieza periódica** — elimine memorias de problemas resueltos > - **No almacene datos sensibles** — credenciales, PII ## Patrones de fallo comunes a almacenar | Tipo de fallo | Qué almacenar | |--------------|---------------| | Elemento no encontrado | Selector probado, estado de la página, captura | | Timeout | Tiempo de espera, qué se estaba esperando | | Aserción fallida | Valor esperado vs actual | | Error de red | URL, código de estado, cuerpo de la respuesta | | Permiso denegado | Permiso requerido, rol del usuario actual | ## Próximos pasos - [Pruebas automatizadas en iOS](/docs/guides/automated-testing-ios) - [Mejores prácticas de memoria](/docs/guides/memory-best-practices) - [Cookbook de recuperación de errores](/docs/llm-cookbook/error-recovery)