# Testing Guide - Navegator Sistema completo de testing E2E para validar que los binarios funcionan correctamente. --- ## 🎯 Tipos de Tests ### 1. **Tests Unitarios** (Go) Tests de funciones individuales en Go. ```bash # Ejecutar todos los tests unitarios make test-unit # O directamente con go test go test -v ./pkg/browser/... go test -v ./pkg/cdp/... go test -v ./pkg/stealth/... ``` **Cobertura:** - ✅ Launch browser - ✅ Navigate - ✅ Screenshot - ✅ JavaScript evaluation - ✅ Stealth flags - ✅ Recorder - ✅ Profile persistence ### 2. **Tests E2E** (Bash) Tests de binarios compilados end-to-end. ```bash # Ejecutar tests E2E make test-e2e # O directamente ./test/e2e_test.sh ``` **Cobertura:** - ✅ Screenshot básico y con opciones - ✅ Búsqueda (con timeout esperado) - ✅ Navegación y recording - ✅ Perfiles personalizados - ✅ Persistencia de perfiles - ✅ Error handling ### 3. **Tests de Integración** (Bash) Tests de integración entre componentes. ```bash # Ejecutar tests de integración make test-integration # O directamente ./test/integration_test.sh ``` **Cobertura:** - ✅ Compartir perfiles entre binarios - ✅ Recording de múltiples acciones - ✅ Perfiles en paralelo (clonados) - ✅ Output JSON válido --- ## 🚀 Quick Start ### Ejecutar todos los tests ```bash make test ``` ### Tests rápidos (solo unitarios) ```bash make test-quick ``` ### Solo E2E ```bash make build make test-e2e ``` --- ## 📊 Estructura de Tests ``` navegator/ ├── pkg/ │ └── browser/ │ └── browser_test.go # Tests unitarios ├── test/ │ ├── e2e_test.sh # Tests E2E de binarios │ └── integration_test.sh # Tests de integración ├── Makefile # Comandos de testing └── .github/ └── workflows/ └── test.yml # CI/CD automático ``` --- ## 🧪 Tests Unitarios Detallados ### TestLaunchBrowser Verifica que el navegador se lance correctamente. ```go func TestLaunchBrowser(t *testing.T) { // Lanza Chrome con perfil temporal // Verifica: perfil creado, debug URL, target ID } ``` ### TestNavigate Verifica navegación a URLs. ```go func TestNavigate(t *testing.T) { // Navega a example.com // Verifica URL correcta via JavaScript } ``` ### TestScreenshot Verifica capturas de pantalla. ```go func TestScreenshot(t *testing.T) { // Toma screenshot // Verifica: PNG válido, tamaño > 0 } ``` ### TestStealthFlags Verifica flags anti-detección. ```go func TestStealthFlags(t *testing.T) { // Evalúa navigator.webdriver // Verifica: false o undefined // Verifica: window.chrome existe } ``` --- ## 🎯 Tests E2E Detallados ### Suite: screenshot **Test 1: Captura básica** ```bash ./screenshot -url https://example.com -o test.png # Verifica: PNG válido, archivo existe ``` **Test 2: Perfil personalizado** ```bash ./screenshot -profile custom-123 -url https://example.com # Verifica: perfil creado en disco ``` **Test 3: Dimensiones custom** ```bash ./screenshot -width=800 -height=600 -url https://example.com # Verifica: screenshot generado ``` ### Suite: buscar **Test 4: Búsqueda básica** ```bash ./buscar -q "test" -n 3 -output results.json # Verifica: no crash (puede tener timeout de red) ``` **Test 5: Perfil personalizado** ```bash ./buscar -profile test-search -q "query" # Verifica: perfil creado ``` ### Suite: navegar **Test 6: Navegación básica** ```bash ./navegar -url https://example.com -duration 2 # Verifica: recording creado ``` **Test 7: Recording funciona** ```bash # Verifica contenido del recording log grep "Navigate" recording_*.log ``` ### Suite: Perfiles **Test 8: Persistencia** ```bash # Primera sesión: crea perfil ./screenshot -profile persist-test -url https://example.com # Segunda sesión: reutiliza ./screenshot -profile persist-test -url https://example.com # Verifica: perfil existe después de ambas ``` **Test 9: Múltiples perfiles** ```bash # Crear múltiples perfiles en paralelo ./screenshot -profile multi-1 & ./screenshot -profile multi-2 & wait # Verifica: ambos existen ``` --- ## 🔗 Tests de Integración Detallados ### Test 1: Compartir perfil entre binarios ```bash # navegar crea sesión ./navegar -url https://example.com -profile shared # screenshot usa misma sesión ./screenshot -url https://example.com -profile shared # Verifica: mismo perfil usado ``` ### Test 2: Recording de múltiples acciones ```bash ./navegar -url https://example.com -duration 3 # Verifica: recording contiene JSON válido con acciones ``` ### Test 3: Perfiles clonados en paralelo ```bash # Clonar perfil base cp -r base clone1 cp -r base clone2 # Ejecutar en paralelo ./screenshot -profile clone1 & ./screenshot -profile clone2 & # Verifica: ambos completan sin error ``` --- ## 📈 Cobertura de Código ### Generar reporte ```bash make coverage ``` Genera `coverage.html` con visualización de cobertura. ### Ver cobertura en terminal ```bash go test -cover ./pkg/... ``` ### Cobertura por paquete ```bash go test -coverprofile=coverage.out ./pkg/browser go tool cover -func=coverage.out ``` --- ## 🔄 CI/CD Automático ### GitHub Actions El workflow `.github/workflows/test.yml` ejecuta automáticamente: 1. **Unit Tests** - En cada push/PR 2. **E2E Tests** - Con Chrome instalado 3. **Integration Tests** - Verificación completa 4. **Lint** - Análisis de código ### Configuración ```yaml on: push: branches: [ main, master, develop ] pull_request: branches: [ main, master ] ``` ### Ver resultados En GitHub: **Actions** tab → Ver runs → Detalles de cada job --- ## 🐛 Debugging Tests Fallidos ### Test unitario falla ```bash # Ejecutar con verbose go test -v ./pkg/browser/ -run TestName # Ver logs completos go test -v ./pkg/browser/ 2>&1 | tee test.log ``` ### Test E2E falla ```bash # Ejecutar directamente sin make ./test/e2e_test.sh # Ver archivos generados ls -la *.png *.json test-profiles/ ``` ### Chrome no se inicia ```bash # Verificar Chrome instalado which google-chrome # Probar manualmente google-chrome --version # Ver si hay procesos colgados ps aux | grep chrome pkill -9 chrome ``` ### Timeout en búsquedas Las búsquedas en DuckDuckGo pueden tardar. Esto es **esperado** y el test lo marca como `SKIP`. ```bash # Test marcado como SKIP por timeout de red # Esto NO es un fallo del binario ``` --- ## 🎭 Tests de Regresión ### Crear baseline ```bash # Capturar estado actual make test > baseline.txt ``` ### Comparar con baseline ```bash # Ejecutar tests nuevamente make test > current.txt # Comparar diff baseline.txt current.txt ``` --- ## 📝 Escribir Nuevos Tests ### Test unitario 1. Crear archivo `*_test.go` en el paquete 2. Función con prefijo `Test` 3. Usar `t.TempDir()` para archivos temporales ```go func TestMyFeature(t *testing.T) { tempDir := t.TempDir() // Tu código aquí if resultado != esperado { t.Errorf("Expected %v, got %v", esperado, resultado) } } ``` ### Test E2E Agregar a `test/e2e_test.sh`: ```bash TEST_NAME="mi-feature: descripción" if ./mi-binario -arg valor; then if [ condición ]; then report_test "$TEST_NAME" "PASS" else report_test "$TEST_NAME" "FAIL" "Razón" fi else report_test "$TEST_NAME" "FAIL" "Error ejecución" fi ``` --- ## 🚨 Troubleshooting ### "Chrome crashed" o "Can't find Chrome" ```bash # Ubuntu/Debian sudo apt-get install google-chrome-stable # Verificar instalación google-chrome --version ``` ### "Permission denied" en scripts ```bash chmod +x test/*.sh chmod +x scripts/*.sh ``` ### Tests pasan localmente pero fallan en CI ```bash # Puede ser dependencia de Chrome # Verificar que Chrome se instala en CI (ver .github/workflows/test.yml) # O diferencias de timezone/locale export TZ=UTC export LANG=en_US.UTF-8 ``` ### Perfiles de test llenan disco ```bash # Limpiar automáticamente make clean # O manualmente rm -rf test-profiles/ rm -rf ~/.navegator/profiles/test-* ``` --- ## 📊 Métricas de Calidad ### Objetivos - ✅ **Cobertura de código**: >70% - ✅ **Tests E2E**: >10 tests - ✅ **Tiempo de ejecución**: <5 minutos - ✅ **Pass rate**: >90% ### Monitorear ```bash # Tiempo de ejecución time make test # Cobertura make coverage # Ver coverage.html # Pass rate make test | grep "Pass rate" ``` --- ## 🔧 Comandos Útiles ```bash # Ejecutar todo make test # Solo tests rápidos make test-quick # Solo E2E make test-e2e # Solo integración make test-integration # Con cobertura make coverage # Limpiar todo make clean # Ver ayuda make help ``` --- ## 📚 Recursos - **Go Testing**: https://go.dev/doc/tutorial/add-a-test - **Table-driven tests**: https://go.dev/wiki/TableDrivenTests - **CI/CD con GitHub Actions**: https://docs.github.com/actions --- ## ✅ Checklist Pre-Commit Antes de hacer commit, ejecutar: ```bash □ make fmt # Formatear código □ make lint # Verificar código □ make test-quick # Tests rápidos □ make test # Tests completos (si hay tiempo) ``` Antes de hacer PR: ```bash □ make test # Todos los tests □ make coverage # Verificar cobertura □ Revisar CI/CD # Ver que pase en GitHub Actions ``` --- ## 🎯 Conclusión Con este sistema de testing puedes: ✅ Verificar que los binarios funcionan correctamente ✅ Detectar regresiones automáticamente ✅ Validar cambios antes de deploy ✅ Mantener calidad de código alta ✅ CI/CD automático en cada push **Comando más importante:** ```bash make test ``` Ejecuta todo: unitarios, E2E, integración. Si pasa, el código está listo.