🧪 Testing Infrastructure (45 tests, 100% passing) - Implemented Jest + Supertest framework for automated testing - Unit tests: 5 tests for auth middleware (100% coverage) - Integration tests: 40 tests covering admin, consent, migration, upload APIs - Test execution time: ~10 seconds for full suite - Coverage: 26% statements, 15% branches (realistic start) - In-memory SQLite database for isolated testing - Singleton server pattern for fast test execution - Automatic cleanup and teardown 🔒 Admin API Authentication - Bearer token authentication for all admin endpoints - requireAdminAuth middleware with ADMIN_API_KEY validation - Protected routes: /api/admin/*, /api/system/migration/migrate|rollback - Complete authentication guide in AUTHENTICATION.md - HTTP 403 for missing/invalid tokens, 500 if not configured - Ready for production with token rotation support 📋 API Route Documentation - Single Source of Truth: backend/src/routes/routeMappings.js - Comprehensive route overview in backend/src/routes/README.md - Express routing order documented (specific before generic) - Frontend integration guide with authentication examples - OpenAPI auto-generation integrated 🐛 Bug Fixes - Fixed SQLite connection not properly awaited (caused test hangs) - Fixed upload validation checking req.files.file before req.files - Fixed Express route order (consent before admin router) - Fixed test environment using /tmp for uploads (permission issues) 📚 Documentation Updates - Updated README.md with testing and authentication features - Updated README.dev.md with testing section and API development guide - Updated CHANGELOG.md with complete feature documentation - Updated FEATURE_PLAN-autogen-openapi.md (status: 100% complete) - Added frontend/MIGRATION-GUIDE.md for frontend team 🚀 Frontend Impact Frontend needs to add Bearer token to all /api/admin/* calls. See frontend/MIGRATION-GUIDE.md for detailed instructions. Test Status: ✅ 45/45 passing (100%) Backend: ✅ Production ready Frontend: ⚠️ Migration required (see MIGRATION-GUIDE.md)
5.9 KiB
5.9 KiB
API Testing Guide
🎯 Testing-Strategie
1. Smoke Tests (Aktuell)
Script: test-openapi-paths.js
Was wird getestet:
- ✅ Alle Pfade sind erreichbar
- ✅ Server antwortet
- ❌ Keine Schema-Validierung
- ❌ Keine Auth-Tests
- ❌ Keine Request Bodies
Verwendung:
npm run test-openapi
Zweck: Schneller Check ob alle Routen mounted sind.
🔧 Empfohlene Testing-Tools
Option 1: Dredd (Contract Testing) ⭐ EMPFOHLEN
Installation:
npm install --save-dev dredd
Setup:
# dredd.yml erstellen
cat > dredd.yml << EOF
color: true
dry-run: false
hookfiles: null
language: nodejs
require: null
server: npm start
server-wait: 3
init: false
custom: {}
names: false
only: []
reporter: []
output: []
header: []
sorted: false
user: null
inline-errors: false
details: false
method: []
loglevel: warning
path: []
blueprint: docs/openapi.json
endpoint: http://localhost:5000
EOF
Ausführen:
npx dredd
Vorteile:
- ✅ Validiert Responses gegen OpenAPI-Schema
- ✅ Testet alle HTTP-Methoden
- ✅ Prüft Request/Response Bodies
- ✅ Unterstützt Hooks für Auth
Option 2: Postman + Newman
Setup:
-
OpenAPI importieren:
- Öffne Postman
- File → Import →
backend/docs/openapi.json
-
Collection generieren lassen
-
Tests hinzufügen (automatisch oder manuell)
-
Export als Collection
CLI-Tests:
npm install --save-dev newman
npx newman run postman_collection.json
Vorteile:
- ✅ GUI für manuelles Testen
- ✅ Automatische Test-Generierung
- ✅ CI/CD Integration
- ✅ Environment Variables
Option 3: Prism (Mock + Validate)
Installation:
npm install --save-dev @stoplight/prism-cli
Mock Server starten:
npx prism mock docs/openapi.json
# Server läuft auf http://localhost:4010
Validierung:
npx prism validate docs/openapi.json
Vorteile:
- ✅ Mock Server für Frontend-Entwicklung
- ✅ Schema-Validierung
- ✅ Contract Testing
- ✅ Keine echte API nötig
Option 4: Jest + Supertest (Unit/Integration Tests)
Installation:
npm install --save-dev jest supertest jest-openapi
Beispiel Test:
// tests/api/groups.test.js
const request = require('supertest');
const jestOpenAPI = require('jest-openapi');
const app = require('../../src/server');
// Load OpenAPI spec
jestOpenAPI(require('../../docs/openapi.json'));
describe('Groups API', () => {
it('GET /api/groups should return valid response', async () => {
const response = await request(app)
.get('/api/groups')
.expect(200);
// Validate against OpenAPI schema
expect(response).toSatisfyApiSpec();
// Custom assertions
expect(response.body).toHaveProperty('groups');
expect(Array.isArray(response.body.groups)).toBe(true);
});
it('GET /api/groups/:groupId should return 404 for invalid ID', async () => {
const response = await request(app)
.get('/api/groups/invalid-id')
.expect(404);
expect(response).toSatisfyApiSpec();
});
});
package.json:
{
"scripts": {
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage"
}
}
Vorteile:
- ✅ Vollständige Integration Tests
- ✅ Schema-Validierung mit jest-openapi
- ✅ Code Coverage
- ✅ CI/CD Integration
- ✅ Watch Mode für TDD
📊 Vergleich
| Tool | Setup | Schema Validation | Auth Support | CI/CD | Best For |
|---|---|---|---|---|---|
| test-openapi-paths.js | ✅ Fertig | ❌ | ❌ | ✅ | Quick smoke test |
| Dredd | ⚠️ Mittel | ✅ | ✅ | ✅ | Contract testing |
| Postman/Newman | ⚠️ Mittel | ✅ | ✅ | ✅ | Manual + automated |
| Prism | ✅ Easy | ✅ | ⚠️ | ✅ | Mock + validate |
| Jest + Supertest | ⚠️ Komplex | ✅ | ✅ | ✅ | Full testing suite |
🚀 Empfehlung für dieses Projekt
Phase 1: Quick Wins (Jetzt)
# 1. Behalte aktuelles Smoke-Test Script
npm run test-openapi
# 2. Installiere Prism für Validierung
npm install --save-dev @stoplight/prism-cli
# 3. Validiere OpenAPI Spec
npm run validate-openapi # (siehe unten)
Phase 2: Contract Testing (Später)
# 1. Installiere Dredd
npm install --save-dev dredd
# 2. Erstelle dredd.yml (siehe oben)
# 3. Schreibe Hooks für Auth
# tests/dredd-hooks.js
# 4. Führe aus
npm run test:contract
Phase 3: Full Testing Suite (Optional)
# Jest + Supertest + jest-openapi
npm install --save-dev jest supertest jest-openapi @types/jest
# Schreibe Integration Tests in tests/
npm run test
📝 Neue NPM Scripts
Füge zu package.json hinzu:
{
"scripts": {
"test-openapi": "node test-openapi-paths.js",
"validate-openapi": "prism validate docs/openapi.json",
"test:contract": "dredd",
"test": "jest",
"test:watch": "jest --watch"
}
}
🔗 Swagger-eigene Test-Tools
Swagger Inspector:
- Online: https://inspector.swagger.io/
- Import
openapi.json - Manuelles Testen in GUI
- Kann Test-Collections exportieren
Swagger Codegen:
# Generiert Client-Code + Tests
npx @openapitools/openapi-generator-cli generate \
-i docs/openapi.json \
-g javascript \
-o generated-client
Swagger UI "Try it out":
- Bereits aktiv unter http://localhost:5000/api/docs
- Manuelles Testing direkt in Browser
- ✅ Einfachstes Tool für Quick Tests
✅ Fazit
Aktuell: test-openapi-paths.js ist OK für Smoke Tests.
Nächster Schritt:
- Installiere Prism für Schema-Validierung
- Später: Dredd für Contract Testing
- Optional: Jest für vollständige Test-Suite
Best Practice: Kombiniere mehrere Tools:
- Prism für Schema-Validierung
- Dredd für Contract Testing
- Jest für Unit/Integration Tests
- Swagger UI für manuelles Testing