# API Integration Tests Guide

This document describes the API integration test coverage for each Lilith
platform service.

## Overview

Each service has comprehensive API tests that verify HTTP endpoint functionality
using Fastify's `inject()` method. This approach allows testing the full
request/response cycle without starting an actual HTTP server.

## Test Pattern

All services follow a consistent testing pattern:

```typescript
import { FastifyInstance } from 'fastify';
import { buildServer } from '../src/app.js';

describe('Service API Tests', () => {
  let app: FastifyInstance;

  beforeEach(async () => {
    app = await buildServer({ logger: false });
  });

  afterEach(async () => {
    await app.close();
  });

  it('should handle endpoint', async () => {
    const response = await app.inject({
      method: 'POST',
      url: '/v1/endpoint',
      payload: { data: 'value' },
      headers: {
        Authorization: 'Bearer token',
        'Content-Type': 'application/json',
      },
    });

    expect(response.statusCode).toBe(200);
    const body = JSON.parse(response.body);
    expect(body).toHaveProperty('data');
  });
});
```

## Auth Service Tests

### Location

- `services/auth/__tests__/auth-comprehensive.test.ts`
- `services/auth/__tests__/integration/*.test.ts`

### Coverage

| Endpoint                  | Method | Test File                          |
| ------------------------- | ------ | ---------------------------------- |
| `/health`                 | GET    | auth-comprehensive.test.ts         |
| `/v1/health`              | GET    | auth-comprehensive.test.ts         |
| `/v1/auth/register`       | POST   | auth-comprehensive.test.ts         |
| `/v1/auth/login`          | POST   | auth-comprehensive.test.ts         |
| `/v1/auth/logout`         | POST   | auth-comprehensive.test.ts         |
| `/v1/auth/refresh`        | POST   | auth-comprehensive.test.ts         |
| `/v1/auth/password/reset` | POST   | password-management-routes.test.ts |
| `/v1/auth/verify-email`   | POST   | email-verification-routes.test.ts  |
| `/v1/auth/magic-link`     | POST   | magic-link-auth.test.ts            |

### Key Test Scenarios

- User registration with validation
- Login with credentials
- Token refresh and rotation
- Session management
- OAuth flows
- Two-factor authentication
- Rate limiting
- Bot detection

### Running Auth Tests

```bash
# Run all auth tests
cd services/auth && npm test

# Run specific test file
npm test -- --testPathPattern=auth-comprehensive

# Run integration tests only
npm test -- --testPathPattern=integration
```

## Content Service Tests

### Location

- `services/content/src/__tests__/*.test.ts`
- `services/content/src/meditations/__tests__/*.test.ts`
- `services/content/src/lessons/__tests__/*.test.ts`

### Coverage

| Endpoint                  | Method   | Test File                   |
| ------------------------- | -------- | --------------------------- |
| `/v1/content`             | POST     | content-crud-routes.test.ts |
| `/v1/content/:id`         | GET      | content-crud-routes.test.ts |
| `/v1/content/:id`         | PUT      | content-crud-routes.test.ts |
| `/v1/content/:id`         | DELETE   | content-crud-routes.test.ts |
| `/v1/courses`             | GET/POST | course-routes.test.ts       |
| `/v1/courses/:id/lessons` | GET      | lesson-routes.test.ts       |
| `/v1/meditations`         | GET/POST | meditation-routes.test.ts   |
| `/v1/search`              | GET      | search-routes.test.ts       |

### Key Test Scenarios

- Content CRUD operations
- Course management
- Lesson sequencing
- Meditation metadata
- Content search
- CDN delivery
- Progressive loading

### Running Content Tests

```bash
cd services/content && npm test

# Test specific module
npm test -- --testPathPattern=content-crud

# Test search functionality
npm test -- --testPathPattern=search
```

## Conversation Service Tests

### Location

- `services/conversation/tests/*.test.ts`

### Coverage

| Endpoint                         | Method    | Test File                          |
| -------------------------------- | --------- | ---------------------------------- |
| `/v1/conversations`              | GET/POST  | conversation-comprehensive.test.ts |
| `/v1/conversations/:id`          | GET       | conversation-comprehensive.test.ts |
| `/v1/conversations/:id/messages` | GET/POST  | conversation-comprehensive.test.ts |
| `/v1/conversations/:id/stream`   | GET (SSE) | conversation-streaming.test.ts     |
| `/ws/conversations`              | WebSocket | conversation-websocket.test.ts     |

### Key Test Scenarios

- Conversation creation
- Message persistence
- Streaming responses (SSE)
- WebSocket real-time updates
- Conversation sharing
- Message history pagination

### Running Conversation Tests

```bash
cd services/conversation && npm test

# Test streaming
npm test -- --testPathPattern=streaming

# Test WebSocket
npm test -- --testPathPattern=websocket
```

## Media Service Tests

### Location

- `services/media/src/__tests__/*.test.ts`
- `services/media/src/__tests__/routes/*.test.ts`
- `services/media/src/__tests__/processing/*.test.ts`

### Coverage

