# Testing

Guide to testing your AIDP integration.

## Test Environment

AIDP provides a sandbox environment for testing:

**Sandbox API Base URL**:

```
https://sandbox-api.aidp.dev/v1
```

**Features**:

* Separate from production data
* No rate limits
* Test API keys
* Mock responses available

***

## Getting Test API Keys

1. Go to [Developer Dashboard](https://platform.aidp.dev/developers)
2. Navigate to "API Keys"
3. Click "Create Test Key"
4. Copy your test key (starts with `test_`)

**Test Key Format**: `test_abc123...`\
**Production Key Format**: `live_abc123...`

***

## Test Data

### Sample Businesses

The sandbox includes test businesses you can use:

```javascript
const testBusinessIds = [
  'biz_test_coffee_shop',
  'biz_test_restaurant',
  'biz_test_hotel',
  'biz_test_spa',
];
```

### Sample Queries

Pre-configured test queries:

```javascript
const testQueries = [
  'coffee shop in Portland',
  'best restaurants near me',
  'hotels with spa',
  'yoga studios downtown',
];
```

***

## Unit Testing

### Testing API Calls

```javascript
// Jest example
import { searchBusinesses } from './aidp-client';

describe('AIDP Search API', () => {
  it('should return businesses for valid query', async () => {
    const results = await searchBusinesses({
      query: 'coffee shop',
      location: { lat: 45.5231, lon: -122.6765, distance: '5km' },
    });

    expect(results.success).toBe(true);
    expect(results.data.businesses).toBeInstanceOf(Array);
    expect(results.data.businesses.length).toBeGreaterThan(0);
  });

  it('should handle rate limiting', async () => {
    // Mock rate limit response
    global.fetch = jest.fn(() =>
      Promise.resolve({
        status: 429,
        json: () => Promise.resolve({ error: 'Rate limit exceeded' }),
      })
    );

    await expect(searchBusinesses({ query: 'test' })).rejects.toThrow('Rate limit exceeded');
  });
});
```

### Mocking Responses

```javascript
// Mock AIDP API responses
const mockAIDPResponse = {
  success: true,
  data: {
    query: 'coffee shop',
    response: 'I found several great coffee shops...',
    businesses: [
      {
        id: 'biz_test_123',
        name: 'Test Coffee Shop',
        category: 'restaurants',
        verified: true,
      },
    ],
    total: 1,
    sessionId: 'session-test-123',
  },
};

jest.mock('./aidp-client', () => ({
  searchBusinesses: jest.fn(() => Promise.resolve(mockAIDPResponse)),
}));
```

***

## Integration Testing

### End-to-End Tests

```javascript
describe('AIDP Integration', () => {
  let apiKey;

  beforeAll(() => {
    apiKey = process.env.AIDP_TEST_API_KEY;
  });

  it('should complete full search flow', async () => {
    // 1. Search for businesses
    const searchResults = await fetch('https://sandbox-api.aidp.dev/v1/api/v1/consumer/search', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        query: 'coffee shop',
        location: { lat: 45.5231, lon: -122.6765, distance: '5km' },
      }),
    });

    const data = await searchResults.json();
    expect(data.success).toBe(true);

    // 2. Get business details
    const businessId = data.data.businesses[0].id;
    const businessDetails = await fetch(
      `https://sandbox-api.aidp.dev/v1/api/v1/businesses/${businessId}`,
      {
        headers: { Authorization: `Bearer ${apiKey}` },
      }
    );

    const business = await businessDetails.json();
    expect(business.success).toBe(true);
  });
});
```

***

## Testing Webhooks

### Local Webhook Testing

Use tools like ngrok to test webhooks locally:

```bash
# Start ngrok
ngrok http 3000

# Use the ngrok URL in webhook settings
https://abc123.ngrok.io/webhooks/aidp
```

### Webhook Test Events

Send test events from the Developer Dashboard:

1. Go to Webhooks section
2. Select your webhook
3. Click "Send Test Event"
4. Choose event type
5. Verify receipt

***

## Performance Testing

### Load Testing

```javascript
// Using artillery.io
module.exports = {
  config: {
    target: 'https://sandbox-api.aidp.dev/v1',
    phases: [{ duration: 60, arrivalRate: 10 }],
  },
  scenarios: [
    {
      name: 'Search businesses',
      flow: [
        {
          post: {
            url: '/api/v1/consumer/search',
            headers: {
              Authorization: 'Bearer test_abc123',
            },
            json: {
              query: 'coffee shop',
              location: { lat: 45.5231, lon: -122.6765, distance: '5km' },
            },
          },
        },
      ],
    },
  ],
};
```

***

## Best Practices

### 1. Use Test Keys

Never use production keys in tests:

```javascript
const API_KEY =
  process.env.NODE_ENV === 'production'
    ? process.env.AIDP_LIVE_API_KEY
    : process.env.AIDP_TEST_API_KEY;
```

### 2. Clean Up Test Data

Remove test data after tests:

```javascript
afterEach(async () => {
  await cleanupTestData();
});
```

### 3. Test Error Scenarios

```javascript
it('should handle invalid API key', async () => {
  await expect(searchBusinesses({ query: 'test' }, 'invalid_key')).rejects.toThrow(
    'Invalid API key'
  );
});
```

***

## CI/CD Integration

### GitHub Actions Example

```yaml
name: Test AIDP Integration

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v2
      - run: npm install
      - run: npm test
        env:
          AIDP_TEST_API_KEY: ${{ secrets.AIDP_TEST_API_KEY }}
```

***

## Need Help?

* 📧 Email: <testing@aidp.dev>
* 📚 Documentation: [docs.aidp.dev/testing](https://docs.aidp.dev/testing)
