# Stressor CLI 

<div align="center">
  <img src="https://github.com/rodnye/stressor/blob/main/assets/logo.png?raw=true" alt="Stressor Logo" width="300" />
 
  <div>
    <a href="https://www.npmjs.com/package/stressor-cli">
      <img src="https://img.shields.io/npm/v/stressor-cli.svg" alt="npm version" />
    </a>
    <a href="LICENSE">
      <img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="License" />
    </a>
    <a href="https://nodejs.org/">
      <img src="https://img.shields.io/badge/node-%3E%3D16.0.0-brightgreen.svg" alt="Node.js" />
    </a>
    <a href="https://www.typescriptlang.org/">
      <img src="https://img.shields.io/badge/TypeScript-Ready-blue.svg" alt="TypeScript" />
    </a>
    <a href="https://github.com/rodnye/stressor-cli">
      <img src="https://img.shields.io/github/stars/rodnye/stressor-cli" alt="GitHub stars" />
    </a>
  </div>
  
  <p><em>CLI para ejecutar pruebas de rendimiento y carga de manera sencilla y potente</em></p>
</div>

## Info

Stressor CLI es una interfaz de línea de comandos para ejecutar pruebas de rendimiento, carga y auditorías usando `stressor-core`. Combina la potencia de **k6** para pruebas de carga y **Lighthouse** para auditorías en una herramienta fácil de usar desde terminal.

## Resumen de características

- **Interfaz CLI intuitiva** - Comandos simples y bien documentados
- **Formatos de salida múltiples** - JSON, YAML, tabla, CSV
- **Configuración flexible** - Archivos YAML/JSON o parámetros CLI
- **Ejecución en paralelo** - Soporte para tests simultáneos
- **Logging detallado** - Verbose mode y salida silenciosa
- **Validación integrada** - Verificación automática de configuraciones

## Instalación

### Global (recomendado)

```bash
npm install -g stressor-cli
# o
pnpm add -g stressor-cli
# o
yarn global add stressor-cli
```

### Local
```bash
npm install --save-dev stressor-cli
# o
pnpm add -D stressor-cli
```

### Desde fuente (para desarrollo)
```bash
git clone https://github.com/rodnye/stressor-cli.git
cd stressor-cli
pnpm install
pnpm build
pnpm link --global
```

## Ejemplo de usos

```bash
# Mostrar ayuda
stressor --help

# Ejecutar tests desde archivo de configuración
stressor run -c config.yaml

# Ejecutar audit test directo
stressor test audit --url https://example.com

# Ejecutar load test directo
stressor test load --scenario ./tests/api.yml --vus 20 --duration 1m
```

## Comandos básicos

### `stressor run`
Ejecuta tests desde un archivo de configuración.

```bash
stressor run -c config.yaml
stressor run -c config.json --name "Mi Test" --parallel
stressor run -c config.yaml --output json --output-file results.json
```

**Opciones:**
- `-c, --config <path>` - Ruta al archivo de configuración (YAML/JSON) (requerido)
- `--name <name>` - Sobrescribir nombre del test suite
- `--owner <owner>` - Sobrescribir propietario del test
- `--id <id>` - Sobrescribir ID del test
- `--parallel` - Ejecutar tests en paralelo
- `--timeout <ms>` - Timeout en milisegundos
- `--save-raw` - Guardar datos de salida crudos
- `-o, --output <format>` - Formato de salida (json, yaml, table)
- `--output-file <path>` - Escribir salida a archivo

### `stressor test audit`
Ejecuta una auditoría Lighthouse.

```bash
stressor test audit --url https://example.com
stressor test audit --url https://example.com --form-factor mobile --categories performance,seo
stressor test audit --url https://example.com --show-audits --output json
```

**Opciones:**
- `--url <url>` - URL a auditar (requerido)
- `--form-factor <type>` - Factor de forma (mobile|desktop, default: desktop)
- `--categories <items>` - Categorías (comma-separated, default: performance,seo,accessibility,best-practices)
- `--show-audits` - Mostrar auditorías detalladas
- `--chrome-path <path>` - Ruta personalizada a Chrome
- `-o, --output <format>` - Formato de salida (json, yaml, table)

