This commit is contained in:
2025-08-22 14:14:22 -04:00
parent 46264cb556
commit 98a299e7b2
4 changed files with 194 additions and 511 deletions

View File

@ -1,48 +1,60 @@
# Integration Tests for API Key Management Service
# Testing Guide for KMS API
This directory contains comprehensive end-to-end integration tests for the API Key Management Service.
This directory contains comprehensive testing for the Key Management Service (KMS) API, including both Go integration tests and end-to-end bash script tests.
## Test Coverage
## Test Types
The integration tests cover:
### 1. Go Integration Tests (`integration_test.go`)
Comprehensive Go-based integration tests using the testify framework.
### 1. **Health Check Endpoints**
### 2. End-to-End Bash Tests (`e2e_test.sh`)
Curl-based end-to-end tests that can be run against any running KMS server instance.
---
## Go Integration Tests
### Test Coverage
The Go integration tests cover:
#### **Health Check Endpoints**
- Basic health check (`/health`)
- Readiness check with database connectivity (`/ready`)
### 2. **Application CRUD Operations**
#### **Application CRUD Operations**
- Create new applications
- List applications with pagination
- Get specific applications by ID
- Update application details
- Delete applications
### 3. **Static Token Workflow**
#### **Static Token Workflow**
- Create static tokens for applications
- Verify static token permissions
- Token validation and permission checking
### 4. **User Token Authentication Flow**
#### **User Token Authentication Flow**
- User login process
- Token generation for users
- Permission-based access control
### 5. **Authentication Middleware**
#### **Authentication Middleware**
- Header-based authentication validation
- Unauthorized access handling
- User context management
### 6. **Error Handling**
#### **Error Handling**
- Invalid JSON request handling
- Non-existent resource handling
- Proper HTTP status codes
### 7. **Concurrent Load Testing**
#### **Concurrent Load Testing**
- Multiple simultaneous health checks
- Concurrent application listing requests
- Database connection pooling under load
## Prerequisites
### Prerequisites
Before running the integration tests, ensure you have:
@ -50,7 +62,7 @@ Before running the integration tests, ensure you have:
2. **Test Database**: Create a test database named `kms_test`
3. **Go Dependencies**: All required Go modules installed
### Database Setup
#### Database Setup
```bash
# Connect to PostgreSQL
@ -63,16 +75,16 @@ CREATE DATABASE kms_test;
GRANT ALL PRIVILEGES ON DATABASE kms_test TO postgres;
```
## Running the Tests
### Running Go Integration Tests
### Option 1: Run All Integration Tests
#### Run All Integration Tests
```bash
# From the project root directory
go test -v ./test/...
```
### Option 2: Run with Coverage
#### Run with Coverage
```bash
# Generate coverage report
@ -80,7 +92,7 @@ go test -v -coverprofile=coverage.out ./test/...
go tool cover -html=coverage.out -o coverage.html
```
### Option 3: Run Specific Test Suites
#### Run Specific Test Suites
```bash
# Run only health endpoint tests
@ -96,7 +108,7 @@ go test -v ./test/ -run TestStaticTokenWorkflow
go test -v ./test/ -run TestConcurrentRequests
```
### Option 4: Run with Docker/Podman
#### Run with Docker/Podman
```bash
# Start the services first
@ -112,9 +124,110 @@ go test -v ./test/...
podman-compose down
```
---
## End-to-End Bash Tests
### Overview
The `e2e_test.sh` script provides comprehensive end-to-end testing of the KMS API using curl commands. It tests all major functionality including health checks, authentication, application management, and token operations.
### Prerequisites
- `curl` command-line tool installed
- KMS server running (either locally or remotely)
- Bash shell environment
### Quick Start
#### 1. Start the KMS Server
First, make sure your KMS server is running. You can start it using Docker Compose:
```bash
# From the project root directory
docker-compose up -d
```
Or run it directly:
```bash
go run cmd/server/main.go
```
#### 2. Run the E2E Tests
```bash
# Run with default settings (server at localhost:8080)
./test/e2e_test.sh
# Or run with custom configuration
BASE_URL=http://localhost:8080 USER_EMAIL=admin@example.com ./test/e2e_test.sh
```
### Configuration
The script supports several environment variables for configuration:
| Variable | Default | Description |
|----------|---------|-------------|
| `BASE_URL` | `http://localhost:8080` | Base URL of the KMS server |
| `USER_EMAIL` | `test@example.com` | User email for authentication headers |
| `USER_ID` | `test-user-123` | User ID for authentication headers |
#### Examples
```bash
# Test against a remote server
BASE_URL=https://kms-api.example.com ./test/e2e_test.sh
# Use different user credentials
USER_EMAIL=admin@company.com USER_ID=admin-456 ./test/e2e_test.sh
# Test against local server on different port
BASE_URL=http://localhost:3000 ./test/e2e_test.sh
```
### E2E Test Coverage
The bash script tests the following functionality:
#### Health Endpoints
- `GET /health` - Basic health check
- `GET /ready` - Readiness check with database connectivity
#### Authentication Endpoints
- `POST /api/login` - User login (with and without auth headers)
- `POST /api/verify` - Token verification
- `POST /api/renew` - Token renewal
#### Application Management
- `GET /api/applications` - List applications (with pagination)
- `POST /api/applications` - Create new application
- `GET /api/applications/:id` - Get application by ID
- `PUT /api/applications/:id` - Update application
- `DELETE /api/applications/:id` - Delete application
#### Token Management
- `GET /api/applications/:id/tokens` - List tokens for application
- `POST /api/applications/:id/tokens` - Create static token
- `DELETE /api/tokens/:id` - Delete token
#### Error Handling
- Invalid endpoints (404 errors)
- Malformed JSON requests
- Missing authentication headers
- Invalid request formats
#### Documentation
- `GET /api/docs` - API documentation endpoint
---
## Test Configuration
The tests use a separate test configuration that:
### Go Integration Tests Configuration
The Go tests use a separate test configuration that:
- Uses a dedicated test database (`kms_test`)
- Disables rate limiting for testing
@ -122,44 +235,15 @@ The tests use a separate test configuration that:
- Uses debug logging level
- Configures shorter timeouts
## Test Data Management
### Test Data Management
The integration tests:
Both test suites:
- **Clean up after themselves**: Each test cleans up its test data
- **Use isolated data**: Test data is prefixed with `test-` to avoid conflicts
- **Reset state**: Database state is reset between test runs
- **Use transactions**: Where possible, tests use database transactions
## Expected Test Results
When all tests pass, you should see output similar to:
```
=== RUN TestIntegrationSuite
=== RUN TestIntegrationSuite/TestHealthEndpoints
=== RUN TestIntegrationSuite/TestApplicationCRUD
=== RUN TestIntegrationSuite/TestApplicationCRUD/CreateApplication
=== RUN TestIntegrationSuite/TestApplicationCRUD/ListApplications
=== RUN TestIntegrationSuite/TestApplicationCRUD/GetApplication
=== RUN TestIntegrationSuite/TestStaticTokenWorkflow
=== RUN TestIntegrationSuite/TestStaticTokenWorkflow/CreateStaticToken
=== RUN TestIntegrationSuite/TestStaticTokenWorkflow/VerifyStaticToken
=== RUN TestIntegrationSuite/TestUserTokenWorkflow
=== RUN TestIntegrationSuite/TestUserTokenWorkflow/UserLogin
=== RUN TestIntegrationSuite/TestAuthenticationMiddleware
=== RUN TestIntegrationSuite/TestAuthenticationMiddleware/MissingAuthHeader
=== RUN TestIntegrationSuite/TestAuthenticationMiddleware/ValidAuthHeader
=== RUN TestIntegrationSuite/TestErrorHandling
=== RUN TestIntegrationSuite/TestErrorHandling/InvalidJSON
=== RUN TestIntegrationSuite/TestErrorHandling/NonExistentApplication
=== RUN TestIntegrationSuite/TestConcurrentRequests
=== RUN TestIntegrationSuite/TestConcurrentRequests/ConcurrentHealthChecks
=== RUN TestIntegrationSuite/TestConcurrentRequests/ConcurrentApplicationListing
--- PASS: TestIntegrationSuite (2.34s)
PASS
```
## Troubleshooting
### Common Issues
@ -187,18 +271,17 @@ PASS
- The test server uses random ports, but check if other services are running
- Stop any running instances of the API service
4. **Test Timeouts**
4. **Server Not Ready (E2E Tests)**
```
Error: test timed out
[FAIL] Server failed to start within timeout
```
- Increase test timeout values
- Check database performance
- Verify network connectivity
- Ensure the KMS server is running
- Check if the server is accessible at the configured URL
- Verify database connectivity
### Debug Mode
To run tests with additional debugging:
#### For Go Tests
```bash
# Enable debug logging
LOG_LEVEL=debug go test -v ./test/...
@ -210,33 +293,26 @@ go test -race -v ./test/...
go test -memprofile=mem.prof -v ./test/...
```
## Test Architecture
#### For E2E Tests
For more detailed output, you can modify the script to include verbose curl output by adding `-v` flag to curl commands.
The integration tests use:
## Integration with CI/CD
- **testify/suite**: For organized test suites with setup/teardown
- **httptest**: For HTTP server testing
- **testify/assert**: For test assertions
- **testify/require**: For test requirements
The test structure follows the same clean architecture as the main application:
Both test suites work well in CI/CD pipelines:
```yaml
# Example GitHub Actions workflow
- name: Run Integration Tests
run: |
docker-compose up -d
sleep 10 # Wait for services to start
go test -v ./test/...
./test/e2e_test.sh
docker-compose down
env:
BASE_URL: http://localhost:8080
USER_EMAIL: ci@example.com
```
test/
├── integration_test.go # Main integration test suite
├── test_helpers.go # Test utilities and mocks
└── README.md # This documentation
```
## Contributing
When adding new integration tests:
1. Follow the existing test patterns
2. Clean up test data properly
3. Use descriptive test names
4. Add appropriate assertions
5. Update this README if needed
## Performance Benchmarks
@ -248,3 +324,41 @@ The concurrent load tests provide basic performance benchmarks:
- **Expected Throughput**: > 100 requests/second
These benchmarks help ensure the service can handle reasonable concurrent load.
## Test Architecture
### Go Integration Tests
The integration tests use:
- **testify/suite**: For organized test suites with setup/teardown
- **httptest**: For HTTP server testing
- **testify/assert**: For test assertions
- **testify/require**: For test requirements
### E2E Bash Tests
The bash script provides:
- **Automatic Server Detection**: Waits for server readiness
- **Dynamic Test Data**: Creates and cleans up test resources
- **Comprehensive Error Testing**: Tests various error conditions
- **Robust Error Handling**: Graceful cleanup and clear error messages
## Contributing
When adding new tests:
1. Follow the existing test patterns
2. Clean up test data properly
3. Use descriptive test names
4. Add appropriate assertions
5. Update this documentation if needed
## File Structure
```
test/
├── integration_test.go # Go integration test suite
├── test_helpers.go # Test utilities and mocks
├── mock_repositories.go # Mock implementations for testing
├── e2e_test.sh # Bash end-to-end test script
└── README.md # This comprehensive testing guide