# Slidev E2E Test Suite

Comprehensive end-to-end tests for Slidev deck generation, GitHub Pages publishing, and control commands.

## Overview

This test suite validates the complete Slidev presentation flow:

1. **Happy Path Tests** (`slidev-flow.spec.ts`)
   - Full deck generation and GitHub Pages publish workflow
   - Control commands (next, prev, goto)
   - Performance benchmarks
   - Placeholder replacement validation

2. **Error Handling Tests** (`error-handling.spec.ts`)
   - Invalid session IDs and parameters
   - Missing/invalid API keys
   - Rate limiting
   - Malformed requests
   - Concurrent operations

3. **Browser Compatibility Tests** (`browser-compatibility.spec.ts`)
   - Chrome, Firefox, Safari, Edge support
   - Mobile viewports
   - Cross-browser synchronization
   - Performance consistency

## Prerequisites

### Required Environment Variables

Create a `.env` file in the project root:

```bash
# API Configuration
API_BASE_URL=http://localhost:3000  # Or your staging/production URL
SLIDEV_API_KEY=your-api-key-here

# GitHub Integration
GITHUB_TOKEN=your-github-token-here

# Supabase Configuration
SUPABASE_URL=your-supabase-url
SUPABASE_SERVICE_KEY=your-service-key
```

### Install Dependencies

```bash
pnpm install
npx playwright install
```

This will install Playwright and download browser binaries for Chrome, Firefox, Safari, and Edge.

## Running Tests

### Run All E2E Tests

```bash
npx playwright test tests/e2e
```

### Run Specific Test Suite

```bash
# Happy path tests only
npx playwright test tests/e2e/slidev-flow.spec.ts

# Error handling tests only
npx playwright test tests/e2e/error-handling.spec.ts

# Browser compatibility tests only
npx playwright test tests/e2e/browser-compatibility.spec.ts
```

### Run Tests in Specific Browser

```bash
# Chrome only
npx playwright test --project=chromium

# Firefox only
npx playwright test --project=firefox

# Safari only
npx playwright test --project=webkit

# Edge only
npx playwright test --project="Microsoft Edge"
```

### Run Tests in UI Mode (Interactive)

```bash
npx playwright test --ui
```

This opens an interactive UI where you can:
- Run tests selectively
- View test execution in real-time
- Debug failures
- Inspect screenshots and traces

### Run Tests with Debugging

```bash
# Debug a specific test
npx playwright test tests/e2e/slidev-flow.spec.ts --debug

# Debug with headed browser
npx playwright test --headed --project=chromium
```

### Generate Test Report

```bash
npx playwright test
npx playwright show-report
```

This opens an HTML report with:
- Test results
- Screenshots on failure
- Video recordings
- Performance metrics

## Test Configuration

### Timeouts

Tests are configured with extended timeouts to accommodate GitHub Pages publishing:

- **Test timeout:** 3 minutes (180,000ms)
- **Action timeout:** 30 seconds
- **Navigation timeout:** 60 seconds

These can be adjusted in `playwright.config.ts`.

### GitHub Pages Delays

GitHub Pages typically takes 30-90 seconds to publish. Tests include:

- `waitForGitHubPages()` helper with retry logic
- Extended timeout for initial deck generation
- Polling mechanism to detect when URL becomes accessible

### API Rate Limiting

Control command tests may trigger rate limiting. Tests handle this gracefully and verify rate limiter is working.

## Test Helpers

The `helpers.ts` module provides reusable utilities:

### Session Management

```typescript
// Setup test session with deck generation
const { deckId, deckUrl } = await setupTestSession({
  data: {
    COMPANY_NAME: 'Test Company',
    INDUSTRY: 'Technology'
  }
});
```

### GitHub Pages

```typescript
// Wait for GitHub Pages to publish
await waitForGitHubPages(deckUrl, maxWaitMs, retryIntervalMs);
```

### Control Commands

```typescript
// Send control commands
await sendControlCommand(deckId, 'next');
await sendControlCommand(deckId, 'prev');
await sendControlCommand(deckId, 'goto', '3');
```

### Screenshot Capture

```typescript
// Capture screenshot on failure
await captureScreenshot(page, 'test-failure');
```

### Cleanup

```typescript
// Clean up test decks
await cleanupTestDecks([deckId1, deckId2]);
```

## Performance Benchmarks

Tests validate the following performance targets:

| Metric | Target | Ideal | Validation |
|--------|--------|-------|------------|
| Deck Build Time | < 30s | < 15s | Measured |
| GitHub Pages Publish | < 60s | < 30s | Measured |
| Total Generation Time | < 90s | < 60s | **Required** |
| Control Command Latency | < 500ms | < 200ms | **Required** |
| Page Load Time | < 3s | < 2s | Measured |

