Project-Image-Uploader/backend/test-openapi-paths.js
matthias.lotz cdb2aa95e6 feat: Add comprehensive test suite and admin API authentication
🧪 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)
2025-11-16 18:08:48 +01:00

65 lines
2.3 KiB
JavaScript

/**
* OpenAPI Path Validator
*
* Basic smoke test to verify all OpenAPI paths are reachable.
* Does NOT replace proper API testing!
*
* For comprehensive testing, consider:
* - Dredd (npm install -g dredd) - Contract testing against OpenAPI spec
* - Postman/Newman - Import openapi.json and run automated tests
* - Prism (npm install -g @stoplight/prism-cli) - Mock server + validation
* - Jest/Supertest - Full integration tests with schema validation
*
* This script only checks if paths respond (basic reachability check).
*/
const fs = require('fs');
const path = require('path');
// Read generated openapi.json
const specPath = path.join(__dirname, 'docs', 'openapi.json');
const spec = JSON.parse(fs.readFileSync(specPath, 'utf8'));
const baseUrl = 'http://localhost:5000';
const paths = Object.keys(spec.paths || {});
console.log(`🔍 Testing ${paths.length} paths from openapi.json against ${baseUrl}\n`);
async function testPath(path, methods) {
const method = Object.keys(methods)[0]; // take first method (usually GET)
const url = `${baseUrl}${path}`;
return new Promise((resolve) => {
const http = require('http');
const req = http.request(url, { method: method.toUpperCase() }, (res) => {
const status = res.statusCode;
const statusEmoji = status === 200 ? '✅' : status === 404 ? '❌' : '⚠️';
console.log(`${statusEmoji} ${method.toUpperCase()} ${path}${status}`);
resolve({ path, status, ok: status === 200 });
});
req.on('error', (err) => {
console.log(`💥 ${method.toUpperCase()} ${path} → ERROR: ${err.message}`);
resolve({ path, status: 'ERROR', ok: false });
});
req.end();
});
}
(async () => {
const results = [];
for (const p of paths) {
const result = await testPath(p, spec.paths[p]);
results.push(result);
}
const failed = results.filter(r => !r.ok);
console.log(`\n📊 Summary: ${results.length} paths tested, ${failed.length} failed\n`);
if (failed.length > 0) {
console.log('❌ Failed paths (likely missing route prefixes):');
failed.forEach(f => console.log(` ${f.path}${f.status}`));
console.log('\n💡 Hint: Generator scanned route files without mount prefixes.');
console.log(' Check backend/src/routes/index.js for app.use() calls with prefixes like /api/admin');
}
})();