# Integration Test: REST API

## Summary
Validate the REST API component that provides HTTP endpoints for managing flights, uploading images, retrieving results, and controlling the ASTRAL-Next system.

## Component Under Test
**Component**: GPS Denied REST API
**Location**: `gps_denied_01_gps_denied_rest_api`
**Dependencies**:
- Flight Manager
- Result Manager
- SSE Event Streamer
- Database Layer
- Image Input Pipeline
- Configuration Manager

## Detailed Description
This test validates that the REST API can:
1. Handle flight creation and management (CRUD operations)
2. Accept image uploads for processing
3. Provide endpoints for result retrieval
4. Support user input for manual fixes (AC-6)
5. Manage authentication and authorization
6. Handle concurrent requests
7. Provide appropriate error responses
8. Follow REST conventions and return proper status codes
9. Support SSE connections for real-time updates

The API is the primary interface for external clients to interact with the GPS-denied navigation system.

## Input Data

### Test Case 1: Create Flight
- **Endpoint**: POST /flights
- **Payload**:
```json
{
  "flight_name": "Test_Flight_001",
  "start_gps": {"lat": 48.275292, "lon": 37.385220},
  "altitude_m": 400,
  "camera_params": {
    "focal_length_mm": 25,
    "sensor_width_mm": 23.5,
    "resolution": {"width": 6252, "height": 4168}
  }
}
```
- **Expected**: 201 Created, returns flight_id

### Test Case 2: Upload Single Image
- **Endpoint**: POST /flights/{flightId}/images
- **Payload**: Multipart form-data with AD000001.jpg
- **Headers**: Content-Type: multipart/form-data
- **Expected**: 202 Accepted, processing started

### Test Case 3: Upload Multiple Images
- **Endpoint**: POST /flights/{flightId}/images/batch
- **Payload**: AD000001-AD000010 (10 images)
- **Expected**: 202 Accepted, all images queued

### Test Case 4: Get Flight Status
- **Endpoint**: GET /flights/{flightId}
- **Expected**: 200 OK, returns processing status and statistics

### Test Case 5: Get Results
- **Endpoint**: GET /flights/{flightId}/results
- **Query Params**: ?format=json&include_refined=true
- **Expected**: 200 OK, returns GPS coordinates for all processed images

### Test Case 6: Get Specific Image Result
- **Endpoint**: GET /flights/{flightId}/results?image_id={imageId}
- **Expected**: 200 OK, returns detailed result for one image

### Test Case 7: Submit User Fix (AC-6)
- **Endpoint**: POST /flights/{flightId}/user-fix
- **Payload**:
```json
{
  "frame_id": 15,
  "uav_pixel": [3126, 2084],
  "satellite_gps": {"lat": 48.270334, "lon": 37.374442}
}
```
- **Expected**: 200 OK, system incorporates user fix, processing resumes

### Test Case 8: List Flights
- **Endpoint**: GET /flights
- **Query Params**: ?status=active&limit=10
- **Expected**: 200 OK, returns list of flights

### Test Case 9: Delete Flight
- **Endpoint**: DELETE /flights/{flightId}
- **Expected**: 204 No Content, flight and associated data deleted

### Test Case 10: Error Handling - Invalid Input
- **Endpoint**: POST /flights
- **Payload**: Invalid JSON or missing required fields
- **Expected**: 400 Bad Request with error details

### Test Case 11: Error Handling - Not Found
- **Endpoint**: GET /flights/nonexistent_id
- **Expected**: 404 Not Found

### Test Case 12: SSE Connection
- **Endpoint**: GET /flights/{flightId}/stream
- **Headers**: Accept: text/event-stream
- **Expected**: 200 OK, establishes SSE stream for real-time updates

### Test Case 13: Concurrent Requests
- **Scenario**: 10 simultaneous GET requests for different flights
- **Expected**: All succeed, no race conditions

## Expected Output

For each test case, verify HTTP response:
```json
{
  "status_code": <integer>,
  "headers": {
    "Content-Type": "string",
    "X-Request-ID": "string"
  },
  "body": {
    "success": true/false,
    "data": {...},
    "error": {...}
  },
  "response_time_ms": <float>
}
```

## Success Criteria

**Test Case 1 (Create Flight)**:
- status_code = 201
- Response includes valid flight_id
- Flight persisted in database
- response_time_ms < 500

**Test Case 2 (Upload Single)**:
- status_code = 202
- Image accepted and queued
- Processing begins within 5 seconds
- response_time_ms < 2000

**Test Case 3 (Upload Batch)**:
- status_code = 202
- All 10 images accepted
- Queue order maintained
- response_time_ms < 10000

**Test Case 4 (Get Status)**:
- status_code = 200
- Returns valid status JSON
- Includes processing statistics
- response_time_ms < 200

**Test Case 5 (Get Results)**:
- status_code = 200
- Returns GPS coordinates for all processed images
- JSON format correct
- response_time_ms < 1000

