使用说明
🤖 AI测试浏览器
使用Claude AI+MCP自动生成真实页面扫描的PlayWright测试
智能系统,自动扫描网页,提取真实的选择器,并使用内置的自动修复生成PlayWright测试。它包括对受保护页面的认证扫描和交互式对话模式。
✨ 特点
🔍 实际页面扫描
- 使用PlayWright浏览网页
- 其他元素交互(输入、按钮、选择、链接)
- 标识ID、名称、类型和属性 真实的
- 没有猜测-仅验证选择器
🔐 验证扫描
- 浏览需要登录的页面
- 配置凭据
auth.yaml - 站点自动检测
- 支持多个应用程序
🤖 智能发电
- 克劳德分析页面结构
- 使用选择器生成测试 从一开始就正确
- 自动模式: 完整的2-5测试套件
- 互动模式: 与克劳德讨论测试什么
- 带有类型提示和文档的干净代码
🔧 自动修复
- 检测选择器何时更改
- 自动重新扫描页面
- 使用新的选择器更新测试
- 在修改之前创建备份
- 预览更改
--dry-run
💻 CLI专业
- 8个直观命令
- 更改预览(-dry-run)
- 多URL的批处理
- 智能处理重复文件
- 交互元素验证
🚀 安装
要求
- Python 3.11+
- 人类账户(API密钥)
设置
# Clonar repositorio
git clone https://github.com/TU_USUARIO/ai-test-explorer.git
cd ai-test-explorer
# Crear entorno virtual
python3 -m venv venv
source venv/bin/activate # En Windows: venv\Scripts\activate
# Instalar dependencias
pip install -r requirements.txt
# Instalar navegadores de Playwright
python -m playwright install
# Configurar API Key
echo "ANTHROPIC_API_KEY=tu_api_key_aqui" > .env
📖 使用
🎮 可用命令
python cli.py --help
Commands:
explore 🔍 Explora una página web
explore-auth 🔐 Explora página con autenticación
generate 🤖 Genera test básico
generate-auth 🤖🔐 Genera test con autenticación
batch 📦 Genera múltiples tests
heal 🔧 Repara test roto (auto-healing)
list 📋 Lista tests generados
run ▶️ Ejecuta tests
1️⃣ 浏览页面
基本探索(公共页面)
# Exploración simple
python cli.py explore https://www.saucedemo.com
# Con detalles de elementos
python cli.py explore https://www.saucedemo.com --show-details
退出:
📦 Elementos encontrados:
• 2 inputs
• 1 botones
• 5 links
🔹 INPUTS:
1. type=text, id=user-name, name=user-name
2. type=password, id=password, name=password
带身份验证的扫描(受保护的页面) 🔐
对于需要登录的页面:
帕索1: 在中配置凭据 auth.yaml
mi-app:
login_url: https://mi-app.com/login
username: testuser
password: testpass
username_selector: "#email"
password_selector: "#password"
submit_selector: "button[type='submit']"
帕索2: 浏览经过验证的页面
python cli.py explore-auth https://mi-app.com/dashboard -s mi-app
它是做什么的:
1. ✅ Navega a login
2. ✅ Ingresa credenciales automáticamente
3. ✅ Hace login
4. ✅ Navega a la página objetivo
5. ✅ Explora elementos del dashboard (NO del login)
二️⃣ 生成测试
基本测试
# Suite completa (2-5 tests automáticos)
python cli.py generate https://www.saucedemo.com
# Test específico con descripción
python cli.py generate https://www.saucedemo.com \
--description "login con credenciales válidas"
# Personalizar salida
python cli.py generate https://www.saucedemo.com \
--output tests \
--filename test_custom.py
结果:
import pytest
from playwright.async_api import Page
@pytest.mark.asyncio
async def test_login(page: Page):
'''Test de login con credenciales válidas'''
await page.goto("https://www.saucedemo.com")
# Selectores REALES extraídos de la página
await page.fill("#user-name", "standard_user")
await page.fill("#password", "secret_sauce")
await page.click("#login-button")
await page.wait_for_url("**/inventory.html")
assert "inventory.html" in page.url
认证测试 🔐
对于需要登录的页面(仪表板、个人资料等):
自动模式:
python cli.py generate-auth https://mi-app.com/dashboard -s mi-app
克劳德:
- 自动登录
- Explora el仪表板
- 确定主要行动
- 2-4次流量一致性测试
互动模式(与克劳德对话):
python cli.py generate-auth https://mi-app.com/dashboard -s mi-app --interactive
对话:
💬 MODO INTERACTIVO
Elementos encontrados en la página:
• 3 inputs
• 5 botones
Botones principales:
1. Exportar Reporte
2. Crear Nuevo
3. Filtrar Datos
💡 ¿Qué quieres testear? (describe en una frase)
Tú: exportar reporte con fechas personalizadas
🤖 Generando test específico...
✅ Test generado
生成的测试包括:
@pytest.mark.asyncio
async def test_exportar_reporte_fechas_personalizadas(page: Page):
# PASO 1: Login
await page.goto("https://mi-app.com/login")
await page.fill("#email", "testuser")
await page.fill("#password", "testpass")
await page.click("button[type='submit']")
# PASO 2: Navegar a dashboard
await page.goto("https://mi-app.com/dashboard")
# PASO 3: Exportar reporte
await page.fill("#fecha-inicio", "2024-01-01")
await page.fill("#fecha-fin", "2024-12-31")
await page.click("#exportar-btn")
# PASO 4: Verificar descarga
# ... verificaciones ...
智能文件管理:
如果文件已经存在,系统会询问:
⚠️ El archivo test_dashboard_auth.py ya existe
¿Qué quieres hacer?
1. Sobrescribir (se creará backup: test_dashboard_auth.py.backup)
2. Crear nuevo (test_dashboard_auth_2.py)
3. Cancelar
Opción [1/2/3]:
3.️⃣ 批处理
为多个URL生成测试:
# Crear archivo de URLs
cat > urls.txt << EOF
https://www.saucedemo.com
https://example.com
https://mi-app.com/features
EOF
# Generar tests para todas
python cli.py batch urls.txt
退出:
📋 Se encontraron 3 URLs
[1/3] Procesando: https://www.saucedemo.com
✅ Guardado en: tests/test_saucedemo_com_generated.py
[2/3] Procesando: https://example.com
⚠️ Advertencia: Test muy simple
✅ Guardado en: tests/test_example_com_generated.py
[3/3] Procesando: https://mi-app.com/features
✅ Guardado en: tests/test_mi_app_com_features_generated.py
✅ Exitosos: 3/3
4.️⃣ 自动修复🔧
当选择器更改时(部署后):
更改预览(首先推荐):
python cli.py heal tests/test_login.py --dry-run
退出:
============================================================
📋 ANÁLISIS DE CAMBIOS
============================================================
⚠️ SE DETECTARON CAMBIOS EN SELECTORES:
🔴 REMOVIDOS:
• #username-field
• #pass
• #submit-btn
🟢 AGREGADOS:
• #user-name
• #password
• #login-button
🔍 DRY RUN - No se aplicaron cambios
💾 Para aplicar cambios, ejecuta:
python cli.py heal tests/test_login.py
应用修复:
python cli.py heal tests/test_login.py
结果:
✅ CONFIRMADO: Test necesita reparación
💾 Backup creado: tests/test_login.py.backup
✅ Test reparado: tests/test_login.py
💡 Para ejecutar:
python -m pytest tests/test_login.py -v
何时使用自愈:
- ✅ 部署后(选择器已更改)
- ✅ 由于选择器超时而失败的测试
- ✅ 前端重构
- ❌ 不适用于实际应用程序错误
5️⃣ 列出并运行测试
列出所有生成的测试:
python cli.py list
退出:
============================================================
📋 TESTS GENERADOS
============================================================
✅ Se encontraron 5 tests:
1. test_saucedemo_com_generated.py
Tamaño: 1247 bytes
Ruta: tests/test_saucedemo_com_generated.py
2. test_dashboard_auth.py
Tamaño: 2134 bytes
Ruta: tests/test_dashboard_auth.py
...
💡 Para ejecutar todos:
python -m pytest tests -v
运行所有测试:
# Ejecución básica
python cli.py run
# Con verbose
python cli.py run --verbose
🎯 实际使用案例
场景1:新功能
# 1. Explora la nueva página
python cli.py explore https://tu-app.com/nueva-feature
# 2. Genera tests automáticamente
python cli.py generate https://tu-app.com/nueva-feature
# 3. Ejecuta
python -m pytest tests/test_nueva_feature.py -v
时间: 5分钟vs 30-45分钟手动
Escussio 2:打破登录后测试
# 1. Configura credenciales (una sola vez)
cat >> auth.yaml << EOF
mi-app:
login_url: https://mi-app.com/login
username: testuser
password: testpass
username_selector: "#email"
password_selector: "#password"
submit_selector: "button[type='submit']"
EOF
# 2. Explora dashboard
python cli.py explore-auth https://mi-app.com/dashboard -s mi-app
# 3. Genera tests interactivamente
python cli.py generate-auth https://mi-app.com/dashboard -s mi-app --interactive
时间: 5-10分钟vs 45-60分钟手动
场景3:部署后
# Frontend cambió selectores
# 10 tests fallando
# 1. Preview cambios
python cli.py heal tests/test_login.py --dry-run
python cli.py heal tests/test_checkout.py --dry-run
# 2. Aplicar reparaciones
python cli.py heal tests/test_login.py
python cli.py heal tests/test_checkout.py
# 3. Re-ejecutar
python cli.py run
时间: 10分钟vs 2-3小时手动
场景4:新应用程序的完整套件
# 1. Generar test de login
python cli.py generate https://nueva-app.com/login \
--description "login exitoso"
# 2. Agregar credenciales a auth.yaml
# 3. Generar tests para resto de la app
python cli.py generate-auth https://nueva-app.com/dashboard -s nueva-app
python cli.py generate-auth https://nueva-app.com/profile -s nueva-app
python cli.py generate-auth https://nueva-app.com/settings -s nueva-app
# 4. Ejecutar suite completa
python cli.py run --verbose
时间: 20-30分钟vs 4-6小时手动
🏗️ 建筑
┌─────────────┐
│ Usuario │
└──────┬──────┘
│
▼
┌─────────────┐
│ CLI │ ← 8 comandos
└──────┬──────┘
│
├──────────────────┬─────────────────┬──────────────┐
▼ ▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌──────────┐
│ Explorer │ │ Generator │ │ Auto-Healer │ │ Auth │
│ │ │ │ │ │ │ Config │
└──────┬──────┘ └──────┬──────┘ └──────┬──────┘ └────┬─────┘
│ │ │ │
└──────────────────┴─────────────────┴─────────────┘
│
▼
┌─────────────┐
│ Playwright │ ← Navegador real
└──────┬──────┘
│
▼
┌─────────────┐
│ Claude │ ← Análisis + Generación
└─────────────┘
📊 比较
Sin AI测试浏览器:
1. Abrir DevTools
2. Inspeccionar elementos manualmente
3. Copiar selectores
4. Escribir código del test
5. Ejecutar y debuggear
6. Ajustar selectores que fallan
7. Repetir para cada test
Tiempo por test: 15-30 minutos
Tasa de error: ~20% (selectores incorrectos)
Páginas con login: Requiere setup manual complejo
Con AI测试浏览器:
1. python cli.py generate-auth <url> -s <sitio> --interactive
2. Conversar con Claude sobre qué testear
3. Ejecutar
Tiempo por test: 2-5 minutos
Tasa de error: ~5% (selectores verificados)
Auto-healing: Sí
Páginas con login: Manejo automático
节省:80-90%的时间
精度提高:75%
认证支持:✅
🛠️ 技术
📁 项目结构
ai-test-explorer/
├── cli.py # CLI principal (8 comandos)
├── src/
│ ├── ai_test_generator.py # Generador de tests
│ ├── auto_healer.py # Sistema de auto-reparación
│ ├── auth_config.py # Manejo de autenticación
│ └── __init__.py
├── tests/
│ ├── conftest.py # Fixtures compartidas
│ └── test_*.py # Tests generados
├── auth.yaml # Credenciales (no subir a Git)
├── screenshots/ # Screenshots de tests
├── pytest.ini # Configuración de Pytest
├── requirements.txt
├── LICENSE
├── EXAMPLES.md # Ejemplos detallados
└── README.md
⚙️ 配置
auth.yaml
配置认证扫描的凭据:
saucedemo:
login_url: https://www.saucedemo.com
username: standard_user
password: secret_sauce
username_selector: "#user-name"
password_selector: "#password"
submit_selector: "#login-button"
mi-app:
login_url: https://mi-app.com/login
username: admin
password: admin123
username_selector: "#email"
password_selector: "#pwd"
submit_selector: "button[type='submit']"
⚠️ 重要提示: 添加 auth.yaml 一 .gitignore 为了不上传凭据。
pytest.ini
[pytest]
asyncio_mode = auto
pythonpath = .
testpaths = tests
conftest.py
PlayWright Global Fixtures在所有测试中都自动可用。
📄 许可证
MIT许可证-ve 许可证 更多细节
👤 作者
布莱恩·罗德里格斯
- 领英: 布莱恩·罗德里格斯-32a9a8211
- github: 布莱恩0422
⭐ 明星历史
如果这个项目对你有帮助,考虑给他一颗星⭐
Hecho con ❤️ y ☕ por Bryan Rodriguez