mirror of
https://gitlab.com/openstapps/openstapps.git
synced 2026-01-09 10:12:47 +00:00
test: add tests for routes
This commit is contained in:
committed by
Rainer Killinger
parent
751693bebc
commit
d3955b3cdd
36
package-lock.json
generated
36
package-lock.json
generated
@@ -1535,6 +1535,12 @@
|
||||
"resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz",
|
||||
"integrity": "sha1-V00xLt2Iu13YkS6Sht1sCu1KrII="
|
||||
},
|
||||
"check-more-types": {
|
||||
"version": "2.24.0",
|
||||
"resolved": "https://registry.npmjs.org/check-more-types/-/check-more-types-2.24.0.tgz",
|
||||
"integrity": "sha1-FCD/sQ/URNz8ebQ4kbv//TKoRgA=",
|
||||
"dev": true
|
||||
},
|
||||
"clean-stack": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz",
|
||||
@@ -2794,6 +2800,12 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"get-port": {
|
||||
"version": "5.1.1",
|
||||
"resolved": "https://registry.npmjs.org/get-port/-/get-port-5.1.1.tgz",
|
||||
"integrity": "sha512-g/Q1aTSDOxFpchXC4i8ZWvxA1lnPqx/JHqcpIw0/LX9T8x/GBbi6YnlN5nhaKIFkT8oFsscUKgDJYxfwfS6QsQ==",
|
||||
"dev": true
|
||||
},
|
||||
"get-stdin": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-4.0.1.tgz",
|
||||
@@ -3537,6 +3549,12 @@
|
||||
"json-buffer": "3.0.0"
|
||||
}
|
||||
},
|
||||
"lazy-ass": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/lazy-ass/-/lazy-ass-1.6.0.tgz",
|
||||
"integrity": "sha1-eZllXoZGwX8In90YfRUNMyTVRRM=",
|
||||
"dev": true
|
||||
},
|
||||
"lcid": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/lcid/-/lcid-2.0.0.tgz",
|
||||
@@ -4228,6 +4246,18 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"mocked-env": {
|
||||
"version": "1.3.2",
|
||||
"resolved": "https://registry.npmjs.org/mocked-env/-/mocked-env-1.3.2.tgz",
|
||||
"integrity": "sha512-jwm3ziowCjpbLNhUNYwn2G0tawV/ZGRuWeEGt6PItrkQT74Nk3pDldL2pmwm9sQZw6a/x+ZBGeBVYq54acTauQ==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"check-more-types": "2.24.0",
|
||||
"debug": "4.1.1",
|
||||
"lazy-ass": "1.6.0",
|
||||
"ramda": "0.26.1"
|
||||
}
|
||||
},
|
||||
"modify-values": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/modify-values/-/modify-values-1.0.1.tgz",
|
||||
@@ -4945,6 +4975,12 @@
|
||||
"integrity": "sha512-ARhCpm70fzdcvNQfPoy49IaanKkTlRWF2JMzqhcJbhSFRZv7nPTvZJdcY7301IPmvW+/p0RgIWnQDLJxifsQ7g==",
|
||||
"dev": true
|
||||
},
|
||||
"ramda": {
|
||||
"version": "0.26.1",
|
||||
"resolved": "https://registry.npmjs.org/ramda/-/ramda-0.26.1.tgz",
|
||||
"integrity": "sha512-hLWjpy7EnsDBb0p+Z3B7rPi3GDeRG5ZtiI33kJhTt+ORCd38AbAIjB/9zRIUoeTbE/AVX5ZkU7m6bznsvrf8eQ==",
|
||||
"dev": true
|
||||
},
|
||||
"range-parser": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
|
||||
|
||||
27
package.json
27
package.json
@@ -77,8 +77,10 @@
|
||||
"chai": "4.2.0",
|
||||
"chai-as-promised": "7.1.1",
|
||||
"conventional-changelog-cli": "2.0.21",
|
||||
"get-port": "5.1.1",
|
||||
"mocha": "6.1.4",
|
||||
"mocha-typescript": "1.1.17",
|
||||
"mocked-env": "1.3.2",
|
||||
"nyc": "14.1.1",
|
||||
"prepend-file-cli": "1.0.6",
|
||||
"rimraf": "2.6.3",
|
||||
@@ -88,5 +90,30 @@
|
||||
"tslint": "6.1.3",
|
||||
"typedoc": "0.18.0",
|
||||
"typescript": "3.8.3"
|
||||
},
|
||||
"nyc": {
|
||||
"all": true,
|
||||
"branches": 95,
|
||||
"check-coverage": true,
|
||||
"exclude": [
|
||||
"src/cli.ts"
|
||||
],
|
||||
"extension": [
|
||||
".ts"
|
||||
],
|
||||
"functions": 95,
|
||||
"include": [
|
||||
"src"
|
||||
],
|
||||
"lines": 95,
|
||||
"per-file": true,
|
||||
"reporter": [
|
||||
"html",
|
||||
"text-summary"
|
||||
],
|
||||
"require": [
|
||||
"ts-node/register"
|
||||
],
|
||||
"statements": 95
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ import cors from 'cors';
|
||||
import {Express} from 'express';
|
||||
import morgan from 'morgan';
|
||||
import {join} from 'path';
|
||||
import {configFile, isTestEnvironment, mailer, plugins, validator} from './common';
|
||||
import {configFile, DEFAULT_TIMEOUT, isTestEnvironment, mailer, plugins, validator} from './common';
|
||||
import {MailQueue} from './notification/mail-queue';
|
||||
import {bulkAddRouter} from './routes/bulk-add-route';
|
||||
import {bulkDoneRouter} from './routes/bulk-done-route';
|
||||
@@ -53,8 +53,7 @@ export async function configureApp(app: Express) {
|
||||
integrationTestTimeout = setTimeout(() => {
|
||||
process.exit(1);
|
||||
},
|
||||
// tslint:disable-next-line:no-magic-numbers
|
||||
20000);
|
||||
DEFAULT_TIMEOUT);
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -95,6 +94,7 @@ export async function configureApp(app: Express) {
|
||||
// only accept json as content type for all requests
|
||||
app.use((req, res, next) => {
|
||||
// get the content type
|
||||
// TODO: Always lowercase (see type definition of IncomingHttpHeaders)
|
||||
let contentType = '';
|
||||
// the content type can be string, string[] or undefined
|
||||
if (typeof req.headers['Content-Type'] === 'string') {
|
||||
@@ -189,7 +189,7 @@ export async function configureApp(app: Express) {
|
||||
throw new Error('No implementation for configured database found. Please check your configuration.');
|
||||
}
|
||||
|
||||
Logger.ok('Validated config file sucessfully');
|
||||
Logger.ok('Validated config file successfully');
|
||||
|
||||
// treats /foo and /foo/ as two different routes
|
||||
// see http://expressjs.com/en/api.html#app.set
|
||||
|
||||
@@ -60,3 +60,8 @@ export const plugins = new Map<string, SCPluginMetaData>();
|
||||
*/
|
||||
export const coreVersion: string = JSON.parse((readFileSync(resolve('.', '.', 'package.json'), 'utf-8')).toString())
|
||||
.dependencies['@openstapps/core'];
|
||||
|
||||
/**
|
||||
* The default timeout in milliseconds
|
||||
*/
|
||||
export const DEFAULT_TIMEOUT = 20000;
|
||||
|
||||
@@ -31,6 +31,7 @@ export const bulkAddRouter = createRoute<SCBulkAddRequest, SCBulkAddResponse>(
|
||||
bulkRouteModel,
|
||||
async (request, app, params) => {
|
||||
|
||||
// TODO: DELETE as not used
|
||||
if (typeof params === 'undefined' || typeof params.UID !== 'string') {
|
||||
throw new Error('UID of Bulk was not given, but route with obligatory parameter was called');
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ export const bulkDoneRouter = createRoute<SCBulkDoneRequest, SCBulkDoneResponse>
|
||||
bulkDoneRouteModel,
|
||||
async (_request, app, params) => {
|
||||
|
||||
// TODO: DELETE as not used
|
||||
if (typeof params === 'undefined' || typeof params.UID !== 'string') {
|
||||
throw new Error('UID of Bulk was not given, but route with obligatory parameter was called');
|
||||
}
|
||||
|
||||
@@ -13,33 +13,15 @@
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
// the list provides option to easily implement "isHttpMethod" guard
|
||||
const httpVerbs = ['get', 'post', 'put', 'delete', 'patch', 'options',
|
||||
'head', 'checkout', 'copy', 'lock', 'merge', 'mkactivity', 'mkcol',
|
||||
'move', 'm-search', 'notify', 'purge', 'report', 'search', 'subscribe',
|
||||
'trace', 'unlock','unsubscribe'] as const;
|
||||
/**
|
||||
* Strings that can be used as HTTP verbs (e.g. in requests)
|
||||
* Strings that can be used as HTTP verbs (e.g. in requests): 'get' | 'post' | 'put' | 'delete' etc.
|
||||
*/
|
||||
export type HTTPVerb = 'all' |
|
||||
'get' |
|
||||
'post' |
|
||||
'put' |
|
||||
'delete' |
|
||||
'patch' |
|
||||
'options' |
|
||||
'head' |
|
||||
'checkout' |
|
||||
'copy' |
|
||||
'lock' |
|
||||
'merge' |
|
||||
'mkactivity' |
|
||||
'mkcol' |
|
||||
'move' |
|
||||
'm-search' |
|
||||
'notify' |
|
||||
'purge' |
|
||||
'report' |
|
||||
'search' |
|
||||
'subscribe' |
|
||||
'trace' |
|
||||
'unlock' |
|
||||
'unsubscribe';
|
||||
export type HTTPVerb = typeof httpVerbs[number];
|
||||
|
||||
/**
|
||||
* Provides information if a text (representing a method) is an HTTP verb
|
||||
@@ -47,5 +29,5 @@ export type HTTPVerb = 'all' |
|
||||
* @param method A text (representing a method) to check
|
||||
*/
|
||||
export function isHttpMethod(method: string): method is HTTPVerb {
|
||||
return ['get', 'post', 'put'].indexOf(method) > -1;
|
||||
return (httpVerbs as unknown as string[]).indexOf(method) > -1;
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ export function createRoute<REQUESTTYPE, RETURNTYPE>(
|
||||
// the given type has no index signature so we have to cast to get the IRouteHandler when a HTTP method is given
|
||||
const route = router.route(routeClass.urlFragment);
|
||||
|
||||
// get route parameters (path parameters)
|
||||
// get route parameters (path parameters) TODO: DELETE as not used
|
||||
if (Array.isArray(routeClass.obligatoryParameters) && routeClass.obligatoryParameters.length > 0) {
|
||||
routeClass.obligatoryParameters.forEach((parameterName) => {
|
||||
router.param(parameterName, async (req, _res, next, parameterValue: string) => {
|
||||
@@ -101,7 +101,7 @@ export function createRoute<REQUESTTYPE, RETURNTYPE>(
|
||||
isTestEnvironment,
|
||||
);
|
||||
// The validation error is not caused by faulty user input, but through an error that originates somewhere in
|
||||
// the backend, therefor we use this "stacked" error.
|
||||
// the backend, therefore we use this "stacked" error.
|
||||
const internalServerError = new SCInternalServerErrorResponse(
|
||||
validationError,
|
||||
isTestEnvironment,
|
||||
|
||||
@@ -1,247 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2019 StApps
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
// tslint:disable: no-implicit-dependencies
|
||||
import {SCPluginRemove} from '@openstapps/core';
|
||||
import {Logger} from '@openstapps/logger';
|
||||
import {should, use} from 'chai';
|
||||
import chaiAsPromised from 'chai-as-promised';
|
||||
import express from 'express';
|
||||
import got from 'got';
|
||||
import {slow, suite, test, timeout} from 'mocha-typescript';
|
||||
import nock from 'nock';
|
||||
import sinon from 'sinon';
|
||||
import supertest from 'supertest';
|
||||
import {configureApp} from '../src/app';
|
||||
import {plugins} from '../src/common';
|
||||
import {registerAddRequest, registerRemoveRequest} from './routes/plugin-register-route.spec';
|
||||
|
||||
// tslint:disable: completed-docs prefer-function-over-method no-magic-numbers member-ordering
|
||||
|
||||
should();
|
||||
use(chaiAsPromised);
|
||||
let appTest: supertest.SuperTest<supertest.Test>;
|
||||
// configures the backend and creates supertest
|
||||
async function prepareTestApp() {
|
||||
const app = express();
|
||||
await configureApp(app);
|
||||
Logger.ok('App Configured');
|
||||
appTest = supertest(app);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests plugin registration routes
|
||||
*/
|
||||
@suite(timeout(10000), slow(5000))
|
||||
export class AppPluginRegisterSpec {
|
||||
static async before() {
|
||||
if (typeof appTest === 'undefined') {
|
||||
await prepareTestApp();
|
||||
}
|
||||
}
|
||||
async after() {
|
||||
// remove plugins
|
||||
plugins.clear();
|
||||
|
||||
}
|
||||
|
||||
@test
|
||||
'should respond with success when providing valid request'() {
|
||||
return appTest
|
||||
.post('/plugin/register')
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
.send(registerAddRequest)
|
||||
.expect(200, {success: true});
|
||||
}
|
||||
|
||||
@test
|
||||
async 'should respond with bad request if when providing invalid request'() {
|
||||
return appTest
|
||||
.post('/plugin/register')
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
.send({foo: 'bar'})
|
||||
.expect(400);
|
||||
}
|
||||
|
||||
@test
|
||||
async 'should respond with false if something went wrong with a valid request'() {
|
||||
// lets simulate that a plugin is already registered
|
||||
plugins.set(registerAddRequest.plugin.route, registerAddRequest.plugin);
|
||||
|
||||
// registering a different plugin for the same route causes the expected error
|
||||
const registerAddRequestAltered = {...registerAddRequest, plugin: {...registerAddRequest.plugin, name: 'FooBar Plugin'}};
|
||||
|
||||
await appTest
|
||||
.post('/plugin/register')
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
.send(registerAddRequestAltered)
|
||||
.expect(409)
|
||||
.expect((res: supertest.Response) => {
|
||||
res.body.should.have.property('name', 'SCPluginAlreadyRegisteredError');
|
||||
});
|
||||
}
|
||||
|
||||
@test
|
||||
async 'should respond with success when deregistering already registered plugin'() {
|
||||
// lets simulate that a plugin is already registered
|
||||
plugins.set(registerAddRequest.plugin.route, registerAddRequest.plugin);
|
||||
|
||||
await appTest
|
||||
.post('/plugin/register')
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
.send(registerRemoveRequest)
|
||||
.expect(200, {success: true});
|
||||
}
|
||||
|
||||
@test
|
||||
async 'should response with 404 when deleting non previously registered plugin'() {
|
||||
// lets simulate that the plugin is already registered
|
||||
plugins.set(registerAddRequest.plugin.route, registerAddRequest.plugin);
|
||||
|
||||
await appTest
|
||||
.post('/plugin/register')
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
// using a different route for the remove request
|
||||
.send({action: 'remove', route: '/not-foo'} as SCPluginRemove)
|
||||
.expect(404);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests functioning of already registered plugins
|
||||
*/
|
||||
@suite(timeout(50000), slow(5000))
|
||||
export class AppPluginSpec {
|
||||
static async before() {
|
||||
if (typeof appTest === 'undefined') {
|
||||
await prepareTestApp();
|
||||
}
|
||||
}
|
||||
|
||||
async after() {
|
||||
// remove plugins
|
||||
plugins.clear();
|
||||
// restore everything to default methods (remove stubs)
|
||||
sinon.restore();
|
||||
// clean up request mocks (fixes issue with receiving response from mock from previous test case)
|
||||
nock.cleanAll();
|
||||
}
|
||||
|
||||
@test
|
||||
async 'should properly provide the response of a registered plugin'() {
|
||||
// lets simulate that the plugin is already registered
|
||||
plugins.set(registerAddRequest.plugin.route, registerAddRequest.plugin);
|
||||
// mock responses of the plugin, depending on the body sent
|
||||
nock('http://foo.com:1234')
|
||||
.post('/foo', {query: 'foo'})
|
||||
.reply(200, {result: [{foo: 'foo'}, {bar: 'foo'}]});
|
||||
nock('http://foo.com:1234')
|
||||
.post('/foo', {query: 'bar'})
|
||||
.reply(200, {result: [{foo: 'bar'}, {bar: 'bar'}]});
|
||||
|
||||
await appTest
|
||||
.post('/foo')
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
.send({query: 'foo'})
|
||||
.expect(200, {result: [{foo: 'foo'}, {bar: 'foo'}]});
|
||||
|
||||
await appTest
|
||||
.post('/foo')
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
.send({query: 'bar'})
|
||||
.expect(200, {result: [{foo: 'bar'}, {bar: 'bar'}]});
|
||||
}
|
||||
|
||||
@test
|
||||
async 'should provide 404 if plugin/route is not registered'() {
|
||||
// lets simulate that the plugin is already registered
|
||||
plugins.set(registerAddRequest.plugin.route, registerAddRequest.plugin);
|
||||
// mock response of the plugin address
|
||||
nock('http://foo.com:1234')
|
||||
.post('/foo')
|
||||
.reply(200, {result: [{foo: 'bar'}, {bar: 'foo'}]});
|
||||
|
||||
return appTest
|
||||
.post('/not-foo')
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
.send({query: 'foo'})
|
||||
.expect(404);
|
||||
}
|
||||
|
||||
@test
|
||||
async 'should return error response if plugin address is not responding'() {
|
||||
// lets simulate that the plugin is already registered
|
||||
plugins.set(registerAddRequest.plugin.route, registerAddRequest.plugin);
|
||||
|
||||
class FooError extends Error {}
|
||||
// fake that got's post method throws an error
|
||||
sinon.stub(got, 'post')
|
||||
.callsFake(() => {
|
||||
throw new FooError();
|
||||
});
|
||||
|
||||
return appTest
|
||||
.post('/foo')
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
.send({query: 'foo'})
|
||||
.expect(502);
|
||||
}
|
||||
|
||||
@test
|
||||
async 'should return error response if request is not valid'() {
|
||||
// lets simulate that the plugin is already registered
|
||||
plugins.set(registerAddRequest.plugin.route, registerAddRequest.plugin);
|
||||
|
||||
return appTest
|
||||
.post('/foo')
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
// using number for query instead of (in request schema) required text
|
||||
.send({query: 123})
|
||||
.expect(502)
|
||||
.expect((res: supertest.Response) => {
|
||||
res.body.additionalData.should.have.property('name', 'ValidationError');
|
||||
});
|
||||
}
|
||||
|
||||
@test
|
||||
async 'should return error response if plugin response is not valid'() {
|
||||
// lets simulate that the plugin is already registered
|
||||
plugins.set(registerAddRequest.plugin.route, registerAddRequest.plugin);
|
||||
// mock response of the plugin address
|
||||
nock('http://foo.com:1234')
|
||||
.post('/foo')
|
||||
.reply(200, {not_valid_field: ['foo bar']});
|
||||
|
||||
return appTest
|
||||
.post('/foo')
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
.send({query: 'foo'})
|
||||
.expect(502)
|
||||
.expect((res: supertest.Response) => {
|
||||
res.body.additionalData.should.have.property('name', 'ValidationError');
|
||||
});
|
||||
}
|
||||
}
|
||||
108
test/app.spec.ts
Normal file
108
test/app.spec.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
* Copyright (C) 2019, 2020 StApps
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {
|
||||
SCNotFoundErrorResponse,
|
||||
SCRequestBodyTooLargeErrorResponse,
|
||||
SCSyntaxErrorResponse,
|
||||
SCUnsupportedMediaTypeErrorResponse,
|
||||
} from '@openstapps/core';
|
||||
import {expect} from 'chai';
|
||||
import {configFile, DEFAULT_TIMEOUT} from '../src/common';
|
||||
import {DEFAULT_TEST_TIMEOUT} from './common';
|
||||
import {testApp} from './tests-setup';
|
||||
import sinon from 'sinon';
|
||||
import mockedEnv from 'mocked-env';
|
||||
|
||||
describe('App', async function () {
|
||||
// increase timeout for the suite
|
||||
this.timeout(DEFAULT_TEST_TIMEOUT);
|
||||
const sandbox = sinon.createSandbox();
|
||||
|
||||
afterEach(function () {
|
||||
sandbox.restore();
|
||||
});
|
||||
|
||||
it('should exit process if there is 20 seconds of pause after a request during the integration test', async function() {
|
||||
const clock = sandbox.useFakeTimers();
|
||||
let processExitStub = sandbox.stub(process, 'exit');
|
||||
// fake NODE_ENV as integration test
|
||||
const restore = mockedEnv({
|
||||
NODE_ENV: 'integration-test',
|
||||
});
|
||||
await testApp
|
||||
.post('/');
|
||||
// fake timeout of default timeout
|
||||
clock.tick(DEFAULT_TIMEOUT);
|
||||
|
||||
expect(processExitStub.called).to.be.true;
|
||||
|
||||
// restore env variables
|
||||
restore();
|
||||
// terminate faking of the clock (setTimeout etc.)
|
||||
clock.restore();
|
||||
});
|
||||
|
||||
it('should provide request body too large error in case of a body larger than the max size', async function () {
|
||||
sandbox.stub(configFile.backend, 'maxRequestBodySize').value('3');
|
||||
|
||||
const {status} = await testApp
|
||||
.post('/')
|
||||
.set('Content-Type', 'application/json')
|
||||
.send({some: 'data larger than 1 byte'});
|
||||
|
||||
expect(status).to.equal(new SCRequestBodyTooLargeErrorResponse().statusCode);
|
||||
});
|
||||
|
||||
it('should implement CORS', async function () {
|
||||
// @ts-ignore
|
||||
const {headers} = await testApp
|
||||
.options('/');
|
||||
|
||||
expect(headers['access-control-allow-origin']).to.be.equal('*');
|
||||
});
|
||||
|
||||
it('should provide unsupported media type error in case of a non-json body', async function () {
|
||||
const responseNoType = await testApp
|
||||
.post('/non-existing-route')
|
||||
.send();
|
||||
|
||||
const responseOtherType = await testApp
|
||||
.post('/non-existing-route')
|
||||
.set('Content-Type','application/foo')
|
||||
.send();
|
||||
|
||||
expect(responseNoType.status).to.equal(new SCUnsupportedMediaTypeErrorResponse().statusCode);
|
||||
expect(responseOtherType.status).to.equal(new SCUnsupportedMediaTypeErrorResponse().statusCode);
|
||||
});
|
||||
|
||||
it('should provide syntax error if not able to parse the expected JSON body', async function () {
|
||||
const {status} = await testApp
|
||||
.post('/non-existing-route')
|
||||
.set('Content-Type', 'application/json')
|
||||
.send('this is not a JSON');
|
||||
|
||||
expect(status).to.equal(new SCSyntaxErrorResponse('Any message').statusCode);
|
||||
});
|
||||
|
||||
it('should provide route not found error for non-registered routes', async function () {
|
||||
const {status} = await testApp
|
||||
.post('/non-existing-route')
|
||||
.set('Content-Type', 'application/json')
|
||||
.send({});
|
||||
|
||||
expect(status).to.equal(new SCNotFoundErrorResponse().statusCode);
|
||||
});
|
||||
});
|
||||
31
test/common.spec.ts
Normal file
31
test/common.spec.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright (C) 2020 StApps
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {inRangeInclusive} from '../src/common';
|
||||
import {expect} from 'chai';
|
||||
|
||||
describe('Common', function () {
|
||||
describe('inRangeInclusive', function () {
|
||||
it('should provide true if the given number is in the range', function () {
|
||||
expect(inRangeInclusive(1, [1,3])).to.be.true;
|
||||
expect(inRangeInclusive(2, [1,3])).to.be.true;
|
||||
expect(inRangeInclusive(1.1, [1,3])).to.be.true;
|
||||
});
|
||||
|
||||
it('should provide false if the given number is not in the range', function () {
|
||||
expect(inRangeInclusive(3.1, [1,3])).to.be.false;
|
||||
});
|
||||
});
|
||||
});
|
||||
106
test/common.ts
Normal file
106
test/common.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
* Copyright (C) 2019, 2020 StApps
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {SCSearchQuery, SCSearchResponse, SCThings, SCUuid} from '@openstapps/core';
|
||||
import {Express} from 'express';
|
||||
import {configureApp} from '../src/app';
|
||||
import express from 'express';
|
||||
import http from 'http';
|
||||
import {Bulk, BulkStorage} from '../src/storage/bulk-storage';
|
||||
import {Database} from '../src/storage/database';
|
||||
import getPort from 'get-port';
|
||||
|
||||
/**
|
||||
* Adds routers and configures an (express) app
|
||||
*
|
||||
*/
|
||||
export async function startApp(): Promise<Express> {
|
||||
const app = express();
|
||||
|
||||
await configureApp(app);
|
||||
|
||||
const server = http.createServer(app);
|
||||
|
||||
// get a random free port
|
||||
const port = await getPort();
|
||||
server.listen(port);
|
||||
|
||||
server.on('error', err => {
|
||||
throw err;
|
||||
});
|
||||
|
||||
return new Promise(resolve => server.on('listening', () => {
|
||||
app.set(
|
||||
'bulk',
|
||||
bulkStorage,
|
||||
);
|
||||
resolve(app);
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* An elasticsearch mock
|
||||
*/
|
||||
export class ElasticsearchMock implements Database {
|
||||
// @ts-ignore
|
||||
private bulk: Bulk | undefined;
|
||||
private storageMock = new Map<string, SCThings>();
|
||||
|
||||
constructor() {
|
||||
// Nothing to do here
|
||||
}
|
||||
|
||||
bulkCreated(bulk: Bulk): Promise<void> {
|
||||
this.bulk = bulk;
|
||||
return Promise.resolve(undefined);
|
||||
}
|
||||
|
||||
bulkExpired(_bulk: Bulk): Promise<void> {
|
||||
return Promise.resolve(undefined);
|
||||
}
|
||||
|
||||
bulkUpdated(_bulk: Bulk): Promise<void> {
|
||||
return Promise.resolve(undefined);
|
||||
}
|
||||
|
||||
get(uid: SCUuid): Promise<SCThings> {
|
||||
// @ts-ignore
|
||||
return Promise.resolve(this.storageMock.get(uid));
|
||||
}
|
||||
|
||||
init(): Promise<void> {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
post(_thing: SCThings, _bulk: Bulk): Promise<void> {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
put(thing: SCThings): Promise<void> {
|
||||
this.storageMock.set(thing.uid, thing);
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
search(_params: SCSearchQuery): Promise<SCSearchResponse> {
|
||||
return Promise.resolve({data: [], facets: [], pagination: {count: 0, offset: 0, total: 0}, stats: {time: 0}});
|
||||
}
|
||||
}
|
||||
|
||||
export const bulkStorage = new BulkStorage(new ElasticsearchMock());
|
||||
|
||||
export class FooError extends Error {
|
||||
}
|
||||
|
||||
export const DEFAULT_TEST_TIMEOUT = 10000;
|
||||
128
test/routes/bulk-route.spec.ts
Normal file
128
test/routes/bulk-route.spec.ts
Normal file
@@ -0,0 +1,128 @@
|
||||
/*
|
||||
* Copyright (C) 2019, 2020 StApps
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {
|
||||
SCBulkAddRoute,
|
||||
SCBulkDoneRoute,
|
||||
SCBulkRequest,
|
||||
SCBulkRoute,
|
||||
SCNotFoundErrorResponse,
|
||||
SCThingType
|
||||
} from '@openstapps/core';
|
||||
import {Bulk} from '../../src/storage/bulk-storage';
|
||||
import {expect} from 'chai';
|
||||
import {instance as book} from '@openstapps/core/test/resources/Book.1.json';
|
||||
import moment from 'moment';
|
||||
import {DEFAULT_TEST_TIMEOUT} from '../common';
|
||||
import {testApp} from '../tests-setup';
|
||||
|
||||
describe('Bulk routes', async function () {
|
||||
// increase timeout for the suite
|
||||
this.timeout(DEFAULT_TEST_TIMEOUT);
|
||||
|
||||
const bulkObj: Bulk = {
|
||||
expiration: moment().add(3600, 'seconds')
|
||||
.format(),
|
||||
source: 'some_source',
|
||||
state: 'in progress',
|
||||
type: SCThingType.Book,
|
||||
uid: ''
|
||||
};
|
||||
const request: SCBulkRequest = {
|
||||
expiration: bulkObj.expiration,
|
||||
source: bulkObj.source,
|
||||
type: bulkObj.type,
|
||||
};
|
||||
const bulkRoute = new SCBulkRoute();
|
||||
const bulkAddRoute = new SCBulkAddRoute();
|
||||
const bulkDoneRoute = new SCBulkDoneRoute();
|
||||
|
||||
// afterEach(async function() {
|
||||
// TODO: Delete saved bulks
|
||||
// });
|
||||
|
||||
it('should create bulk', async function () {
|
||||
const {status, body, error} = await testApp
|
||||
.post(bulkRoute.urlFragment)
|
||||
.set('Content-Type', 'application/json')
|
||||
.send(request);
|
||||
|
||||
expect(status).to.be.equal(bulkRoute.statusCodeSuccess);
|
||||
expect(error).to.be.equal(false);
|
||||
expect(body.uid).to.be.a('string');
|
||||
expect(body).to.deep.equal({...bulkObj, uid: body.uid});
|
||||
});
|
||||
|
||||
it('should return (throw) error if a bulk with the provided UID cannot be found when adding to a bulk', async function () {
|
||||
await testApp
|
||||
.post(bulkRoute.urlFragment)
|
||||
.set('Content-Type', 'application/json')
|
||||
.send(request);
|
||||
const bulkAddRouteUrlFragment = bulkAddRoute.urlFragment.toLocaleLowerCase().replace(':uid', 'a-wrong-uid');
|
||||
|
||||
const {status} = await testApp
|
||||
.post(bulkAddRouteUrlFragment)
|
||||
.set('Content-Type', 'application/json')
|
||||
.send(book);
|
||||
|
||||
expect(status).to.be.equal(new SCNotFoundErrorResponse().statusCode);
|
||||
});
|
||||
|
||||
it('should add to a created bulk', async function () {
|
||||
const response = await testApp
|
||||
.post(bulkRoute.urlFragment)
|
||||
.set('Content-Type', 'application/json')
|
||||
.send(request);
|
||||
const bulkAddRouteUrlFragment = bulkAddRoute.urlFragment.toLocaleLowerCase().replace(':uid', response.body.uid);
|
||||
|
||||
const {status, body} = await testApp
|
||||
.post(bulkAddRouteUrlFragment)
|
||||
.set('Content-Type', 'application/json')
|
||||
.send(book);
|
||||
|
||||
expect(status).to.be.equal(bulkAddRoute.statusCodeSuccess);
|
||||
expect(body).to.be.deep.equal({});
|
||||
});
|
||||
|
||||
it('should return (throw) error if a bulk with the provided UID cannot be found when closing a bulk (done)', async function () {
|
||||
await testApp
|
||||
.post(bulkRoute.urlFragment)
|
||||
.set('Content-Type', 'application/json')
|
||||
.send(request);
|
||||
const bulkDoneRouteUrlFragment = bulkDoneRoute.urlFragment.toLocaleLowerCase().replace(':uid', 'a-wrong-uid');
|
||||
|
||||
const {status} = await testApp
|
||||
.post(bulkDoneRouteUrlFragment)
|
||||
.set('Content-Type', 'application/json')
|
||||
.send({});
|
||||
|
||||
expect(status).to.be.equal(new SCNotFoundErrorResponse().statusCode);
|
||||
});
|
||||
|
||||
it ('should close the bulk (done)', async function () {
|
||||
const response = await testApp
|
||||
.post(bulkRoute.urlFragment)
|
||||
.set('Content-Type', 'application/json')
|
||||
.send(request);
|
||||
const bulkDoneRouteUrlFragment = bulkDoneRoute.urlFragment.toLocaleLowerCase().replace(':uid', response.body.uid);
|
||||
|
||||
const response2 = await testApp
|
||||
.post(bulkDoneRouteUrlFragment)
|
||||
.set('Content-Type', 'application/json')
|
||||
.send({});
|
||||
|
||||
expect(response2.status).to.be.equal(bulkDoneRoute.statusCodeSuccess);
|
||||
});
|
||||
});
|
||||
37
test/routes/http-types.spec.ts
Normal file
37
test/routes/http-types.spec.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Copyright (C) 2020 StApps
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {SCRouteHttpVerbs} from '@openstapps/core';
|
||||
import {expect} from 'chai';
|
||||
import {isHttpMethod} from '../../src/routes/http-types';
|
||||
|
||||
describe('Is HTTP method', async function () {
|
||||
it('should allow valid (predefined) http methods', async function () {
|
||||
// take methods names from SCRouteHttpVerbs
|
||||
const validMethods = Object.values(SCRouteHttpVerbs).map(v => v.toLowerCase());
|
||||
|
||||
for (const method of validMethods) {
|
||||
expect(isHttpMethod(method)).to.be.true;
|
||||
}
|
||||
});
|
||||
|
||||
it('should disallow http methods that are not valid (predefined)', async function () {
|
||||
const invalidMethods = ['foo', 'bar'];
|
||||
|
||||
for (const method of invalidMethods) {
|
||||
expect(isHttpMethod(method)).to.be.false;
|
||||
}
|
||||
});
|
||||
});
|
||||
39
test/routes/index-route.spec.ts
Normal file
39
test/routes/index-route.spec.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright (C) 2019, 2020 StApps
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {DEFAULT_TEST_TIMEOUT} from '../common';
|
||||
import {testApp} from '../tests-setup';
|
||||
import {SCIndexRequest, SCIndexRoute} from '@openstapps/core';
|
||||
import {expect} from 'chai';
|
||||
|
||||
describe('Index route', async function () {
|
||||
// increase timeout for the suite
|
||||
this.timeout(DEFAULT_TEST_TIMEOUT);
|
||||
const indexRoute = new SCIndexRoute();
|
||||
|
||||
it('should respond with both app and backend configuration', async function () {
|
||||
const request: SCIndexRequest = {};
|
||||
|
||||
const response = await testApp
|
||||
.post(indexRoute.urlFragment)
|
||||
.set('Content-Type', 'application/json')
|
||||
.send(request);
|
||||
|
||||
expect(response.type).to.equal('application/json');
|
||||
expect(response.status).to.equal(indexRoute.statusCodeSuccess);
|
||||
expect(response.body).to.haveOwnProperty('app');
|
||||
expect(response.body).to.haveOwnProperty('backend');
|
||||
});
|
||||
});
|
||||
@@ -13,95 +13,183 @@
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
// tslint:disable
|
||||
import {
|
||||
SCPluginAdd,
|
||||
SCPluginAlreadyRegisteredErrorResponse,
|
||||
SCPluginRemove,
|
||||
SCNotFoundErrorResponse,
|
||||
SCPluginAdd,
|
||||
SCPluginAlreadyRegisteredErrorResponse, SCPluginRegisterResponse, SCPluginRegisterRoute,
|
||||
SCPluginRemove, SCValidationErrorResponse,
|
||||
} from '@openstapps/core';
|
||||
import {should, use} from 'chai';
|
||||
import {slow, timeout, test, suite} from 'mocha-typescript';
|
||||
import chaiAsPromised from 'chai-as-promised';
|
||||
import nock from 'nock';
|
||||
import {plugins} from '../../src/common';
|
||||
import {pluginRegisterHandler} from '../../src/routes/plugin-register-route';
|
||||
import {expect, use} from 'chai';
|
||||
import chaiAsPromised from 'chai-as-promised';
|
||||
import {instance as registerRequest} from '@openstapps/core/test/resources/PluginRegisterRequest.1.json';
|
||||
import {DEFAULT_TEST_TIMEOUT} from '../common';
|
||||
import {testApp} from '../tests-setup';
|
||||
|
||||
should();
|
||||
// for using promises in expectations (to.eventually.be...)
|
||||
use(chaiAsPromised);
|
||||
|
||||
export const registerAddRequest: SCPluginAdd =
|
||||
require('../../node_modules/@openstapps/core/test/resources/PluginRegisterRequest.1.json')
|
||||
.instance;
|
||||
// cast it because of "TS2322: Type 'string' is not assignable to type '"add"'"
|
||||
export const registerAddRequest: SCPluginAdd = registerRequest as SCPluginAdd;
|
||||
|
||||
export const registerRemoveRequest: SCPluginRemove = {
|
||||
action: 'remove',
|
||||
route: registerAddRequest.plugin.route
|
||||
};
|
||||
|
||||
@suite(timeout(10000), slow(5000))
|
||||
export class PluginRegisterRouteSpec {
|
||||
after() {
|
||||
// remove plugins
|
||||
plugins.clear();
|
||||
}
|
||||
describe('Plugin registration', async function () {
|
||||
const bodySuccess: SCPluginRegisterResponse = {success: true};
|
||||
describe('Middleware', async function () {
|
||||
after(function () {
|
||||
// remove plugins
|
||||
plugins.clear();
|
||||
});
|
||||
|
||||
@test
|
||||
async 'should register a plugin'() {
|
||||
// register one plugin
|
||||
const response = await pluginRegisterHandler(registerAddRequest, {});
|
||||
it('should register a plugin', async function () {
|
||||
// register one plugin
|
||||
const response = await pluginRegisterHandler(registerAddRequest, {});
|
||||
|
||||
return response.should.eql({success: true})
|
||||
&& plugins.size.should.equal(1);
|
||||
}
|
||||
expect(response).to.deep.equal(bodySuccess) && expect(plugins.size).to.equal(1);
|
||||
});
|
||||
|
||||
@test
|
||||
async 'should allow re-registering the same plugin'() {
|
||||
// register one plugin
|
||||
await pluginRegisterHandler(registerAddRequest, {});
|
||||
it('should allow re-registering the same plugin', async function () {
|
||||
// register one plugin
|
||||
await pluginRegisterHandler(registerAddRequest, {});
|
||||
|
||||
// register the same plugin again
|
||||
const responseReregister = await pluginRegisterHandler(registerAddRequest, {});
|
||||
// register the same plugin again
|
||||
const response = await pluginRegisterHandler(registerAddRequest, {});
|
||||
|
||||
return responseReregister.should.eql({success: true})
|
||||
&& plugins.size.should.equal(1);
|
||||
}
|
||||
return expect(response).to.deep.equal(bodySuccess)
|
||||
&& expect(plugins.size).to.equal(1);
|
||||
});
|
||||
|
||||
@test
|
||||
async 'should show an error if a plugin has already been registered'() {
|
||||
// register one plugin
|
||||
await pluginRegisterHandler(registerAddRequest, {});
|
||||
it('should show an error if a plugin has already been registered', async function () {
|
||||
// register one plugin
|
||||
await pluginRegisterHandler(registerAddRequest, {});
|
||||
|
||||
// create new request for adding a plugin with only name that changed
|
||||
let registerAddRequestAltered: SCPluginAdd = {...registerAddRequest, plugin: {...registerAddRequest.plugin, name: 'FooBar Plugin'}};
|
||||
// create new request for adding a plugin with only name that changed
|
||||
let registerAddRequestAltered: SCPluginAdd = {
|
||||
...registerAddRequest,
|
||||
plugin: {...registerAddRequest.plugin, name: registerAddRequest.plugin.name + 'foo'}
|
||||
};
|
||||
|
||||
// register the same plugin again
|
||||
return pluginRegisterHandler(registerAddRequestAltered, {})
|
||||
.should.eventually.be.rejectedWith('Plugin already registered')
|
||||
.and.be.an.instanceOf(SCPluginAlreadyRegisteredErrorResponse)
|
||||
// check that the right plugin information (of the previously registered plugin) is provided with the error
|
||||
.and.have.property('additionalData', registerAddRequest.plugin);
|
||||
}
|
||||
// register the same plugin again
|
||||
expect(pluginRegisterHandler(registerAddRequestAltered, {}))
|
||||
.to.eventually.be.rejectedWith('Plugin already registered')
|
||||
.and.be.an.instanceOf(SCPluginAlreadyRegisteredErrorResponse)
|
||||
// check that the right plugin information (of the previously registered plugin) is provided with the error
|
||||
.and.have.property('additionalData', registerAddRequest.plugin);
|
||||
});
|
||||
|
||||
@test
|
||||
async 'should remove a plugin if it exists'() {
|
||||
// register one plugin
|
||||
await pluginRegisterHandler(registerAddRequest, {});
|
||||
it('should remove plugin if it exists', async function () {
|
||||
// register one plugin
|
||||
await pluginRegisterHandler(registerAddRequest, {});
|
||||
|
||||
plugins.size.should.equal(1);
|
||||
expect(plugins.size).to.equal(1);
|
||||
|
||||
const response = await pluginRegisterHandler(registerRemoveRequest, {});
|
||||
const response = await pluginRegisterHandler(registerRemoveRequest, {});
|
||||
|
||||
return response.should.eql({success: true})
|
||||
&& plugins.size.should.equal(0);
|
||||
}
|
||||
expect(response).to.deep.equal(bodySuccess)
|
||||
&& expect(plugins.size).to.equal(0);
|
||||
});
|
||||
|
||||
@test
|
||||
async 'should throw a "not found" error when removing a plugin whose route doesn\'t exist'() {
|
||||
// register one plugin
|
||||
await pluginRegisterHandler(registerAddRequest, {});
|
||||
it('should throw a "not found" error when removing a plugin whose registered route does not exist', async function () {
|
||||
// register one plugin
|
||||
await pluginRegisterHandler(registerAddRequest, {});
|
||||
|
||||
return pluginRegisterHandler({...registerRemoveRequest, route: '/not-foo'}, {})
|
||||
.should.eventually.be.rejectedWith('Resource not found')
|
||||
.and.be.an.instanceOf(SCNotFoundErrorResponse);
|
||||
}
|
||||
}
|
||||
expect(pluginRegisterHandler({...registerRemoveRequest, route: '/not-foo'}, {}))
|
||||
.to.eventually.be.rejectedWith('Resource not found')
|
||||
.and.be.an.instanceOf(SCNotFoundErrorResponse);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Routes', async function () {
|
||||
// increase timeout for the suite
|
||||
this.timeout(DEFAULT_TEST_TIMEOUT);
|
||||
const pluginRegisterRoute = new SCPluginRegisterRoute();
|
||||
const validationError = new SCValidationErrorResponse([]);
|
||||
const notFoundError = new SCNotFoundErrorResponse();
|
||||
//@ts-ignore
|
||||
const alreadyRegisteredError = new SCPluginAlreadyRegisteredErrorResponse('Foo Message', {});
|
||||
|
||||
afterEach(async function() {
|
||||
// remove routes
|
||||
plugins.clear();
|
||||
// clean up request mocks (fixes issue with receiving response from mock from previous test case)
|
||||
nock.cleanAll();
|
||||
});
|
||||
|
||||
it('should provide "not found" (404) if plugin/route is not registered', async function () {
|
||||
// lets simulate that the plugin is already registered
|
||||
plugins.set(registerAddRequest.plugin.route, registerAddRequest.plugin);
|
||||
// mock response of the plugin address
|
||||
nock('http://foo.com:1234')
|
||||
.post('/foo')
|
||||
.reply(200, {result: [{foo: 'bar'}, {bar: 'foo'}]});
|
||||
|
||||
const {status} = await testApp
|
||||
.post('/not-foo')
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
.send({query: 'foo'});
|
||||
|
||||
expect(status).to.be.equal(notFoundError.statusCode);
|
||||
});
|
||||
|
||||
it('should respond with bad request if when providing invalid request', async function () {
|
||||
const {status} = await testApp
|
||||
.post(pluginRegisterRoute.urlFragment)
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
.send({foo: 'bar'});
|
||||
|
||||
expect(status).to.be.equal(validationError.statusCode);
|
||||
});
|
||||
|
||||
it('should respond with an error if something went wrong with a valid request', async function () {
|
||||
// lets simulate that a plugin is already registered
|
||||
plugins.set(registerAddRequest.plugin.route, registerAddRequest.plugin);
|
||||
// registering a different plugin for the same route causes the expected error
|
||||
const registerAddRequestAltered = {...registerAddRequest, plugin: {...registerAddRequest.plugin, name: 'FooBar Plugin'}};
|
||||
|
||||
const {status, body} = await testApp
|
||||
.post(pluginRegisterRoute.urlFragment)
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
.send(registerAddRequestAltered);
|
||||
|
||||
expect(status).to.be.equal(alreadyRegisteredError.statusCode);
|
||||
expect(body).to.haveOwnProperty('name', 'SCPluginAlreadyRegisteredError');
|
||||
});
|
||||
|
||||
it('should respond with success when de-registering already registered plugin', async function() {
|
||||
// lets simulate that a plugin is already registered
|
||||
plugins.set(registerAddRequest.plugin.route, registerAddRequest.plugin);
|
||||
|
||||
const {status, body} = await testApp
|
||||
.post('/plugin/register')
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
.send(registerRemoveRequest);
|
||||
|
||||
expect(status).to.be.equal(new SCPluginRegisterRoute().statusCodeSuccess);
|
||||
expect(body).to.be.deep.equal(bodySuccess);
|
||||
});
|
||||
|
||||
it('should response with 404 when deleting a plugin which was not registered', async function() {
|
||||
// lets simulate that the plugin is already registered
|
||||
plugins.set(registerAddRequest.plugin.route, registerAddRequest.plugin);
|
||||
|
||||
const {status} = await testApp
|
||||
.post('/plugin/register')
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
// using a different route for the remove request
|
||||
.send({action: 'remove', route: '/not-foo'} as SCPluginRemove);
|
||||
|
||||
expect(status).to.be.equal(notFoundError.statusCode);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
217
test/routes/route.spec.ts
Normal file
217
test/routes/route.spec.ts
Normal file
@@ -0,0 +1,217 @@
|
||||
/*
|
||||
* Copyright (C) 2020 StApps
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {
|
||||
SCInternalServerErrorResponse,
|
||||
SCMethodNotAllowedErrorResponse,
|
||||
SCRoute,
|
||||
SCRouteHttpVerbs, SCValidationErrorResponse,
|
||||
} from '@openstapps/core';
|
||||
import * as bodyParser from 'body-parser';
|
||||
import sinon from 'sinon';
|
||||
import {expect} from 'chai';
|
||||
import {Application} from 'express';
|
||||
import {validator} from '../../src/common';
|
||||
import {createRoute} from '../../src/routes/route';
|
||||
import express, {Express} from 'express';
|
||||
import supertest from 'supertest';
|
||||
import {Logger} from '@openstapps/logger';
|
||||
import {DEFAULT_TEST_TIMEOUT} from '../common';
|
||||
|
||||
interface ReturnType {
|
||||
foo: boolean;
|
||||
}
|
||||
|
||||
describe('Create route', async function () {
|
||||
let routeClass: SCRoute;
|
||||
let handler: (
|
||||
validatedBody: any,
|
||||
app: Application, params?: { [parameterName: string]: string; },
|
||||
) => Promise<ReturnType>;
|
||||
let app: Express;
|
||||
const statusCodeSuccess = 222;
|
||||
const bodySuccess = {foo: true};
|
||||
const sandbox = sinon.createSandbox();
|
||||
const validationError = new SCValidationErrorResponse([]);
|
||||
const internalServerError = new SCInternalServerErrorResponse();
|
||||
|
||||
beforeEach(function () {
|
||||
app = express();
|
||||
app.use(bodyParser.json());
|
||||
routeClass = {
|
||||
errorNames: [],
|
||||
method: SCRouteHttpVerbs.POST,
|
||||
requestBodyName: 'fooBodyName',
|
||||
responseBodyName: 'barBodyName',
|
||||
statusCodeSuccess: statusCodeSuccess,
|
||||
urlFragment: '/foo',
|
||||
};
|
||||
handler = (_request, _app) => {
|
||||
return Promise.resolve(bodySuccess);
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
sandbox.restore();
|
||||
});
|
||||
|
||||
it('should complain (throw an error) if provided method is not a valid HTTP verb', async function () {
|
||||
// put a "method" which is not a valid HTTP verb and pretend that it is defined in SCRouteHttpVerbs
|
||||
routeClass.method = 'update' as SCRouteHttpVerbs;
|
||||
expect(() => createRoute<any, any>(routeClass, handler)).to.throw(Error);
|
||||
});
|
||||
|
||||
it('should complain (throw an error) if used method is other than defined in the route creation', async function () {
|
||||
const methodNotAllowedError = new SCMethodNotAllowedErrorResponse();
|
||||
// @ts-ignore
|
||||
sandbox.stub(validator, 'validate').returns({errors: []})
|
||||
let error: any = {};
|
||||
sandbox.stub(Logger, 'warn').callsFake((err) => { error = err });
|
||||
const router = createRoute<any, any>(routeClass, handler);
|
||||
await app.use(router);
|
||||
|
||||
const response = await supertest(app)
|
||||
// use method other than defined ("get" is not the method of the route)
|
||||
.get(routeClass.urlFragment)
|
||||
.send();
|
||||
|
||||
expect(response.status).to.be.equal(methodNotAllowedError.statusCode);
|
||||
expect(error).to.be.instanceOf(SCMethodNotAllowedErrorResponse);
|
||||
});
|
||||
|
||||
it('should provide a route which returns handler response and success code', async function () {
|
||||
// @ts-ignore
|
||||
sandbox.stub(validator, 'validate').returns({errors: []});
|
||||
const router = createRoute<any, any>(routeClass, handler);
|
||||
app.use(router);
|
||||
|
||||
const response = await supertest(app)
|
||||
.post(routeClass.urlFragment)
|
||||
.send();
|
||||
|
||||
expect(response.status).to.be.equal(statusCodeSuccess);
|
||||
expect(response.body).to.be.deep.equal(bodySuccess);
|
||||
});
|
||||
|
||||
it('should complain (throw an error) if provided request is not valid', async function () {
|
||||
this.timeout(DEFAULT_TEST_TIMEOUT);
|
||||
const body = {invalid: 'request'};
|
||||
const router = createRoute<any, any>(routeClass, handler);
|
||||
app.use(router);
|
||||
const startApp = supertest(app);
|
||||
const validatorStub = sandbox.stub(validator, 'validate');
|
||||
// @ts-ignore
|
||||
validatorStub.withArgs(body, routeClass.requestBodyName).returns({errors: [new Error('Foo Error')]});
|
||||
|
||||
const response = await startApp
|
||||
.post(routeClass.urlFragment)
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
.send(body);
|
||||
|
||||
expect(response.status).to.be.equal(validationError.statusCode);
|
||||
});
|
||||
|
||||
it('should complain (throw an error) if response got through the handler is not valid', async function () {
|
||||
const router = createRoute<any, any>(routeClass, handler);
|
||||
await app.use(router);
|
||||
const startApp = supertest(app);
|
||||
// @ts-ignore
|
||||
const validatorStub = sandbox.stub(validator, 'validate').returns({errors:[]});
|
||||
// @ts-ignore
|
||||
validatorStub.withArgs(bodySuccess, routeClass.responseBodyName).returns({errors: [new Error('Foo Error')]});
|
||||
|
||||
const response = await startApp
|
||||
.post(routeClass.urlFragment)
|
||||
.send();
|
||||
|
||||
expect(response.status).to.be.equal(internalServerError.statusCode);
|
||||
});
|
||||
|
||||
it('should return internal server error if error response not allowed', async function () {
|
||||
class FooErrorResponse {
|
||||
statusCode: number;
|
||||
name: string;
|
||||
message: string;
|
||||
constructor(statusCode: number, name: string, message: string) {
|
||||
this.statusCode = statusCode;
|
||||
this.name = name;
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
class BarErrorResponse {
|
||||
statusCode: number;
|
||||
constructor(statusCode: number) {
|
||||
this.statusCode = statusCode;
|
||||
}
|
||||
}
|
||||
const routeClassWithErrorNames: SCRoute = {
|
||||
...routeClass,
|
||||
errorNames: [FooErrorResponse],
|
||||
};
|
||||
const barErrorResponse = new BarErrorResponse(599);
|
||||
|
||||
const handlerThatThrows = () => {
|
||||
throw barErrorResponse;
|
||||
};
|
||||
const router = createRoute<any, any>(routeClassWithErrorNames, handlerThatThrows);
|
||||
await app.use(router);
|
||||
const startApp = supertest(app);
|
||||
|
||||
// @ts-ignore
|
||||
sandbox.stub(validator, 'validate').returns({errors:[]});
|
||||
|
||||
const response = await startApp
|
||||
.post(routeClass.urlFragment)
|
||||
.send();
|
||||
|
||||
expect(response.status).to.be.equal(internalServerError.statusCode);
|
||||
});
|
||||
|
||||
it('should return the exact error if error response is allowed', async function () {
|
||||
class FooErrorResponse {
|
||||
statusCode: number;
|
||||
name: string;
|
||||
message: string;
|
||||
constructor(statusCode: number, name: string, message: string) {
|
||||
this.statusCode = statusCode;
|
||||
this.name = name;
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
const routeClassWithErrorNames: SCRoute = {
|
||||
...routeClass,
|
||||
errorNames: [FooErrorResponse],
|
||||
};
|
||||
|
||||
const fooErrorResponse = new FooErrorResponse(598, 'Foo Error', 'Foo Error occurred');
|
||||
|
||||
const handlerThatThrows = () => {
|
||||
throw fooErrorResponse;
|
||||
};
|
||||
const router = createRoute<any, any>(routeClassWithErrorNames, handlerThatThrows);
|
||||
await app.use(router);
|
||||
const startApp = supertest(app);
|
||||
|
||||
// @ts-ignore
|
||||
sandbox.stub(validator, 'validate').returns({errors:[]});
|
||||
|
||||
const response = await startApp
|
||||
.post(routeClass.urlFragment)
|
||||
.send();
|
||||
|
||||
expect(response.status).to.be.equal(fooErrorResponse.statusCode);
|
||||
});
|
||||
});
|
||||
123
test/routes/search-route.spec.ts
Normal file
123
test/routes/search-route.spec.ts
Normal file
@@ -0,0 +1,123 @@
|
||||
/*
|
||||
* Copyright (C) 2019, 2020 StApps
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {
|
||||
SCMethodNotAllowedErrorResponse,
|
||||
SCMultiSearchRoute,
|
||||
SCSearchRoute,
|
||||
SCSyntaxErrorResponse,
|
||||
SCTooManyRequestsErrorResponse
|
||||
} from '@openstapps/core';
|
||||
import {expect} from 'chai';
|
||||
import {configFile} from '../../src/common';
|
||||
import {DEFAULT_TEST_TIMEOUT} from '../common';
|
||||
import {testApp} from '../tests-setup';
|
||||
import sinon from 'sinon';
|
||||
|
||||
describe('Search route', async function () {
|
||||
// increase timeout for the suite
|
||||
this.timeout(DEFAULT_TEST_TIMEOUT);
|
||||
const searchRoute = new SCSearchRoute();
|
||||
const multiSearchRoute = new SCMultiSearchRoute();
|
||||
const syntaxError = new SCSyntaxErrorResponse('Foo Message');
|
||||
const methodNotAllowedError = new SCMethodNotAllowedErrorResponse();
|
||||
const tooManyRequestsError = new SCTooManyRequestsErrorResponse();
|
||||
|
||||
it('should reject GET, PUT with a valid search query', async function () {
|
||||
// const expectedParams = JSON.parse(JSON.stringify(defaultParams));
|
||||
const {status} = await testApp
|
||||
.get('/search')
|
||||
.set('Accept', 'application/json')
|
||||
.send({
|
||||
query: 'Some search terms'
|
||||
});
|
||||
|
||||
expect(status).to.equal(methodNotAllowedError.statusCode);
|
||||
});
|
||||
|
||||
describe('Basic POST /search', async function() {
|
||||
it('should accept empty JSON object', async function () {
|
||||
const {status} = await testApp
|
||||
.post(searchRoute.urlFragment)
|
||||
.set('Accept', 'application/json')
|
||||
.send({});
|
||||
|
||||
expect(status).to.equal(searchRoute.statusCodeSuccess);
|
||||
});
|
||||
|
||||
it('should accept valid search request', async function () {
|
||||
const {status} = await testApp
|
||||
.post(searchRoute.urlFragment)
|
||||
.set('Accept', 'application/json')
|
||||
.send({
|
||||
query: 'Some search terms'
|
||||
});
|
||||
|
||||
expect(status).to.equal(searchRoute.statusCodeSuccess);
|
||||
});
|
||||
|
||||
it('should respond with bad request on invalid search request (body)', async function () {
|
||||
const {status} = await testApp
|
||||
.post(searchRoute.urlFragment)
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
.send({
|
||||
some: {invalid: 'search'}
|
||||
});
|
||||
|
||||
expect(status).to.equal(syntaxError.statusCode);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Basic POST /multi/search', async function() {
|
||||
it('should respond with bad request on invalid search request (empty JSON object as body)', async function () {
|
||||
const {status} = await testApp
|
||||
.post(multiSearchRoute.urlFragment)
|
||||
.set('Accept', 'application/json')
|
||||
.send({});
|
||||
|
||||
expect(status).to.equal(multiSearchRoute.statusCodeSuccess);
|
||||
});
|
||||
|
||||
it('should accept valid search request', async function () {
|
||||
const {status} = await testApp
|
||||
.post(multiSearchRoute.urlFragment)
|
||||
.set('Accept', 'application/json')
|
||||
.send({
|
||||
one: { query: 'Some search terms for one search'},
|
||||
two: { query: 'Some search terms for another search'}
|
||||
});
|
||||
|
||||
expect(status).to.equal(multiSearchRoute.statusCodeSuccess);
|
||||
});
|
||||
|
||||
it('should respond with too many requests error if the number of sub-queries exceed their max number', async function () {
|
||||
const sandbox = sinon.createSandbox();
|
||||
sandbox.stub(configFile.backend, 'maxMultiSearchRouteQueries').value(2);
|
||||
|
||||
const {status} = await testApp
|
||||
.post(multiSearchRoute.urlFragment)
|
||||
.set('Content-Type', 'application/json')
|
||||
.send({
|
||||
one: {},
|
||||
two: {},
|
||||
three: {},
|
||||
});
|
||||
|
||||
expect(status).to.equal(tooManyRequestsError.statusCode);
|
||||
sandbox.restore();
|
||||
});
|
||||
});
|
||||
});
|
||||
43
test/routes/thing-update-route.spec.ts
Normal file
43
test/routes/thing-update-route.spec.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Copyright (C) 2020 StApps
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {SCThingUpdateRoute} from '@openstapps/core';
|
||||
import chaiAsPromised from 'chai-as-promised';
|
||||
import {bulkStorage, DEFAULT_TEST_TIMEOUT} from '../common';
|
||||
import {expect, use} from 'chai';
|
||||
import {instance as book} from '@openstapps/core/test/resources/Book.1.json';
|
||||
import {testApp} from '../tests-setup';
|
||||
|
||||
use(chaiAsPromised);
|
||||
|
||||
describe('Thing update route', async function () {
|
||||
// increase timeout for the suite
|
||||
this.timeout(DEFAULT_TEST_TIMEOUT);
|
||||
const thingUpdateRoute = new SCThingUpdateRoute();
|
||||
|
||||
it('should update a thing', async function () {
|
||||
const thingUpdateRouteUrlFragment = thingUpdateRoute.urlFragment.toLocaleLowerCase()
|
||||
.replace(':type', book.type)
|
||||
.replace(':uid', book.uid);
|
||||
|
||||
const {status} = await testApp
|
||||
.put(thingUpdateRouteUrlFragment)
|
||||
.set('Content-Type', 'application/json')
|
||||
.send(book);
|
||||
|
||||
expect(status).to.equal(thingUpdateRoute.statusCodeSuccess);
|
||||
expect(bulkStorage.database.get(book.uid)).to.eventually.be.deep.equal(book);
|
||||
});
|
||||
});
|
||||
@@ -13,131 +13,238 @@
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
// tslint:disable
|
||||
import {should, use, expect} from 'chai';
|
||||
import {
|
||||
SCInternalServerErrorResponse,
|
||||
SCPluginMetaData,
|
||||
SCValidationErrorResponse
|
||||
} from '@openstapps/core';
|
||||
import {expect, use} from 'chai';
|
||||
import chaiAsPromised from 'chai-as-promised';
|
||||
import {slow, timeout, test, suite} from 'mocha-typescript';
|
||||
import {SCPluginMetaData, SCInternalServerErrorResponse, SCValidationErrorResponse} from '@openstapps/core';
|
||||
import {virtualPluginRoute} from '../../src/routes/virtual-plugin-route';
|
||||
import {mockReq} from 'sinon-express-mock'
|
||||
import nock from 'nock';
|
||||
import got from 'got';
|
||||
import sinon from 'sinon';
|
||||
import {Request} from 'express';
|
||||
import got from 'got';
|
||||
import nock from 'nock';
|
||||
import sinon from 'sinon';
|
||||
import {mockReq} from 'sinon-express-mock';
|
||||
import {plugins, validator} from '../../src/common';
|
||||
import {virtualPluginRoute} from '../../src/routes/virtual-plugin-route';
|
||||
import {DEFAULT_TEST_TIMEOUT, FooError} from '../common';
|
||||
import {registerAddRequest} from './plugin-register-route.spec';
|
||||
import {testApp} from '../tests-setup';
|
||||
|
||||
should();
|
||||
use(chaiAsPromised);
|
||||
|
||||
const plugin = registerAddRequest.plugin;
|
||||
|
||||
@suite(timeout(10000), slow(5000))
|
||||
export class VirtualPluginRouteSpec {
|
||||
/**
|
||||
* Internal method which provides information about the specific error inside of an internal server error
|
||||
*
|
||||
* @param req Express request
|
||||
* @param plugin Plugin information (metadata)
|
||||
* @param specificError Class of a specific error
|
||||
*/
|
||||
private async testRejection(req: Request, plugin: SCPluginMetaData, specificError: object) {
|
||||
let thrownError: Error = new Error();
|
||||
try {
|
||||
describe('Virtual plugin routes', async function () {
|
||||
describe('Middleware', async function () {
|
||||
const sandbox = sinon.createSandbox();
|
||||
/**
|
||||
* Internal method which provides information about the specific error inside of an internal server error
|
||||
*
|
||||
* @param req Express request
|
||||
* @param plugin Plugin information (metadata)
|
||||
* @param specificError Class of a specific error
|
||||
*/
|
||||
async function testRejection(req: Request, plugin: SCPluginMetaData, specificError: object) {
|
||||
let thrownError: Error = new Error();
|
||||
try {
|
||||
await virtualPluginRoute(req, plugin);
|
||||
} catch (e) {
|
||||
thrownError = e;
|
||||
}
|
||||
// return virtualPluginRoute(req, plugin).should.be.rejectedWith(SCInternalServerErrorResponse); was not working for some reason
|
||||
expect(thrownError).to.be.instanceOf(SCInternalServerErrorResponse);
|
||||
expect((thrownError as SCInternalServerErrorResponse).additionalData).to.be.instanceOf(specificError);
|
||||
}
|
||||
|
||||
afterEach(function () {
|
||||
// clean up request mocks (fixes issue with receiving response from mock from previous test case)
|
||||
nock.cleanAll();
|
||||
// restore everything to default methods (remove spies and stubs)
|
||||
sandbox.restore();
|
||||
});
|
||||
|
||||
it('should forward body of the request to address and route of the plugin', async function () {
|
||||
const request = {
|
||||
body: {
|
||||
query: 'bar',
|
||||
},
|
||||
};
|
||||
// spy the post method of got
|
||||
// @ts-ignore
|
||||
const gotStub = sandbox.stub(got, 'post').returns({body: {}});
|
||||
// @ts-ignore
|
||||
sandbox.stub(validator, 'validate').returns({errors: []});
|
||||
const req = mockReq(request);
|
||||
|
||||
await virtualPluginRoute(req, plugin);
|
||||
} catch (e) {
|
||||
thrownError = e;
|
||||
}
|
||||
// return virtualPluginRoute(req, plugin).should.be.rejectedWith(SCInternalServerErrorResponse); was not working for some reason
|
||||
expect(thrownError).to.be.instanceOf(SCInternalServerErrorResponse);
|
||||
expect((thrownError as SCInternalServerErrorResponse).additionalData).to.be.instanceOf(specificError);
|
||||
}
|
||||
|
||||
after() {
|
||||
// clean up request mocks (fixes issue with receiving response from mock from previous test case)
|
||||
nock.cleanAll();
|
||||
// restore everything to default methods (remove spies and stubs)
|
||||
sinon.restore();
|
||||
}
|
||||
expect(gotStub.args[0][0]).to.equal(plugin.route);
|
||||
expect(gotStub.args[0][1].baseUrl).to.equal(plugin.address);
|
||||
expect(gotStub.args[0][1].body).to.equal(req.body);
|
||||
});
|
||||
|
||||
@test
|
||||
'should forward body of the request to address and route of the plugin'() {
|
||||
const request = {
|
||||
body: {
|
||||
query: 'bar',
|
||||
},
|
||||
};
|
||||
// spy the got's post method
|
||||
let spyGot = sinon.spy(got, 'post');
|
||||
const req = mockReq(request);
|
||||
virtualPluginRoute(req, plugin);
|
||||
it('should provide data from the plugin when its route is called', async function () {
|
||||
const request = {
|
||||
body: {
|
||||
query: 'bar',
|
||||
},
|
||||
};
|
||||
const response = {
|
||||
result: [
|
||||
{foo: 'bar'},
|
||||
{bar: 'foo'},
|
||||
]
|
||||
}
|
||||
// mock response of the plugin's address
|
||||
nock('http://foo.com:1234')
|
||||
.post('/foo')
|
||||
.reply(200, response);
|
||||
const req = mockReq(request);
|
||||
|
||||
expect(spyGot.args[0][0]).to.equal(plugin.route);
|
||||
expect(spyGot.args[0][1].baseUrl).to.equal(plugin.address);
|
||||
expect(spyGot.args[0][1].body).to.equal(req.body);
|
||||
}
|
||||
expect(await virtualPluginRoute(req, plugin)).to.eql(response);
|
||||
});
|
||||
|
||||
@test
|
||||
async 'should provide data from the plugin when its route is called'() {
|
||||
const request = {
|
||||
body: {
|
||||
query: 'bar',
|
||||
},
|
||||
};
|
||||
const response = {
|
||||
result: [
|
||||
{foo: 'bar'},
|
||||
{bar: 'foo'},
|
||||
]
|
||||
}
|
||||
// mock response of the plugin's address
|
||||
nock('http://foo.com:1234')
|
||||
it('should throw the validation error if request is not valid', async function () {
|
||||
const request = {
|
||||
body: {
|
||||
invalid_query_field: 'foo',
|
||||
},
|
||||
};
|
||||
const req = mockReq(request);
|
||||
|
||||
await testRejection(req, plugin, SCValidationErrorResponse);
|
||||
});
|
||||
|
||||
it('should throw the validation error if response is not valid', async function () {
|
||||
const request = {
|
||||
body: {
|
||||
query: 'foo',
|
||||
},
|
||||
};
|
||||
// mock response of the plugin service
|
||||
nock('http://foo.com:1234')
|
||||
.post('/foo')
|
||||
.reply(200, {invalid_result: ['foo bar']});
|
||||
const req = mockReq(request);
|
||||
|
||||
await testRejection(req, plugin, SCValidationErrorResponse);
|
||||
});
|
||||
|
||||
it('should throw error if there is a problem with reaching the address of a plugin', async function () {
|
||||
const request = {
|
||||
body: {
|
||||
query: 'foo',
|
||||
},
|
||||
};
|
||||
|
||||
// fake that post method of got throws an error
|
||||
sandbox.stub(got, 'post')
|
||||
.callsFake(() => {
|
||||
throw new FooError();
|
||||
});
|
||||
const req = mockReq(request);
|
||||
|
||||
await testRejection(req, plugin, FooError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Routes', async function () {
|
||||
// increase timeout for the suite
|
||||
this.timeout(DEFAULT_TEST_TIMEOUT);
|
||||
const sandbox = sinon.createSandbox();
|
||||
// http status code
|
||||
const OK = 200;
|
||||
const internalServerError = new SCInternalServerErrorResponse();
|
||||
|
||||
afterEach(async function() {
|
||||
// remove routes
|
||||
plugins.clear();
|
||||
// // restore everything to default methods (remove stubs)
|
||||
sandbox.restore();
|
||||
// clean up request mocks (fixes issue with receiving response from mock from previous test case)
|
||||
nock.cleanAll();
|
||||
});
|
||||
|
||||
it('should properly provide the response of a plugin', async function () {
|
||||
// lets simulate that the plugin is already registered
|
||||
plugins.set(registerAddRequest.plugin.route, registerAddRequest.plugin);
|
||||
// mock responses of the plugin, depending on the body sent
|
||||
nock('http://foo.com:1234')
|
||||
.post('/foo', {query: 'foo'})
|
||||
.reply(200, {result: [{foo: 'foo'}, {bar: 'foo'}]});
|
||||
nock('http://foo.com:1234')
|
||||
.post('/foo', {query: 'bar'})
|
||||
.reply(200, {result: [{foo: 'bar'}, {bar: 'bar'}]});
|
||||
|
||||
const fooResponse = await testApp
|
||||
.post('/foo')
|
||||
.reply(200, response);
|
||||
const req = mockReq(request);
|
||||
expect(await virtualPluginRoute(req, plugin)).to.eql(response);
|
||||
}
|
||||
|
||||
@test
|
||||
async 'should throw error if request is not valid'() {
|
||||
const request = {
|
||||
body: {
|
||||
invalid_query_field: 'foo',
|
||||
},
|
||||
};
|
||||
const req = mockReq(request);
|
||||
await this.testRejection(req, plugin, SCValidationErrorResponse);
|
||||
}
|
||||
|
||||
@test
|
||||
async 'should throw error if response is not valid'() {
|
||||
const request = {
|
||||
body: {
|
||||
query: 'foo',
|
||||
},
|
||||
};
|
||||
// mock response of the plugin service
|
||||
nock('http://foo.com:1234')
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
.send({query: 'foo'});
|
||||
const barResponse = await testApp
|
||||
.post('/foo')
|
||||
.reply(200, {invalid_result: ['foo bar']});
|
||||
const req = mockReq(request);
|
||||
await this.testRejection(req, plugin, SCValidationErrorResponse);
|
||||
}
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
.send({query: 'bar'});
|
||||
|
||||
@test
|
||||
async 'should throw error if there is a problem with reaching the address of a plugin'() {
|
||||
const request = {
|
||||
body: {
|
||||
query: 'foo',
|
||||
},
|
||||
};
|
||||
class FooError extends Error {
|
||||
};
|
||||
// fake that got's post method throws an error
|
||||
sinon.stub(got, 'post')
|
||||
.callsFake(() => {
|
||||
throw new FooError();
|
||||
});
|
||||
const req = mockReq(request);
|
||||
await this.testRejection(req, plugin, FooError);
|
||||
}
|
||||
}
|
||||
expect(fooResponse.status).to.be.equal(OK);
|
||||
expect(fooResponse.body).to.be.deep.equal({result: [{foo: 'foo'}, {bar: 'foo'}]});
|
||||
expect(barResponse.status).to.be.equal(OK);
|
||||
expect(barResponse.body).to.be.deep.equal({result: [{foo: 'bar'}, {bar: 'bar'}]});
|
||||
});
|
||||
|
||||
it('should return error response if plugin address is not responding', async function() {
|
||||
// lets simulate that the plugin is already registered
|
||||
plugins.set(registerAddRequest.plugin.route, registerAddRequest.plugin);
|
||||
|
||||
class FooError extends Error {}
|
||||
// fake that got's post method throws an error
|
||||
sandbox.stub(got, 'post')
|
||||
.callsFake(() => {
|
||||
throw new FooError();
|
||||
});
|
||||
|
||||
const {status} = await testApp
|
||||
.post('/foo')
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
.send({query: 'foo'});
|
||||
|
||||
expect(status).to.be.equal(internalServerError.statusCode);
|
||||
});
|
||||
|
||||
it('should return the validation error response if plugin request is not valid', async function() {
|
||||
// lets simulate that the plugin is already registered
|
||||
plugins.set(registerAddRequest.plugin.route, registerAddRequest.plugin);
|
||||
|
||||
const {status, body} = await testApp
|
||||
.post('/foo')
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
// using number for query instead of (in request schema) required text
|
||||
.send({query: 123})
|
||||
|
||||
expect(status).to.be.equal(502);
|
||||
expect(body.additionalData).to.haveOwnProperty('name','ValidationError');
|
||||
});
|
||||
|
||||
it('should return the validation error response if plugin response is not valid', async function() {
|
||||
// lets simulate that the plugin is already registered
|
||||
plugins.set(registerAddRequest.plugin.route, registerAddRequest.plugin);
|
||||
// mock response of the plugin address
|
||||
nock('http://foo.com:1234')
|
||||
.post('/foo')
|
||||
.reply(OK, {not_valid_field: ['foo bar']});
|
||||
|
||||
const {status, body} = await testApp
|
||||
.post('/foo')
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Accept', 'application/json')
|
||||
.send({query: 'foo'});
|
||||
|
||||
expect(status).to.be.equal(internalServerError.statusCode);
|
||||
expect(body.additionalData).to.haveOwnProperty('name','ValidationError');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
25
test/tests-setup.ts
Normal file
25
test/tests-setup.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Copyright (C) 2020 StApps
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import {DEFAULT_TIMEOUT} from '../src/common';
|
||||
import {startApp} from './common';
|
||||
import supertest from 'supertest';
|
||||
|
||||
before(async function () {
|
||||
this.timeout(DEFAULT_TIMEOUT);
|
||||
testApp = supertest(await startApp());
|
||||
});
|
||||
|
||||
export let testApp: supertest.SuperTest<supertest.Test>;
|
||||
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"extends": "./node_modules/@openstapps/configuration/tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"resolveJsonModule": true
|
||||
},
|
||||
"exclude": [
|
||||
"./config/",
|
||||
"./test/"
|
||||
|
||||
Reference in New Issue
Block a user