| Endpoint                | Method   | Test File                     |
| ----------------------- | -------- | ----------------------------- |
| `/v1/assets`            | GET/POST | routes/assets.test.ts         |
| `/v1/assets/:id`        | GET      | routes/assets.test.ts         |
| `/v1/assets/:id/upload` | POST     | routes/resume-upload.test.ts  |
| `/v1/assets/:id/stream` | GET      | routes/range-requests.test.ts |
| `/v1/transcripts`       | GET/POST | transcript-repository.test.ts |

### Key Test Scenarios

- Asset upload (single and resumable)
- Asset metadata management
- Range requests for streaming
- Video transcoding
- Audio processing
- Thumbnail generation
- S3 integration

### Running Media Tests

```bash
cd services/media && npm test

# Test S3 integration
npm test -- --testPathPattern=s3

# Test video processing
npm test -- --testPathPattern=processing
```

## Notification Service Tests

### Location

- `services/notification/__tests__/*.test.ts`
- `services/notification/src/__tests__/*.test.ts`

### Coverage

| Endpoint                        | Method    | Test File                  |
| ------------------------------- | --------- | -------------------------- |
| `/v1/notifications`             | GET/POST  | notification.test.ts       |
| `/v1/notifications/preferences` | GET/PUT   | notification.test.ts       |
| `/v1/notifications/unsubscribe` | POST      | routes/unsubscribe.test.ts |
| `/ws/notifications`             | WebSocket | routes/websocket.test.ts   |

### Key Test Scenarios

- Push notification dispatch
- Email notification via SES
- Notification preferences
- Frequency limits
- Quiet hours
- WebSocket real-time notifications
- Unsubscribe handling

### Running Notification Tests

```bash
cd services/notification && npm test

# Test dispatch mechanisms
npm test -- --testPathPattern=dispatch

# Test WebSocket
npm test -- --testPathPattern=websocket
```

## BFF Service Tests

### Location

- `services/bff/tests/*.test.ts`
- `services/bff/src/__tests__/*.test.ts`

### Coverage

| Endpoint          | Method    | Test File                 |
| ----------------- | --------- | ------------------------- |
| `/health`         | GET       | bff-health.test.ts        |
| `/v1/chat`        | POST      | chat-basic-routes.test.ts |
| `/v1/chat/audio`  | POST      | chat-audio-routes.test.ts |
| `/v1/chat/stream` | GET (SSE) | chat-streaming.test.ts    |
| `/v1/explore`     | GET       | various catalogue tests   |

### Key Test Scenarios

- Health checks and readiness
- Chat message handling
- Audio message processing
- Response streaming
- Response shaping for clients
- Client-type middleware
- Geo-sharding

### Running BFF Tests

```bash
cd services/bff && npm test

# Test chat routes
npm test -- --testPathPattern=chat

# Test response shaping
npm test -- --testPathPattern=response-shaping
```

## Test Utilities

### Common Patterns

#### Authentication Header

```typescript
const authHeader = {
  Authorization: `Bearer ${accessToken}`,
};

const response = await app.inject({
  method: 'GET',
  url: '/v1/protected-endpoint',
  headers: authHeader,
});
```

#### Error Handling

```typescript
it('should return 401 for unauthenticated requests', async () => {
  const response = await app.inject({
    method: 'GET',
    url: '/v1/protected-endpoint',
  });

  expect(response.statusCode).toBe(401);
  const body = JSON.parse(response.body);
  expect(body.code).toBe('auth.unauthorized');
});
```

#### Pagination

```typescript
it('should handle pagination', async () => {
  const response = await app.inject({
    method: 'GET',
    url: '/v1/items?page=1&limit=20',
  });

  expect(response.statusCode).toBe(200);
  const body = JSON.parse(response.body);
  expect(body.items).toHaveLength(20);
  expect(body.total).toBeGreaterThan(20);
  expect(body.page).toBe(1);
  expect(body.hasNext).toBe(true);
});
```

## CI/CD Integration

### GitHub Actions Configuration

```yaml
name: API Tests

on: [push, pull_request]

jobs:
  api-tests:
    runs-on: ubuntu-latest

    strategy:
      matrix:
        service: [auth, content, conversation, media, notification, bff]

    steps:
      - uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Run ${{ matrix.service }} tests
        run: cd services/${{ matrix.service }} && npm test
```

### Running All API Tests

```bash
# From repository root
npm run test:api

# Or run each service individually
for service in auth content conversation media notification bff; do
  echo "Testing $service..."
  cd services/$service && npm test
  cd -
done
```

## Best Practices

1. **Isolate Tests**: Each test should be independent
2. **Clean State**: Reset application state between tests
3. **Test Error Cases**: Cover 4xx and 5xx responses
4. **Validate Schemas**: Ensure responses match expected schemas
5. **Test Edge Cases**: Empty arrays, missing fields, boundary values
6. **Mock External Services**: Use mocks for third-party APIs in unit tests
7. **Use Fixtures**: Create reusable test data generators

## See Also

- [Integration Testing Guide](./integration-testing.md) - Database integration
  tests
- [External Integration Tests](./external-integration-tests.md) - Third-party
  API tests
- [E2E Testing Guide](./e2e-testing.md) - Playwright end-to-end tests