**Test Case 6 (Get Specific Result)**:
- status_code = 200
- Returns detailed result for requested image
- Includes confidence scores
- response_time_ms < 200

**Test Case 7 (User Fix)**:
- status_code = 200
- User fix accepted and applied
- System re-optimizes affected trajectory
- response_time_ms < 500

**Test Case 8 (List Flights)**:
- status_code = 200
- Returns array of flights
- Pagination works correctly
- response_time_ms < 300

**Test Case 9 (Delete)**:
- status_code = 204
- Flight deleted from database
- Associated files cleaned up
- response_time_ms < 1000

**Test Case 10 (Invalid Input)**:
- status_code = 400
- Error message is clear and specific
- Returns which fields are invalid

**Test Case 11 (Not Found)**:
- status_code = 404
- Error message indicates resource not found

**Test Case 12 (SSE)**:
- status_code = 200
- SSE connection established
- Receives events when images processed
- Connection remains open

**Test Case 13 (Concurrent)**:
- All requests succeed
- No 500 errors
- No data corruption
- Average response_time < 500ms

## Maximum Expected Time
- **GET requests**: < 500ms
- **POST create**: < 500ms
- **POST upload single**: < 2 seconds
- **POST upload batch**: < 10 seconds
- **DELETE**: < 1 second
- **Total test suite**: < 120 seconds

## Test Execution Steps

1. **Setup Phase**:
   a. Start REST API server
   b. Initialize database with clean state
   c. Prepare test images
   d. Configure test client

2. **Execute Test Cases Sequentially**:
   a. Run Test Case 1 (Create Flight) - store flight_id
   b. Run Test Case 2 (Upload Single Image) using flight_id
   c. Wait for processing or use Test Case 4 to poll status
   d. Run Test Case 3 (Upload Batch)
   e. Run Test Case 5 (Get Results)
   f. Run Test Case 6 (Get Specific Result)
   g. Run Test Case 7 (User Fix)
   h. Run Test Case 8 (List Flights)
   i. Run Test Case 12 (SSE Connection) in parallel
   j. Run Test Case 13 (Concurrent Requests)
   k. Run Test Case 10 (Invalid Input)
   l. Run Test Case 11 (Not Found)
   m. Run Test Case 9 (Delete Flight) - cleanup

3. **Validation Phase**:
   a. Verify all status codes correct
   b. Check response times
   c. Validate JSON schemas
   d. Verify database state
   e. Check file system state

4. **Cleanup**:
   a. Delete test flights
   b. Remove uploaded images
   c. Clear database test data
   d. Stop API server

## Pass/Fail Criteria

**Overall Test Passes If**:
- All 13 test cases return expected status codes
- Response times meet constraints
- JSON responses match schemas
- No unhandled exceptions or crashes
- Database transactions are atomic
- File uploads/downloads work correctly

**Test Fails If**:
- Any test case returns wrong status code
- Any response time exceeds 2x maximum expected
- Server crashes or becomes unresponsive
- Data corruption occurs
- Race conditions detected in concurrent tests
- SSE connection fails or drops unexpectedly

## Additional Validation

**REST Conventions**:
- Proper use of HTTP methods (GET, POST, PUT, DELETE)
- Idempotent operations (GET, PUT, DELETE)
- Resource-based URLs
- Appropriate status codes (2xx, 4xx, 5xx)

**JSON Schema Validation**:
Verify responses match defined schemas for:
- Flight object
- Image object
- Result object
- Error object
- Status object

**Security Tests**:
1. **Authentication**: Verify API requires valid auth tokens (if implemented)
2. **Authorization**: Verify users can only access their own flights
3. **Input Sanitization**: Test SQL injection, XSS attempts
4. **Rate Limiting**: Verify rate limiting works (if implemented)
5. **CORS**: Verify CORS headers if cross-origin access needed

**Error Handling**:
Test various error scenarios:
- Malformed JSON
- Missing required fields
- Invalid data types
- Oversized payloads
- Unsupported content types
- Database connection failure
- Disk full
- Processing timeout

**Performance Under Load**:
- 100 concurrent GET requests: avg response time < 1 second
- Upload 100 images: complete within 5 minutes
- 1000 status polls: no degradation

**SSE Specific Tests**:
- Reconnection after disconnect
- Message ordering
- Buffering behavior
- Heartbeat/keep-alive
- Error event handling

**File Upload Tests**:
- Maximum file size enforcement
- Supported formats (JPEG, PNG)
- Rejected formats (TXT, EXE)
- Corrupted image handling
- Duplicate filename handling
- Concurrent uploads to same flight

##API Documentation Compliance

Verify endpoints match documented API spec in:
`docs/02_components/gps_denied_01_gps_denied_rest_api/gps_denied_rest_api_spec.md`

Check:
- All documented endpoints exist
- Request/response formats match
- Error codes match documentation
- Required vs optional fields correct