## CI/CD Integration

### GitHub Actions

Add to `.github/workflows/e2e-tests.yml`:

```yaml
name: E2E Tests

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'

      - name: Install dependencies
        run: pnpm install

      - name: Install Playwright
        run: npx playwright install --with-deps

      - name: Run E2E tests
        env:
          API_BASE_URL: ${{ secrets.API_BASE_URL }}
          SLIDEV_API_KEY: ${{ secrets.SLIDEV_API_KEY }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          SUPABASE_URL: ${{ secrets.SUPABASE_URL }}
          SUPABASE_SERVICE_KEY: ${{ secrets.SUPABASE_SERVICE_KEY }}
        run: npx playwright test tests/e2e

      - name: Upload test results
        if: always()
        uses: actions/upload-artifact@v3
        with:
          name: playwright-report
          path: test-results/
          retention-days: 30
```

## Test Environment Setup

### Local Development

1. Start the Motia API server:
   ```bash
   pnpm nx serve motia-api
   ```

2. Ensure Supabase is running (or use cloud instance)

3. Run tests against local API:
   ```bash
   API_BASE_URL=http://localhost:3000 npx playwright test
   ```

### Staging Environment

```bash
API_BASE_URL=https://staging.buzztrail.ai npx playwright test
```

### Production Environment

**WARNING:** Running tests against production will create real decks and consume GitHub API quota.

Only run smoke tests in production:

```bash
API_BASE_URL=https://api.buzztrail.ai npx playwright test tests/e2e/slidev-flow.spec.ts -g "should generate deck"
```

## Troubleshooting

### Test Failures

1. **GitHub Pages timeout**
   - GitHub Pages can take up to 90 seconds to publish
   - Check GitHub Actions workflow status
   - Verify GITHUB_TOKEN has correct permissions

2. **Session not found (404)**
   - Ensure Supabase is accessible
   - Check SUPABASE_URL and SUPABASE_SERVICE_KEY
   - Verify conversation_sessions table exists

3. **API key errors (401)**
   - Verify SLIDEV_API_KEY matches server configuration
   - Check API key is set in .env file

4. **Rate limiting (429)**
   - Tests intentionally trigger rate limits
   - This is expected behavior
   - Adjust rate limit configuration if needed

5. **Browser not found**
   - Run `npx playwright install` to download browsers
   - Use `npx playwright install --with-deps` on Linux

### Debugging Tips

1. **Enable verbose logging:**
   ```bash
   DEBUG=pw:api npx playwright test
   ```

2. **Keep browser open on failure:**
   ```bash
   npx playwright test --headed --debug
   ```

3. **View test traces:**
   ```bash
   npx playwright show-trace test-results/trace.zip
   ```

4. **Generate screenshot on specific test:**
   Add to test:
   ```typescript
   await page.screenshot({ path: 'debug.png', fullPage: true });
   ```

## Test Data Cleanup

For MVP, test decks are left in place for manual inspection. To clean up:

1. **Database:** Delete entries from `slidev_decks` table
2. **GitHub:** Manually remove deck directories from `buzztrail-presentations` repo
3. **Local files:** Temp directories are auto-cleaned

Future enhancement: Implement automated cleanup script.

## Writing New Tests

### Test Structure

```typescript
import { test, expect } from '@playwright/test';
import { setupTestSession, waitForGitHubPages } from './helpers';

test.describe('My Test Suite', () => {
  let deckId: string;
  let deckUrl: string;

  test.beforeAll(async () => {
    // Setup shared resources
    const result = await setupTestSession();
    deckId = result.deckId;
    deckUrl = result.deckUrl;
  });

  test.afterAll(async () => {
    // Cleanup
    await cleanupTestDecks([deckId]);
  });

  test('should do something', async ({ page }) => {
    await page.goto(deckUrl);
    // Test logic here
  });
});
```

### Best Practices

1. **Use helpers:** Import utilities from `helpers.ts`
2. **Handle GitHub Pages delays:** Always use `waitForGitHubPages()`
3. **Capture screenshots:** Use `captureScreenshot()` on failures
4. **Clean up:** Call `cleanupTestDecks()` in `afterAll`
5. **Log progress:** Use `console.log()` for debugging
6. **Test isolation:** Each test should be independent
7. **Timeouts:** Set appropriate timeouts for async operations

## Resources

- [Playwright Documentation](https://playwright.dev/)
- [Slidev Documentation](https://sli.dev/)
- [GitHub Pages Documentation](https://docs.github.com/en/pages)
- [Supabase Realtime Documentation](https://supabase.com/docs/guides/realtime)

## Support

For issues or questions:
- Check troubleshooting section above
- Review test logs and screenshots
- Consult Playwright documentation
- Open an issue on GitHub
