feat: add functionality to register plugins via http

Also:

- Add functionality for serving the responses from plugins
- Add tests for related methods and routes

Closes #2, #37
This commit is contained in:
Jovan Krunić
2019-07-04 17:43:36 +02:00
committed by Rainer Killinger
parent 59ea7a5ba6
commit 3d51ccfac2
12 changed files with 3035 additions and 188 deletions

2504
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -25,6 +25,7 @@
"preversion": "npm run prepublishOnly",
"push": "git push && git push origin \"v$npm_package_version\"",
"start": "NODE_CONFIG_ENV=elasticsearch ALLOW_NO_TRANSPORT=true node ./lib/cli.js",
"test": "env NODE_CONFIG_ENV=elasticsearch ALLOW_NO_TRANSPORT=true nyc mocha --require ts-node/register --ui mocha-typescript --exit 'test/**/*.ts'",
"tslint": "tslint -p tsconfig.json -c tslint.json 'src/**/*.ts'"
},
"dependencies": {
@@ -35,12 +36,14 @@
"config": "3.1.0",
"cors": "2.8.5",
"elasticsearch": "16.1.1",
"express": "4.17.1",
"express-promise-router": "3.0.3",
"express": "4.17.1",
"fs-extra": "8.0.1",
"got": "9.6.0",
"jsonschema": "1.2.4",
"moment": "2.24.0",
"morgan": "1.9.1",
"nock": "10.0.6",
"node-cache": "4.2.0",
"node-cron": "2.0.3",
"nodemailer": "6.2.1",
@@ -50,20 +53,34 @@
},
"devDependencies": {
"@openstapps/configuration": "0.21.0",
"@types/chai-as-promised": "7.1.0",
"@types/chai": "4.1.7",
"@types/config": "0.0.34",
"@types/cors": "2.8.5",
"@types/elasticsearch": "5.0.34",
"@types/express": "4.17.0",
"@types/fs-extra": "7.0.0",
"@types/got": "9.4.4",
"@types/morgan": "1.7.35",
"@types/nock": "10.0.3",
"@types/node-cache": "4.1.3",
"@types/node-cron": "2.0.2",
"@types/nodemailer": "6.2.0",
"@types/promise-queue": "2.2.0",
"@types/sinon-express-mock": "1.3.7",
"@types/supertest": "2.0.7",
"@types/uuid": "3.4.5",
"chai-as-promised": "7.1.1",
"chai": "4.2.0",
"conventional-changelog-cli": "2.0.21",
"mocha-typescript": "1.1.17",
"mocha": "6.1.4",
"nyc": "14.1.1",
"prepend-file-cli": "1.0.6",
"rimraf": "2.6.3",
"sinon-express-mock": "2.2.0",
"sinon": "7.3.2",
"supertest": "4.0.2",
"tslint": "5.18.0",
"typedoc": "0.14.2",
"typescript": "3.5.3"

View File

@@ -25,15 +25,17 @@ import * as cors from 'cors';
import * as express from 'express';
import * as morgan from 'morgan';
import {join} from 'path';
import {configFile, isTestEnvironment, mailer, validator} from './common';
import {configFile, 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';
import {bulkRouter} from './routes/bulk-route';
import {indexRouter} from './routes/index-route';
import {multiSearchRouter} from './routes/multi-search-route';
import {pluginRegisterRouter} from './routes/plugin-register-route';
import {searchRouter} from './routes/search-route';
import {thingUpdateRouter} from './routes/thing-update-route';
import {virtualPluginRoute} from './routes/virtual-plugin-route';
import {BulkStorage} from './storage/bulk-storage';
import {DatabaseConstructor} from './storage/database';
import {Elasticsearch} from './storage/elasticsearch/elasticsearch';
@@ -193,16 +195,32 @@ export async function configureApp() {
bulkRouter,
indexRouter,
multiSearchRouter,
pluginRegisterRouter,
searchRouter,
thingUpdateRouter,
);
// for plugins, as Express doesn't really want you to unregister routes (and doesn't offer any method to do so at all)
app.all('*', async (req, res, next) => {
// if the route exists then call virtual route on the plugin that registered that route
if (plugins.has(req.originalUrl)) {
try {
res.json(await virtualPluginRoute(req, plugins.get(req.originalUrl)!));
} catch (e) {
// in case of error send an error response
res.status(e.statusCode);
res.json(e);
}
} else {
// pass to the next matching route (which is 404)
next();
}
});
// add a route for a missing resource (404)
app.use((_req, res) => {
const errorResponse = new SCNotFoundErrorResponse(isTestEnvironment);
res.status(errorResponse.statusCode);
res.json(errorResponse);
});
// TODO: implement a route to register plugins
}

View File

@@ -13,7 +13,7 @@
* 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 {SCConfigFile} from '@openstapps/core';
import {SCConfigFile, SCPluginMetaData} from '@openstapps/core';
import {Validator} from '@openstapps/core-tools/lib/validate';
import * as config from 'config';
import {BackendTransport} from './notification/backend-transport';
@@ -37,3 +37,8 @@ export const validator = new Validator();
* Provides information if the backend is executed in the "test" (non-production) environment
*/
export const isTestEnvironment = process.env.NODE_ENV !== 'production';
/*
* Stores a ("key-value") list of plugins where key is route and value is plugin information
*/
export const plugins = new Map<string, SCPluginMetaData>();

View File

@@ -0,0 +1,98 @@
/*
* 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/>.
*/
import {
SCPluginAlreadyRegisteredErrorResponse,
SCPluginMetaData,
SCPluginRegisterRequest,
SCPluginRegisterResponse,
SCPluginRegisterRoute,
} from '@openstapps/core';
import {deepStrictEqual} from 'assert';
import {isTestEnvironment, plugins} from '../common';
import {createRoute} from './route';
/**
* Contains information for using the route for registering routes
*/
const pluginRegisterRouteModel = new SCPluginRegisterRoute();
/**
* Implementation of the plugin registration route (SCPluginRegisterRoute)
*/
export const pluginRegisterRouter = createRoute(
pluginRegisterRouteModel, pluginRegisterHandler);
/**
* Handles requests on route for registering plugins
*
* @param request Request received for registering or unregistering a plugin
* @param _app Express application
*/
export async function pluginRegisterHandler(request: SCPluginRegisterRequest, _app: Express.Application):
Promise<SCPluginRegisterResponse> {
switch (request.action) {
case 'add':
return addPlugin(request.plugin);
case 'remove':
return removePlugin(request.route);
}
}
/**
* Adds a plugin to the list (map) of registered plugins
*
* @param plugin Meta data of the plugin
*/
function addPlugin(plugin: SCPluginMetaData): SCPluginRegisterResponse {
// check if plugin (its route) has already been registered
if (plugins.has(plugin.route)) {
const previouslyRegistered = plugins.get(plugin.route);
try {
deepStrictEqual(previouslyRegistered, plugin);
return {success: true};
} catch (error) {
throw new SCPluginAlreadyRegisteredErrorResponse(
'Plugin already registered',
plugins.get(plugin.route)!,
isTestEnvironment,
);
}
}
// it's a new plugin so it can be added to the map of plugins
plugins.set(plugin.route, plugin);
return {success: true};
}
/**
* Removes a plugin from the list (map) of registered plugins using the provided route
*
* @param route Route of the plugin which needs to be unregistered
*/
function removePlugin(route: string): SCPluginRegisterResponse {
if (!plugins.has(route)) {
// TODO: throw error when plugin that is to be removed is not already registered (after @openstapps/core update)
// throw new SCNotFoundErrorResponse(
// isTestEnvironment,
// );
return {success: false};
}
// remove the plugin information using its route as a key
plugins.delete(route);
return {success: true};
}

View File

@@ -149,6 +149,5 @@ export function createRoute<REQUESTTYPE, RETURNTYPE>(
Logger.warn(error);
});
// return router
return router;
}