### `stressor test load`
Ejecuta una prueba de carga.

```bash
stressor test load --scenario ./scenarios/api.json
stressor test load --scenario ./scenarios/api.json --vus 20 --duration 1m
stressor test load --scenario api.json --stages '[{"duration":"30s","target":10},{"duration":"1m","target":50}]'
stressor test load --scenario '{"executor":"constant-vus","vus":10,"duration":"30s"}' --name "Smoke Test"
stressor test load --scenario api.json --output csv --output-file results.csv
stressor test load --scenario api.json --config load-config.yaml
```

**Opciones:**
- `--scenario <path>` - Ruta al archivo de escenario o JSON inline (requerido)
- `--vus <number>` - Usuarios virtuales (default: 10)
- `--iterations <number>` - Iteraciones totales (default: 100)
- `--duration <duration>` - Duración del test (ej: "30s", "1m", "5m30s")
- `--stages <stages>` - Definición de stages como JSON string
- `--name <name>` - Sobrescribir nombre del test
- `--description <text>` - Descripción del test
- `--tags <tags>` - Tags como lista separada por comas
- `--thresholds <thresholds>` - Thresholds como JSON string
- `--config <path>` - Archivo de configuración adicional para merge
- `-o, --output <format>` - Formato de salida (json, yaml, table, csv)
- `--output-file <path>` - Escribir salida a archivo
- `--verbose` - Habilitar logging detallado
- `--silent` - Suprimir todo output excepto errores

## ⚙️ Configuración

### Archivo de configuración (YAML/JSON)

```yaml
# config.yaml
id: mi-test-produccion
name: "Prueba API Ecommerce"
owner: "equipo-qa"
description: "Prueba de carga para API principal"

# Configuración de carga
load:
  scenario:
    executor: ramping-vus
    steps: 
      request: 
        url: "https://mi-ecommerce.com/api"
    stages:
      - duration: "30s"
        target: 10
      - duration: "1m"
        target: 50
      - duration: "30s"
        target: 0
  options:
    vus: 50
    thresholds:
      http_req_duration: ["p(95)<500"]
      http_req_failed: ["rate<0.01"]

# Configuración de auditoría
audit:
  url: "https://mi-ecommerce.com"
  categories:
    - performance
    - seo
  settings:
    formFactor: "desktop"

# Opciones globales
options:
  runInParallel: false
  timeout: 300000
  saveRaw: true
```

## Formatos de Salida

### Tabla (default)
```bash
stressor run -c config.yaml --output table
```
```
Key                | Value
-------------------|-----------------------------
Test Name          | Prueba API Ecommerce
Status             | COMPLETED
Duration           | 65.23s
Total Requests     | 12500
Avg Response Time  | 245.12 ms
Success Rate       | 99.8%
```

### JSON
```bash
stressor run -c config.yaml --output json
```
```json
{
  "testName": "Prueba API Ecommerce",
  "status": "COMPLETED",
  "duration": 65.23,
  "metrics": {
    "totalRequests": 12500,
    "avgResponseTime": 245.12,
    "successRate": 0.998
  }
}
```

### YAML
```bash
stressor run -c config.yaml --output yaml
```
```yaml
testName: Prueba API Ecommerce
status: COMPLETED
duration: 65.23
metrics:
  totalRequests: 12500
  avgResponseTime: 245.12
  successRate: 0.998
```

### CSV
```bash
stressor test load --scenario api.json --output csv --output-file results.csv
```

## 🔧 Opciones Globales

- `--verbose` - Habilitar logging detallado
- `--silent` - Suprimir todo output excepto errores
- `--version` - Mostrar versión
- `-h, --help` - Mostrar ayuda

## Docker 

Para integración en docker, aquí hay un ejemplo:

```dockerfile
FROM node:18-alpine

RUN npm install -g stressor-cli

WORKDIR /app

COPY scenarios/ ./scenarios/
COPY config.yaml .

ENTRYPOINT ["stressor"]
```

```bash
docker build -t stressor-cli .
docker run -v $(pwd)/results:/app/results stressor-cli run -c config.yaml --output-file /app/results/report.json
```