View File

@@ -0,0 +1,66 @@
/*
* 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/>.
*/
import {
SCInternalServerErrorResponse,
SCPluginMetaData,
SCValidationErrorResponse,
} from '@openstapps/core';
import {Request} from 'express';
import * as got from 'got';
import {isTestEnvironment, validator} from '../common';
/**
* Number of milliseconds after which external request will fail
*/
export const EXTERNAL_REQUEST_TIMEOUT = 5000;
/**
* Generic route function used to proxy actual requests to plugins
*
* @param req The request for a plugin resource
* @param plugin Meta data of the plugin
* @throws {SCInternalServerErrorResponse} On request/response validation or response from the plugin errors
*/
export async function virtualPluginRoute(req: Request, plugin: SCPluginMetaData): Promise<object> {
let responseBody: object;
try {
const requestValidation = validator.validate(req.body, plugin.requestSchema);
if (requestValidation.errors.length > 0) {
throw new SCValidationErrorResponse(requestValidation.errors, isTestEnvironment);
}
// send the request to the plugin (forward the body) and save the response
const pluginResponse = await got.post(
plugin.route,
{
baseUrl: plugin.address,
body: req.body,
json: true,
timeout: EXTERNAL_REQUEST_TIMEOUT,
},
);
responseBody = pluginResponse.body;
const responseValidation = validator.validate(responseBody, plugin.responseSchema);
if (responseValidation.errors.length > 0) {
throw new SCValidationErrorResponse(responseValidation.errors, isTestEnvironment);
}
} catch (e) {
// wrap exact error inside of the internal server error response
throw new SCInternalServerErrorResponse(e, isTestEnvironment);
}
return responseBody;
}

View File

@@ -174,7 +174,6 @@ export class Elasticsearch implements Database {
constructor(private readonly config: SCConfigFile, mailQueue?: MailQueue) {
if (typeof config.internal.database === 'undefined'
|| typeof config.internal.database.version === 'undefined'
|| typeof config.internal.database.version !== 'string') {
throw new Error('Database version is undefined. Check your config file');
}
@@ -182,14 +181,10 @@ export class Elasticsearch implements Database {
const options: ES.ConfigOptions = {
apiVersion: config.internal.database.version,
host: Elasticsearch.getElasticsearchUrl(),
log: 'error',
// enable verbose logging for all request to elasticsearch
log: process.env.ES_DEBUG === 'true' ? 'trace' : 'error',
};
// enable verbose logging for all request to elasticsearch
if (process.env.ES_DEBUG === 'true') {
options.log = 'trace';
}
this.client = new ES.Client(options);
this.aliasMap = {};
this.ready = false;

240
test/app.spec.ts Normal file
View File

@@ -0,0 +1,240 @@
/*
* 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/>.
*/
import * as supertest from 'supertest';
import * as chaiAsPromised from 'chai-as-promised';
import {timeout, slow} from 'mocha-typescript';
import {should, use} from 'chai';
import {configureApp, app} from '../src/app';
import {registerAddRequest, registerRemoveRequest} from './routes/plugin-register-route.spec';
import {plugins} from '../src/common';
import {SCPluginRemove} from '@openstapps/core';
import * as nock from 'nock';
import * as got from 'got';
import * as sinon from 'sinon';
should();
use(chaiAsPromised);
let appTest: supertest.SuperTest<supertest.Test>;
// configures the backend and creates supertest
const prepareTestApp = async () => {
await configureApp();
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 false 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(200, {success: false});
}
}
/**
* Tests functioning of already registered plugins
*/
@suite(timeout(10000), 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');
});
}
}

View File

@@ -0,0 +1,110 @@
/*
* 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/>.
*/
import {
SCPluginAdd,
SCPluginAlreadyRegisteredErrorResponse,
SCPluginRemove,
} from '@openstapps/core';
import {should, use} from 'chai';
import {slow, timeout} from 'mocha-typescript';
import * as chaiAsPromised from 'chai-as-promised';
import {plugins} from '../../src/common';
import {pluginRegisterHandler} from '../../src/routes/plugin-register-route';
should();
use(chaiAsPromised);
export const registerAddRequest: SCPluginAdd =
require('../../node_modules/@openstapps/core/test/resources/PluginRegisterRequest.1.json')
.instance;
export const registerRemoveRequest: SCPluginRemove = {
action: 'remove',
route: registerAddRequest.plugin.route
};
@suite(timeout(10000), slow(5000))
export class PluginRegisterRouteSpec {
after() {
// remove plugins
plugins.clear();
}
@test
async 'should register a plugin'() {
// register one plugin
const response = await pluginRegisterHandler(registerAddRequest, {});
return response.should.eql({success: true})
&& plugins.size.should.equal(1);
}
@test
async 'should allow re-registering the same plugin'() {
// register one plugin
await pluginRegisterHandler(registerAddRequest, {});
// register the same plugin again
const responseReregister = await pluginRegisterHandler(registerAddRequest, {});
return responseReregister.should.eql({success: true})
&& plugins.size.should.equal(1);
}
@test
async 'should show an error if a plugin has already been registered'() {
// 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'}};
// 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);
}
@test
async 'should remove a plugin if it exists'() {
// register one plugin
await pluginRegisterHandler(registerAddRequest, {});
plugins.size.should.equal(1);
const response = await pluginRegisterHandler(registerRemoveRequest, {});
return response.should.eql({success: true})
&& plugins.size.should.equal(0);
}
@test
async 'should return false when removing a plugin whose route doesn\'t exist'() {
// register one plugin
await pluginRegisterHandler(registerAddRequest, {});
const response = await pluginRegisterHandler({...registerRemoveRequest, route: '/not-foo'}, {});
return response.should.eql({success: false});
// TODO: use 404 response
// return pluginRegisterHandler({...registerRemoveRequest, route: '/bar'}, {})
// .should.eventually.be.rejectedWith('Resource not found')
// .and.be.an.instanceOf(SCNotFoundErrorResponse);
}
}

View File

@@ -0,0 +1,142 @@
/*
* 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/>.
*/
import {should, use, expect} from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import {slow, timeout} 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 * as nock from 'nock';
import * as got from 'got';
import * as sinon from 'sinon';
import {Request} from 'express';
import {registerAddRequest} from './plugin-register-route.spec';
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 {
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();
}
@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);
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);
}
@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')
.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')
.post('/foo')
.reply(200, {invalid_result: ['foo bar']});
const req = mockReq(request);
await this.testRejection(req, plugin, SCValidationErrorResponse);
}
@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);
}
}

View File

@@ -1,6 +1,7 @@
{
"extends": "./node_modules/@openstapps/configuration/tsconfig.json",
"exclude": [
"./config/"
"./config/",
"./test/"
]
}