From b2c665dd458016e9cfbc5c7814392bb1b0bef474 Mon Sep 17 00:00:00 2001 From: Denis Antonenko Date: Fri, 16 Feb 2018 13:06:49 +0200 Subject: [PATCH 01/22] HTTP api transport improvement --- .../transportResolvers/HttpApiResolver.js | 19 +++++-- .../controllers/DeviceCommandAPI.http.spec.js | 49 ++++++++++++++----- .../controllers/NotificationAPI.http.spec.js | 35 +++++++++---- test/unit/controllers/TokenAPI.http.spec.js | 2 +- test/unit/controllers/UserAPI.http.spec.js | 2 +- 5 files changed, 80 insertions(+), 27 deletions(-) diff --git a/src/controllers/transportResolvers/HttpApiResolver.js b/src/controllers/transportResolvers/HttpApiResolver.js index c91e02a..b207d7b 100644 --- a/src/controllers/transportResolvers/HttpApiResolver.js +++ b/src/controllers/transportResolvers/HttpApiResolver.js @@ -13,9 +13,22 @@ class HttpApiResolver { * @param {object} parameters - URI parameters * @returns {string} */ - static buildUrl(base, parameters) { - const stringParameters = queryString.stringify(parameters); - const url = format(base, parameters); + static buildUrl(base, parameters = {}) { + // console.log(base, parameters); + const pathRegex = /[^{}]+(?=\})/g; + const pathParameterKeys = pathRegex.test(base) ? base.match(pathRegex) : []; + const pathParameters = {}; + const queryParameters = {}; + Object.keys(parameters).forEach(key => { + if (pathParameterKeys.includes(key)) { + pathParameters[key] = parameters[key]; + } else { + queryParameters[key] = parameters[key]; + } + }); + + const stringParameters = queryString.stringify(queryParameters); + const url = format(base, pathParameters); return stringParameters ? `${url}?${stringParameters}` : url; } diff --git a/test/unit/controllers/DeviceCommandAPI.http.spec.js b/test/unit/controllers/DeviceCommandAPI.http.spec.js index 5bf0ede..cabedca 100644 --- a/test/unit/controllers/DeviceCommandAPI.http.spec.js +++ b/test/unit/controllers/DeviceCommandAPI.http.spec.js @@ -79,7 +79,7 @@ describe('DeviceCommandAPI HTTP', () => { it('DeviceCommandAPI.list()', done => { - const expectedQuery = { + const source = { deviceId: 'deviceId', start: '2018-02-09T10:09:03.033Z', end: '2018-02-09T10:09:03.033Z', @@ -91,16 +91,27 @@ describe('DeviceCommandAPI HTTP', () => { skip: '1' }; + const expected = { + start: '2018-02-09T10:09:03.033Z', + end: '2018-02-09T10:09:03.033Z', + command: 'command', + status: 'status', + sortField: 'sortField', + sortOrder: 'sortOrder', + take: '1', + skip: '1' + }; + // Configurating Device List query - const commandListQuery = new DeviceHive.models.query.CommandListQuery(expectedQuery); + const commandListQuery = new DeviceHive.models.query.CommandListQuery(source); deviceHive.command.list(commandListQuery); // sent data events.once('request', data => { assert.equal(data.method, 'GET', 'Not correct method'); - assert.equal(data.url.pathname, `/device/${expectedQuery.deviceId}/command`, 'Not correct URL'); - assert.deepEqual(data.url.parameters, expectedQuery, 'Not correct query'); + assert.equal(data.url.pathname, `/device/${source.deviceId}/command`, 'Not correct URL'); + assert.deepEqual(data.url.parameters, expected, 'Not correct query'); done(); }); @@ -180,7 +191,7 @@ describe('DeviceCommandAPI HTTP', () => { it('DeviceCommandAPI.poll()', done => { - const expectedQuery = { + const source = { deviceId: 'deviceId', names: 'names', timestamp: '2018-02-09T10:09:03.033Z', @@ -189,16 +200,24 @@ describe('DeviceCommandAPI HTTP', () => { limit: '1', }; + const expected = { + names: 'names', + timestamp: '2018-02-09T10:09:03.033Z', + returnUpdatedCommands: 'returnUpdatedCommands', + waitTimeout: '10', + limit: '1', + }; + // Configurating Command List query - const commandPollQuery = new DeviceHive.models.query.CommandPollQuery(expectedQuery); + const commandPollQuery = new DeviceHive.models.query.CommandPollQuery(source); deviceHive.command.poll(commandPollQuery); // sent data events.once('request', data => { assert.equal(data.method, 'GET', 'Not correct method'); - assert.equal(data.url.pathname, `/device/${expectedQuery.deviceId}/command/poll`, 'Not correct URL'); - assert.deepEqual(data.url.parameters, expectedQuery, 'Not correct query'); + assert.equal(data.url.pathname, `/device/${source.deviceId}/command/poll`, 'Not correct URL'); + assert.deepEqual(data.url.parameters, expected, 'Not correct query'); done(); }); @@ -233,22 +252,26 @@ describe('DeviceCommandAPI HTTP', () => { it('DeviceCommandAPI.wait()', done => { - const expectedQuery = { + const source = { deviceId: '1', commandId: '1', waitTimeout: '1' }; + const expected = { + waitTimeout: '1' + }; + // Configurating Command List query - const commandWaitQuery = new DeviceHive.models.query.CommandWaitQuery(expectedQuery); + const commandWaitQuery = new DeviceHive.models.query.CommandWaitQuery(source); - deviceHive.command.wait(expectedQuery.deviceId, expectedQuery.commandId, commandWaitQuery); + deviceHive.command.wait(source.deviceId, source.commandId, commandWaitQuery); // sent data events.once('request', data => { assert.equal(data.method, 'GET', 'Not correct method'); - assert.equal(data.url.pathname, `/device/${expectedQuery.deviceId}/command/${expectedQuery.commandId}/poll`, 'Not correct URL'); - assert.deepEqual(data.url.parameters, expectedQuery, 'Not correct query'); + assert.equal(data.url.pathname, `/device/${source.deviceId}/command/${source.commandId}/poll`, 'Not correct URL'); + assert.deepEqual(data.url.parameters, expected, 'Not correct query'); done(); }); diff --git a/test/unit/controllers/NotificationAPI.http.spec.js b/test/unit/controllers/NotificationAPI.http.spec.js index fa2fd51..9332d71 100644 --- a/test/unit/controllers/NotificationAPI.http.spec.js +++ b/test/unit/controllers/NotificationAPI.http.spec.js @@ -11,7 +11,7 @@ const DeviceHive = require('../../../index'); let authService, mainService, deviceHive; -describe('NotificationAPI WS', () => { +describe('NotificationAPI HTTP', () => { before(done => { // authService @@ -79,7 +79,7 @@ describe('NotificationAPI WS', () => { it('NotificationAPI.list()', done => { - const expectedQuery = { + const source = { deviceId: 'deviceId', start: '2018-02-09T10:09:03.033Z', end: '2018-02-09T10:09:03.033Z', @@ -91,16 +91,27 @@ describe('NotificationAPI WS', () => { skip: '1' }; + const expected = { + start: '2018-02-09T10:09:03.033Z', + end: '2018-02-09T10:09:03.033Z', + notification: 'notification', + status: 'status', + sortField: 'sortField', + sortOrder: 'sortOrder', + take: '1', + skip: '1' + }; + // Configurating Notification List query - const notificationListQuery = new DeviceHive.models.query.NotificationListQuery(expectedQuery); + const notificationListQuery = new DeviceHive.models.query.NotificationListQuery(source); deviceHive.notification.list(notificationListQuery); // sent data events.once('request', data => { assert.equal(data.method, 'GET', 'Not correct method'); - assert.equal(data.url.pathname, `/device/${expectedQuery.deviceId}/notification`, 'Not correct URL'); - assert.deepEqual(data.url.parameters, expectedQuery, 'Not correct query'); + assert.equal(data.url.pathname, `/device/${source.deviceId}/notification`, 'Not correct URL'); + assert.deepEqual(data.url.parameters, expected, 'Not correct query'); done(); }); @@ -136,23 +147,29 @@ describe('NotificationAPI WS', () => { it('NotificationAPI.poll()', done => { - const expectedQuery = { + const source = { deviceId: 'deviceId', names: 'names', timestamp: '2018-02-09T10:09:03.033Z', waitTimeout: '10' }; + const expected = { + names: 'names', + timestamp: '2018-02-09T10:09:03.033Z', + waitTimeout: '10' + }; + // Configurating Notification List query - const notificationPollQuery = new DeviceHive.models.query.NotificationPollQuery(expectedQuery); + const notificationPollQuery = new DeviceHive.models.query.NotificationPollQuery(source); deviceHive.notification.poll(notificationPollQuery); // sent data events.once('request', data => { assert.equal(data.method, 'GET', 'Not correct method'); - assert.equal(data.url.pathname, `/device/${expectedQuery.deviceId}/notification/poll`, 'Not correct URL'); - assert.deepEqual(data.url.parameters, expectedQuery, 'Not correct query'); + assert.equal(data.url.pathname, `/device/${source.deviceId}/notification/poll`, 'Not correct URL'); + assert.deepEqual(data.url.parameters, expected, 'Not correct query'); done(); }); diff --git a/test/unit/controllers/TokenAPI.http.spec.js b/test/unit/controllers/TokenAPI.http.spec.js index 438f02d..aa58873 100644 --- a/test/unit/controllers/TokenAPI.http.spec.js +++ b/test/unit/controllers/TokenAPI.http.spec.js @@ -11,7 +11,7 @@ const DeviceHive = require('../../../index'); let authService, mainService, deviceHive; -describe('TokenAPI', () => { +describe('TokenAPI HTTP', () => { before(done => { // authService diff --git a/test/unit/controllers/UserAPI.http.spec.js b/test/unit/controllers/UserAPI.http.spec.js index 7c105b6..2f34cc0 100644 --- a/test/unit/controllers/UserAPI.http.spec.js +++ b/test/unit/controllers/UserAPI.http.spec.js @@ -11,7 +11,7 @@ const DeviceHive = require('../../../index'); let authService, mainService, deviceHive; -describe('UserAPI', () => { +describe('UserAPI HTTP', () => { before(done => { // authService From 5fe8de333ec374502f88843adc3313552ead0e58 Mon Sep 17 00:00:00 2001 From: Denis Antonenko Date: Wed, 21 Feb 2018 12:42:51 +0200 Subject: [PATCH 02/22] Integration tests & fixes --- package.json | 4 +- src/models/Configuration.js | 10 - src/models/Device.js | 16 +- src/models/query/PluginRegisterQuery.js | 3 +- test/integration/config.json | 16 ++ .../controllers/ConfigurationAPI.spec.js | 66 +++++ test/integration/controllers/Device.spec.js | 118 ++++++++ .../controllers/DeviceCommandAPI.spec.js | 185 ++++++++++++ .../controllers/DeviceNotificationAPI.spec.js | 135 +++++++++ .../controllers/DeviceTypeAPI.spec.js | 130 +++++++++ .../controllers/NetworkAPI.spec.js | 129 +++++++++ .../integration/controllers/PluginAPI.spec.js | 132 +++++++++ .../controllers/ServerInfoAPI.spec.js | 61 ++++ test/integration/controllers/TokenAPI.spec.js | 96 +++++++ test/integration/controllers/UserAPI.spec.js | 269 ++++++++++++++++++ .../controllers/ConfigurationAPI.http.spec.js | 3 +- test/unit/controllers/DeviceAPI.http.spec.js | 2 +- test/unit/controllers/DeviceAPI.ws.spec.js | 2 +- ....js => DeviceNotificationAPI.http.spec.js} | 0 ...ec.js => DeviceNotificationAPI.ws.spec.js} | 0 test/unit/models/Configuration.spec.js | 3 +- test/unit/models/Device.spec.js | 2 +- 22 files changed, 1354 insertions(+), 28 deletions(-) create mode 100644 test/integration/config.json create mode 100644 test/integration/controllers/ConfigurationAPI.spec.js create mode 100644 test/integration/controllers/Device.spec.js create mode 100644 test/integration/controllers/DeviceCommandAPI.spec.js create mode 100644 test/integration/controllers/DeviceNotificationAPI.spec.js create mode 100644 test/integration/controllers/DeviceTypeAPI.spec.js create mode 100644 test/integration/controllers/NetworkAPI.spec.js create mode 100644 test/integration/controllers/PluginAPI.spec.js create mode 100644 test/integration/controllers/ServerInfoAPI.spec.js create mode 100644 test/integration/controllers/TokenAPI.spec.js create mode 100644 test/integration/controllers/UserAPI.spec.js rename test/unit/controllers/{NotificationAPI.http.spec.js => DeviceNotificationAPI.http.spec.js} (100%) rename test/unit/controllers/{NotificationAPI.ws.spec.js => DeviceNotificationAPI.ws.spec.js} (100%) diff --git a/package.json b/package.json index ef7f6da..d99288b 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,9 @@ "main": "index.js", "scripts": { "build": "node build.js", - "test": "node_modules/.bin/mocha test/unit/**/**.spec.js --exit" + "test": "npm run unitTest & npm run integrationTest", + "unitTest": "node_modules/.bin/mocha test/unit/**/**.spec.js --exit", + "integrationTest": "node_modules/.bin/mocha test/integration/**/**.spec.js --timeout 10000 --exit" }, "repository": { "type": "git", diff --git a/src/models/Configuration.js b/src/models/Configuration.js index fb67d27..fd124b7 100644 --- a/src/models/Configuration.js +++ b/src/models/Configuration.js @@ -11,14 +11,12 @@ class Configuration extends BaseModel { * @param {Object} options - model options object * @param {string} options.name - Configuration parameter name. * @param {string} options.value - Configuration parameter value. - * @param {number} options.entityVersion - Specifies the version field or property of an entity class. */ constructor({ name, value, entityVersion } = {}) { super(); this.name = name; this.value = value; - this.entityVersion = entityVersion; } get name() { @@ -37,14 +35,6 @@ class Configuration extends BaseModel { this._value = value; } - get entityVersion() { - return this._entityVersion; - } - - set entityVersion(value) { - this._entityVersion = value; - } - /** * Returns instance as a plain JS object * @returns {Object} diff --git a/src/models/Device.js b/src/models/Device.js index f9eb193..0d29a94 100644 --- a/src/models/Device.js +++ b/src/models/Device.js @@ -14,9 +14,9 @@ class Device extends BaseModel { * @param {object} options.data - Device data, a JSON object with an arbitrary structure * @param {number} options.networkId - Associated network id * @param {number} options.deviceTypeId - Associated deviceType id - * @param {boolean} options.blocked - Indicates whether device is blocked + * @param {boolean} options.isBlocked - Indicates whether device is isBlocked */ - constructor({ id, name, data, networkId, deviceTypeId, blocked } = {}) { + constructor({ id, name, data, networkId, deviceTypeId, isBlocked } = {}) { super(); this.id = id; @@ -24,7 +24,7 @@ class Device extends BaseModel { this.data = data; this.networkId = networkId; this.deviceTypeId = deviceTypeId; - this.blocked = blocked; + this.isBlocked = isBlocked; } get id() { @@ -67,12 +67,12 @@ class Device extends BaseModel { this._deviceTypeId = value; } - get blocked() { - return this._blocked; + get isBlocked() { + return this._isBlocked; } - set blocked(value) { - this._blocked = value; + set isBlocked(value) { + this._isBlocked = value; } /** @@ -86,7 +86,7 @@ class Device extends BaseModel { data: this.data, networkId: this.networkId, deviceTypeId: this.deviceTypeId, - blocked: this.blocked + isBlocked: this.isBlocked }; } } diff --git a/src/models/query/PluginRegisterQuery.js b/src/models/query/PluginRegisterQuery.js index a485b62..29c5b59 100644 --- a/src/models/query/PluginRegisterQuery.js +++ b/src/models/query/PluginRegisterQuery.js @@ -17,9 +17,8 @@ class PluginRegisterQuery extends BaseModel { * @param {boolean} [options.returnUpdatedCommands] - Checks if updated commands should be returned * @param {boolean} [options.returnNotifications] - Checks if commands should be returned */ - constructor({ deviceId, networkIds, deviceTypeIds, names, returnCommands, returnUpdatedCommands, returnNotifications } = {}) { + constructor({ deviceId, networkIds, deviceTypeIds, names, returnCommands = true, returnUpdatedCommands = false, returnNotifications = false } = {}) { super(); - this.deviceId = deviceId; this.networkIds = networkIds; this.deviceTypeIds = deviceTypeIds; diff --git a/test/integration/config.json b/test/integration/config.json new file mode 100644 index 0000000..dab5212 --- /dev/null +++ b/test/integration/config.json @@ -0,0 +1,16 @@ +{ + "server": { + "http": { + "login": "dhadmin", + "password": "dhadmin_#911", + "mainServiceURL": "http://localhost:8080/dh/rest", + "authServiceURL": "http://localhost:8090/dh/rest", + "pluginServiceURL": "http://localhost:8110/dh/rest" + }, + "ws": { + "login": "dhadmin", + "password": "dhadmin_#911", + "mainServiceURL": "ws://localhost:8080/dh/websocket" + } + } +} \ No newline at end of file diff --git a/test/integration/controllers/ConfigurationAPI.spec.js b/test/integration/controllers/ConfigurationAPI.spec.js new file mode 100644 index 0000000..d4bf98a --- /dev/null +++ b/test/integration/controllers/ConfigurationAPI.spec.js @@ -0,0 +1,66 @@ +const chai = require(`chai`); +const assert = chai.assert; +const config = require('../config'); + +const EventEmitter = require('events'); +const events = new EventEmitter(); + +const DeviceHive = require('../../../index'); + +const httpDeviceHive = new DeviceHive(config.server.http); +const wsDeviceHive = new DeviceHive(config.server.ws) + + +const testConfigurations = [ + { + name: 'myTestName', + value: 'string' + }, + { + name: 'myTestName2', + value: 'string' + } +]; + +describe('ConfigurationAPI', () => { + + before(done => { + // Configaratuion DeviceHive + Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => done()); + }); + + + it('ConfigurationAPI.put()', done => { + + // Configurating Configaration model + const configuration = new DeviceHive.models.Configuration(testConfigurations[0]); + const configuration2 = new DeviceHive.models.Configuration(testConfigurations[1]); + + Promise.all([httpDeviceHive.configuration.put(configuration), wsDeviceHive.configuration.put(configuration2)]) + .then(() => done()) + .catch(done); + }); + + + it('ConfigurationAPI.get()', done => { + + Promise.all([httpDeviceHive.configuration.get(testConfigurations[0].name), wsDeviceHive.configuration.get(testConfigurations[1].name)]) + .then(dataAll => { + for (const key in dataAll) { + assert.isObject(dataAll[key]) + assert.include(dataAll[key], testConfigurations[key]); + } + }) + .then(done) + .catch(done); + }); + + + it('ConfigurationAPI.delete()', done => { + + Promise.all([httpDeviceHive.configuration.delete(testConfigurations[0].name), wsDeviceHive.configuration.delete(testConfigurations[1].name)]) + .then(() => done()) + .catch(done); + }); +}); \ No newline at end of file diff --git a/test/integration/controllers/Device.spec.js b/test/integration/controllers/Device.spec.js new file mode 100644 index 0000000..72b4512 --- /dev/null +++ b/test/integration/controllers/Device.spec.js @@ -0,0 +1,118 @@ +const chai = require(`chai`); +const assert = chai.assert; +const config = require('../config'); + +const EventEmitter = require('events'); +const events = new EventEmitter(); + +const DeviceHive = require('../../../index'); + +const httpDeviceHive = new DeviceHive(config.server.http); +const wsDeviceHive = new DeviceHive(config.server.ws) + + +const testDevices = [ + { + id: 'myTestId', + name: 'myTestName', + networkId: 1, + deviceTypeId: 1, + isBlocked: false + }, { + id: 'myTestId2', + name: 'myTestName', + networkId: 1, + deviceTypeId: 1, + isBlocked: false + } +]; + +describe('DeviceAPI', () => { + + before(done => { + // Configaratuion DeviceHive + + Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => done()); + }); + + + it('DeviceAPI.add()', done => { + + // Configurating Device model + const Device = DeviceHive.models.Device; + + const device = new Device(testDevices[0]); + const device2 = new Device(testDevices[1]); + + Promise.all([httpDeviceHive.device.add(device), wsDeviceHive.device.add(device2)]) + .then(() => done()) + .catch(done); + }); + + + it('DeviceAPI.get()', done => { + + const expected = { + deviceId: testDevices[0].id + }; + + Promise.all([httpDeviceHive.device.get(expected.deviceId), wsDeviceHive.device.get(expected.deviceId)]) + .then(dataAll => { + for (const data of dataAll) { + assert.isObject(data) + assert.include(data, testDevices[0]); + } + }) + .then(done) + .catch(done); + }); + + + it('DeviceAPI.list()', done => { + + // Configurating Device List query + const deviceListQuery = new DeviceHive.models.query.DeviceListQuery({ + networkId: 1 + }); + + + Promise.all([httpDeviceHive.device.list(deviceListQuery), wsDeviceHive.device.list(deviceListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + for (const device of data) { + assert.containsAllKeys(device, Object.keys(testDevices[0])); + } + } + }) + .then(done) + .catch(done); + + }); + + + it('DeviceAPI.count()', done => { + + // Configurating Device List query + const deviceListQuery = new DeviceHive.models.query.DeviceCountQuery({ + networkId: '1' + }); + + Promise.all([httpDeviceHive.device.count(deviceListQuery), wsDeviceHive.device.count(deviceListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + assert.property(data, 'count'); + } + }) + .then(done) + .catch(done); + }); + + + it('DeviceAPI.delete()', done => { + + Promise.all([httpDeviceHive.device.delete(testDevices[0].id), wsDeviceHive.device.delete(testDevices[1].id)]) + .then(() => done()) + .catch(done); + }); +}); \ No newline at end of file diff --git a/test/integration/controllers/DeviceCommandAPI.spec.js b/test/integration/controllers/DeviceCommandAPI.spec.js new file mode 100644 index 0000000..f139351 --- /dev/null +++ b/test/integration/controllers/DeviceCommandAPI.spec.js @@ -0,0 +1,185 @@ +const chai = require(`chai`); +const assert = chai.assert; +const config = require('../config'); + +const EventEmitter = require('events'); +const events = new EventEmitter(); + +const DeviceHive = require('../../../index'); + +const httpDeviceHive = new DeviceHive(config.server.http); +const wsDeviceHive = new DeviceHive(config.server.ws) + +const deviceId = 'e50d6085-2aba-48e9-b1c3-73c673e414be2'; + +const testDeviceCommands = [ + { + deviceId, + command: 'command', + timestamp: new Date().toISOString(), + lastUpdated: new Date().toISOString(), + userId: 1, + networkId: 1, + parameters: { + jsonString: 'jsonString' + }, + lifetime: 0, + status: 'status', + result: { + jsonString: 'jsonString' + } + }, + { + deviceId, + command: 'command2', + timestamp: new Date().toISOString(), + lastUpdated: new Date().toISOString(), + userId: 1, + networkId: 1, + parameters: { + jsonString: 'jsonString' + }, + lifetime: 0, + status: 'status', + result: { + jsonString: 'jsonString' + } + } +]; + +describe('DeviceCommandAPI', () => { + + before(done => { + // Configaratuion DeviceHive + Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => done()); + }); + + + it('DeviceCommandAPI.insert()', done => { + const command = new DeviceHive.models.Command(testDeviceCommands[0]); + const command2 = new DeviceHive.models.Command(testDeviceCommands[1]); + + Promise.all([httpDeviceHive.command.insert(deviceId, command), wsDeviceHive.command.insert(deviceId, command2)]) + .then(() => done()) + .catch(done); + }); + + + it('DeviceCommandAPI.list()', done => { + + // Configurating Device List query + const commandListQuery = new DeviceHive.models.query.CommandListQuery({ + deviceId, + command: 'command', + status: 'status', + sortField: 'id', + sortOrder: 'id', + take: 2, + skip: 0 + }); + + Promise.all([httpDeviceHive.command.list(commandListQuery), wsDeviceHive.command.list(commandListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + for (const deviceCommandKey in data) { + testDeviceCommands[deviceCommandKey].id = data[deviceCommandKey].id; + testDeviceCommands[deviceCommandKey].timestamp = data[deviceCommandKey].timestamp; + testDeviceCommands[deviceCommandKey].lastUpdated = data[deviceCommandKey].lastUpdated; + assert.containsAllKeys(data[deviceCommandKey], Object.keys(testDeviceCommands[0])); + } + } + }) + .then(done) + .catch(done); + }); + + + it('DeviceCommand API.get()', done => { + + + Promise.all([httpDeviceHive.command.get(deviceId, testDeviceCommands[0].id), wsDeviceHive.command.get(deviceId, testDeviceCommands[0].id)]) + .then(dataAll => { + const expected = testDeviceCommands[0]; + for (const data of dataAll) { + assert.isObject(data); + assert.deepInclude(data, expected); + } + }) + .then(done) + .catch(done); + }); + + + it('DeviceCommandAPI.update()', done => { + + const command = new DeviceHive.models.Command(testDeviceCommands[0], testDeviceCommands[0]); + const command2 = new DeviceHive.models.Command(testDeviceCommands[0], testDeviceCommands[1]); + + Promise.all([httpDeviceHive.command.update(command), wsDeviceHive.command.update(command2)]) + .then(() => done()) + .catch(done); + }); + + + it('DeviceCommandAPI.poll()', done => { + + // Configurating Command List query + const commandPollQuery = new DeviceHive.models.query.CommandPollQuery({ + deviceId, + returnUpdatedCommands: true, + limit: 1, + waitTimeout: 1 + }); + + httpDeviceHive.command.poll(commandPollQuery) + .then(() => done()) + .catch(done); + + // emit command + setTimeout(() => { + const command = new DeviceHive.models.Command(testDeviceCommands[0]); + httpDeviceHive.command.insert(deviceId, command); + }, 50); + }); + + + it('DeviceCommandAPI.pollMany()', done => { + + const commandPollManyQuery = new DeviceHive.models.query.CommandPollManyQuery({ + deviceIds: deviceId + }); + + httpDeviceHive.command.pollMany(commandPollManyQuery) + .then(() => done()) + .catch(done); + + // emit command + setTimeout(() => { + const command = new DeviceHive.models.Command(testDeviceCommands[0]); + httpDeviceHive.command.insert(deviceId, command); + }, 50); + }); + + + it('DeviceCommandAPI.wait()', done => { + + // TODO + done(); + + // Configurating Command List query + // const commandWaitQuery = new DeviceHive.models.query.CommandWaitQuery({ + // deviceId, + // commandId: testDeviceCommands[0].id, + // waitTimeout: 1 + // }); + + // httpDeviceHive.command.wait(commandWaitQuery.deviceId, commandWaitQuery.commandId, commandWaitQuery) + // .then(() => done()) + // .catch(done); + + // // emit command + // const command = new DeviceHive.models.Command(testDeviceCommands[0]); + // httpDeviceHive.command.insert(deviceId, command); + }); +}); \ No newline at end of file diff --git a/test/integration/controllers/DeviceNotificationAPI.spec.js b/test/integration/controllers/DeviceNotificationAPI.spec.js new file mode 100644 index 0000000..fb97e36 --- /dev/null +++ b/test/integration/controllers/DeviceNotificationAPI.spec.js @@ -0,0 +1,135 @@ +const chai = require(`chai`); +const assert = chai.assert; +const config = require('../config'); + +const EventEmitter = require('events'); +const events = new EventEmitter(); + +const DeviceHive = require('../../../index'); + +const httpDeviceHive = new DeviceHive(config.server.http); +const wsDeviceHive = new DeviceHive(config.server.ws) + +const deviceId = 'e50d6085-2aba-48e9-b1c3-73c673e414be2'; + +const testDeviceNotifications = [ + { + deviceId, + notification: 'notification', + timestamp: new Date().toISOString(), + parameters: { + jsonString: 'jsonString' + } + }, + { + deviceId, + notification: 'notification', + timestamp: new Date().toISOString(), + parameters: { + jsonString: 'jsonString' + } + }, +]; + +describe('NotificationAPI', () => { + + before(done => { + // Configaratuion DeviceHive + Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => done()); + }); + + + it('NotificationAPI.insert()', done => { + + const notification = new DeviceHive.models.Notification(testDeviceNotifications[0]); + const notification2 = new DeviceHive.models.Notification(testDeviceNotifications[1]); + + Promise.all([httpDeviceHive.notification.insert(deviceId, notification), wsDeviceHive.notification.insert(deviceId, notification2)]) + .then(() => done()) + .catch(done); + }); + + + it('NotificationAPI.list()', done => { + + // Configurating Device List query + const notificationListQuery = new DeviceHive.models.query.NotificationListQuery({ + deviceId, + notification: 'notification', + status: 'status', + sortField: 'id', + sortOrder: 'id', + take: 2, + skip: 0 + }); + + Promise.all([httpDeviceHive.notification.list(notificationListQuery), wsDeviceHive.notification.list(notificationListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + for (const deviceNotificationKey in data) { + testDeviceNotifications[deviceNotificationKey].id = data[deviceNotificationKey].id; + testDeviceNotifications[deviceNotificationKey].timestamp = data[deviceNotificationKey].timestamp; + assert.containsAllKeys(data[deviceNotificationKey], Object.keys(testDeviceNotifications[0])); + } + } + }) + .then(done) + .catch(done); + }); + + + it('NotificationAPI.get()', done => { + + Promise.all([httpDeviceHive.notification.get(deviceId, testDeviceNotifications[0].id), wsDeviceHive.notification.get(deviceId, testDeviceNotifications[0].id)]) + .then(dataAll => { + const expected = testDeviceNotifications[0]; + for (const data of dataAll) { + assert.isObject(data); + assert.deepInclude(data, expected); + } + }) + .then(done) + .catch(done); + }); + + + it('NotificationAPI.poll()', done => { + + // Configurating Notification List query + const notificationPollQuery = new DeviceHive.models.query.NotificationPollQuery({ + deviceId, + returnUpdatedNotifications: true, + limit: 1, + waitTimeout: 1 + }); + + httpDeviceHive.notification.poll(notificationPollQuery) + .then(() => done()) + .catch(done); + + // emit notification + setTimeout(() => { + const notification = new DeviceHive.models.Notification(testDeviceNotifications[0]); + httpDeviceHive.notification.insert(deviceId, notification); + }, 50); + }); + + + it('NotificationAPI.pollMany()', done => { + + const notificationPollManyQuery = new DeviceHive.models.query.NotificationPollManyQuery({ + deviceIds: deviceId + }); + + httpDeviceHive.notification.pollMany(notificationPollManyQuery) + .then(() => done()) + .catch(done); + + // emit notification + setTimeout(() => { + const notification = new DeviceHive.models.Notification(testDeviceNotifications[0]); + httpDeviceHive.notification.insert(deviceId, notification); + }, 50); + }); +}); \ No newline at end of file diff --git a/test/integration/controllers/DeviceTypeAPI.spec.js b/test/integration/controllers/DeviceTypeAPI.spec.js new file mode 100644 index 0000000..82cf932 --- /dev/null +++ b/test/integration/controllers/DeviceTypeAPI.spec.js @@ -0,0 +1,130 @@ +const chai = require(`chai`); +const assert = chai.assert; +const config = require('../config'); + +const EventEmitter = require('events'); +const events = new EventEmitter(); + +const DeviceHive = require('../../../index'); + +const httpDeviceHive = new DeviceHive(config.server.http); +const wsDeviceHive = new DeviceHive(config.server.ws) + + +const testDeviceTypes = [ + { + name: 'name', + description: 'description' + }, { + name: 'name2', + description: 'description2' + } +]; + +describe('DeviceTypeAPI', () => { + + before(done => { + // Configaratuion DeviceHive + + Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => done()); + }); + + + it('DeviceTypeAPI.insert()', done => { + + // Configurating DeviceType model + const DeviceType = DeviceHive.models.DeviceType; + + const deviceType = new DeviceType(testDeviceTypes[0]); + const deviceType2 = new DeviceType(testDeviceTypes[1]); + + Promise.all([httpDeviceHive.deviceType.insert(deviceType), wsDeviceHive.deviceType.insert(deviceType2)]) + .then(() => done()) + .catch(done); + }); + + + it('DeviceTypeAPI.list()', done => { + + + // Configurating Device List query + const deviceTypeListQuery = new DeviceHive.models.query.DeviceTypeListQuery({ + namePattern: 'name%', + sortField: 'name', + sortOrder: 'asc', + take: 2, + skip: 0 + }); + + + Promise.all([httpDeviceHive.deviceType.list(deviceTypeListQuery), wsDeviceHive.deviceType.list(deviceTypeListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + for (const deviceTypeKey in data) { + testDeviceTypes[deviceTypeKey].id = data[deviceTypeKey].id; + testDeviceTypes[deviceTypeKey].name = data[deviceTypeKey].name; + testDeviceTypes[deviceTypeKey].description = data[deviceTypeKey].description; + assert.containsAllKeys(data[deviceTypeKey], Object.keys(testDeviceTypes[0])); + } + } + }) + .then(done) + .catch(done); + }); + + + it('DeviceTypeAPI.get()', done => { + + Promise.all([httpDeviceHive.deviceType.get(testDeviceTypes[0].id), wsDeviceHive.deviceType.get(testDeviceTypes[0].id)]) + .then(dataAll => { + const expected = testDeviceTypes[0]; + for (const data of dataAll) { + assert.isObject(data); + assert.deepInclude(data, expected); + } + }) + .then(done) + .catch(done); + }); + + + it('DeviceTypeAPI.update()', done => { + + // Configurating DeviceType model + const DeviceType = DeviceHive.models.DeviceType; + + const deviceType = new DeviceType(testDeviceTypes[0]); + const deviceType2 = new DeviceType(testDeviceTypes[1]); + + Promise.all([httpDeviceHive.deviceType.update(deviceType), wsDeviceHive.deviceType.update(deviceType2)]) + .then(() => done()) + .catch(done); + + }); + + it('DeviceTypeAPI.count()', done => { + + // Configurating DeviceType List query + const deviceTypeListQuery = new DeviceHive.models.query.DeviceTypeCountQuery({ + name: 'name', + namePattern: 'namePattern' + }); + + Promise.all([httpDeviceHive.deviceType.count(deviceTypeListQuery), wsDeviceHive.deviceType.count(deviceTypeListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + assert.property(data, 'count'); + } + }) + .then(done) + .catch(done); + }); + + it('DeviceTypeAPI.delete()', done => { + + Promise.all([httpDeviceHive.deviceType.delete(testDeviceTypes[0].id), wsDeviceHive.deviceType.delete(testDeviceTypes[1].id)]) + .then(() => done()) + .catch(done); + }); +}); \ No newline at end of file diff --git a/test/integration/controllers/NetworkAPI.spec.js b/test/integration/controllers/NetworkAPI.spec.js new file mode 100644 index 0000000..12f6a6b --- /dev/null +++ b/test/integration/controllers/NetworkAPI.spec.js @@ -0,0 +1,129 @@ +const chai = require(`chai`); +const assert = chai.assert; +const config = require('../config'); + +const EventEmitter = require('events'); +const events = new EventEmitter(); + +const DeviceHive = require('../../../index'); + +const httpDeviceHive = new DeviceHive(config.server.http); +const wsDeviceHive = new DeviceHive(config.server.ws) + + +const testNetworks = [ + { + name: 'name', + description: 'description' + }, { + name: 'name2', + description: 'description2' + } +]; + +describe('NetworkAPI', () => { + + before(done => { + // Configaratuion DeviceHive + + Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => done()); + }); + + + it('NetworkAPI.insert()', done => { + + // Configurating Network model + const Network = DeviceHive.models.Network; + + const network = new Network(testNetworks[0]); + const network2 = new Network(testNetworks[1]); + + Promise.all([httpDeviceHive.network.insert(network), wsDeviceHive.network.insert(network2)]) + .then(() => done()) + .catch(done); + }); + + + it('NetworkAPI.list()', done => { + + // Configurating Device List query + const networkListQuery = new DeviceHive.models.query.NetworkListQuery({ + namePattern: 'name%', + sortField: 'name', + sortOrder: 'asc', + take: 2, + skip: 0 + }); + + + Promise.all([httpDeviceHive.network.list(networkListQuery), wsDeviceHive.network.list(networkListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + for (const networkKey in data) { + testNetworks[networkKey].id = data[networkKey].id; + testNetworks[networkKey].name = data[networkKey].name; + testNetworks[networkKey].description = data[networkKey].description; + assert.containsAllKeys(data[networkKey], Object.keys(testNetworks[0])); + } + } + }) + .then(done) + .catch(done); + }); + + + it('NetworkAPI.get()', done => { + + Promise.all([httpDeviceHive.network.get(testNetworks[0].id), wsDeviceHive.network.get(testNetworks[0].id)]) + .then(dataAll => { + const expected = testNetworks[0]; + for (const data of dataAll) { + assert.isObject(data); + assert.deepInclude(data, expected); + } + }) + .then(done) + .catch(done); + }); + + + it('NetworkAPI.update()', done => { + + // Configurating Network model + const Network = DeviceHive.models.Network; + + const network = new Network(testNetworks[0]); + const network2 = new Network(testNetworks[1]); + + Promise.all([httpDeviceHive.network.update(network), wsDeviceHive.network.update(network2)]) + .then(() => done()) + .catch(done); + + }); + + it('NetworkAPI.count()', done => { + + // Configurating Network List query + const networkListQuery = new DeviceHive.models.query.NetworkCountQuery({ + name: 'name', + namePattern: 'namePattern' + }); + + Promise.all([httpDeviceHive.network.count(networkListQuery), wsDeviceHive.network.count(networkListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + assert.property(data, 'count'); + } + }) + .then(done) + .catch(done); + }); + + it('NetworkAPI.delete()', done => { + + Promise.all([httpDeviceHive.network.delete(testNetworks[0].id), wsDeviceHive.network.delete(testNetworks[1].id)]) + .then(() => done()) + .catch(done); + }); +}); \ No newline at end of file diff --git a/test/integration/controllers/PluginAPI.spec.js b/test/integration/controllers/PluginAPI.spec.js new file mode 100644 index 0000000..fab0122 --- /dev/null +++ b/test/integration/controllers/PluginAPI.spec.js @@ -0,0 +1,132 @@ +const chai = require(`chai`); +const assert = chai.assert; +const config = require('../config'); + +const EventEmitter = require('events'); +const events = new EventEmitter(); + +const DeviceHive = require('../../../index'); + +const httpDeviceHive = new DeviceHive(config.server.http); +const wsDeviceHive = new DeviceHive(config.server.ws) + + +const testPlugins = [ + { + name: `testName${new Date().getMilliseconds()}`, + description: 'description', + parameters: { + jsonString: 'string' + } + } +]; + +describe('PluginAPI', () => { + + before(done => { + // Configaratuion DeviceHive + + Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => done()); + }); + + + it('PluginAPI.register()', done => { + const plugin = new DeviceHive.models.Plugin(testPlugins[0]); + const pluginQuery = new DeviceHive.models.query.PluginRegisterQuery({ + returnCommands: 'true', + returnUpdatedCommands: 'false', + returnNotifications: 'false' + }); + + Promise.all([httpDeviceHive.plugin.register(plugin, pluginQuery)]) + .then(dataAll => { + for (const data of dataAll) { + testPlugins[0] = Object.assign({}, testPlugins[0], data); + } + }) + .then(() => done()) + .catch(done); + }); + + it('PluginAPI.list()', done => { + + // Configurating Plugin List query + const pluginListQuery = new DeviceHive.models.query.PluginListQuery({ + take: 1, + skip: 0 + }); + + Promise.all([httpDeviceHive.plugin.list(pluginListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + assert.isArray(data); + } + }) + .then(() => done()) + .catch(done); + }); + + + // TODO + // it('PluginAPI.update()', done => { + // }); + + + it('PluginAPI.count()', done => { + + // Configurating Plugin List query + const pluginCountQuery = new DeviceHive.models.query.PluginCountQuery({ + status: '1' + }); + + Promise.all([httpDeviceHive.plugin.count(pluginCountQuery)]) + .then(dataAll => { + for (const data of dataAll) { + assert.property(data, 'count'); + } + }) + .then(() => done()) + .catch(done); + }); + + it('TokenAPI.createPluginToken()', done => { + + // Configurating Token model + const token = new DeviceHive.models.PluginToken({ + actions: [0], + expiration: '2018-02-09T10:09:03.033Z', + type: 0, + topicName: testPlugins[0].topicName + }); + + Promise.all([httpDeviceHive.token.createPluginToken(token)]) + .then(dataAll => { + for (const data of dataAll) { + const expectedKeys = ['accessToken', 'refreshToken'] + assert.containsAllKeys(data, expectedKeys); + } + }) + .then(done) + .catch(done); + }); + + it('TokenAPI.authPlugin()', done => { + Promise.all([httpDeviceHive.token.authPlugin(testPlugins[0].accessToken)]) + .then(dataAll => { + for (const data of dataAll) { + const expectedKeys = ['tpc', 'a', 'e', 't']; + assert.containsAllKeys(data, expectedKeys) + } + }) + .then(done) + .catch(done); + }); + + it('PluginAPI.delete()', done => { + + Promise.all([httpDeviceHive.plugin.delete(testPlugins[0].topicName)]) + .then(() => done()) + .catch(done); + }); +}); \ No newline at end of file diff --git a/test/integration/controllers/ServerInfoAPI.spec.js b/test/integration/controllers/ServerInfoAPI.spec.js new file mode 100644 index 0000000..4b21d60 --- /dev/null +++ b/test/integration/controllers/ServerInfoAPI.spec.js @@ -0,0 +1,61 @@ +const chai = require(`chai`); +const assert = chai.assert; +const config = require('../config'); + +const EventEmitter = require('events'); +const events = new EventEmitter(); + +const DeviceHive = require('../../../index'); + +const httpDeviceHive = new DeviceHive(config.server.http); +const wsDeviceHive = new DeviceHive(config.server.ws) + + +describe('ServerInfoAPI', () => { + + before(done => { + // Configaratuion DeviceHive + Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => done()); + }); + + + it('InfoAPI.getServerInfo()', done => { + + Promise.all([httpDeviceHive.info.getServerInfo(), wsDeviceHive.info.getServerInfo()]) + .then(dataAll => { + for (const data of dataAll) { + const expectedKeys = ['apiVersion', 'serverTimestamp'] + assert.isObject(data); + assert.containsAllKeys(data, expectedKeys); + } + }) + .then(done) + .catch(done); + }); + + it('InfoAPI.getCacheInfo()', done => { + + Promise.all([httpDeviceHive.info.getCacheInfo()]) + .then(dataAll => { + for (const data of dataAll) { + const expectedKeys = ['serverTimestamp', 'cacheStats'] + assert.isObject(data); + assert.containsAllKeys(data, expectedKeys); + } + }) + .then(done) + .catch(done); + }); + + it('InfoAPI.getClusterInfo()', done => { + Promise.all([httpDeviceHive.info.getClusterInfo(), wsDeviceHive.info.getClusterInfo()]) + .then(dataAll => { + for (const data of dataAll) { + assert.isObject(data); + } + }) + .then(done) + .catch(done); + }); +}); \ No newline at end of file diff --git a/test/integration/controllers/TokenAPI.spec.js b/test/integration/controllers/TokenAPI.spec.js new file mode 100644 index 0000000..d6e7aab --- /dev/null +++ b/test/integration/controllers/TokenAPI.spec.js @@ -0,0 +1,96 @@ +const chai = require(`chai`); +const assert = chai.assert; +const config = require('../config'); + +const EventEmitter = require('events'); +const events = new EventEmitter(); + +const DeviceHive = require('../../../index'); + +const httpDeviceHive = new DeviceHive(config.server.http); +const wsDeviceHive = new DeviceHive(config.server.ws) + + +const testToken = { + login: config.server.http.login, + password: config.server.http.password +}; + +describe('TokenAPI', () => { + + before(done => { + // Configaratuion DeviceHive + + Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => done()); + }); + + it('TokenAPI.createUserToken()', done => { + + // Configurating Token model + const token = new DeviceHive.models.UserToken({ + userId: 1, + actions: ['string'], + networkIds: ['string'], + deviceTypeIds: ['string'], + expiration: '2030-02-09T10:09:03.033Z' + }); + + Promise.all([httpDeviceHive.token.createUserToken(token), wsDeviceHive.token.createUserToken(token)]) + .then(dataAll => { + for (const data of dataAll) { + const expectedkeys = ['accessToken', 'refreshToken']; + assert.isObject(data); + assert.containsAllKeys(data, expectedkeys); + testToken.accessToken = data.accessToken; + testToken.refreshToken = data.refreshToken; + } + }) + .then(done) + .catch(done); + }); + + it('TokenAPI.refresh()', done => { + + // Configurating Token model + + Promise.all([httpDeviceHive.token.refresh(testToken.refreshToken)]) + .then(dataAll => { + for (const data of dataAll) { + const expectedkeys = ['accessToken']; + assert.isObject(data); + assert.containsAllKeys(data, expectedkeys); + testToken.accessToken = data.accessToken; + testToken.refreshToken = data.refreshToken; + } + }) + .then(done) + .catch(done); + + // sent data + events.once('request', data => { + assert.equal(data.method, 'POST', 'Not correct method'); + assert.equal(data.url.pathname, `/token/refresh`, 'Not correct URL'); + assert.deepEqual(data.body, expectedBody, 'Not correct body'); + + done(); + }); + }); + + + it('TokenAPI.login()', done => { + + Promise.all([httpDeviceHive.token.login(testToken.login, testToken.password), wsDeviceHive.token.login(testToken.login, testToken.password)]) + .then(dataAll => { + for (const data of dataAll) { + const expectedkeys = ['accessToken', 'refreshToken']; + assert.isObject(data); + assert.containsAllKeys(data, expectedkeys); + testToken.accessToken = data.accessToken; + testToken.refreshToken = data.refreshToken; + } + }) + .then(done) + .catch(done) + }); +}); \ No newline at end of file diff --git a/test/integration/controllers/UserAPI.spec.js b/test/integration/controllers/UserAPI.spec.js new file mode 100644 index 0000000..088c911 --- /dev/null +++ b/test/integration/controllers/UserAPI.spec.js @@ -0,0 +1,269 @@ +const chai = require(`chai`); +const assert = chai.assert; +const config = require('../config'); + +const EventEmitter = require('events'); +const events = new EventEmitter(); + +const DeviceHive = require('../../../index'); + +const httpDeviceHive = new DeviceHive(config.server.http); +const wsDeviceHive = new DeviceHive(config.server.ws) + + +const testUsers = [ + { + login: 'testLogin', + role: 1, + status: 1, + password: 'password', + lastLogin: '2018-02-09T10:09:03.033Z', + data: { + jsonString: 'jsonString' + }, + introReviewed: false, + allDeviceTypesAvailable: false + }, { + login: 'testLogin2', + role: 1, + status: 1, + password: 'password', + lastLogin: '2018-02-09T10:09:03.033Z', + data: { + jsonString: 'jsonString' + }, + introReviewed: false, + allDeviceTypesAvailable: false + } +]; + +describe('UserAPI', () => { + + before(done => { + // Configaratuion DeviceHive + + Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => done()); + }); + + it('UserAPI.insert()', done => { + + // Configurating User model + const User = DeviceHive.models.User; + + const user = new User(testUsers[0]); + const user2 = new User(testUsers[1]); + + Promise.all([httpDeviceHive.user.insert(user), wsDeviceHive.user.insert(user2)]) + .then(() => done()) + .catch(done); + }); + + + it('UserAPI.list()', done => { + + // Configurating User List query + const userListQuery = new DeviceHive.models.query.UserListQuery({ + loginPattern: 'testLogin%', + role: 1, + status: 1, + sortField: 'login', + sortOrder: 'asc', + take: 2, + skip: 0, + }); + + Promise.all([httpDeviceHive.user.list(userListQuery), wsDeviceHive.user.list(userListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + for (const userKey in data) { + testUsers[userKey].id = data[userKey].id; + testUsers[userKey].lastLogin = data[userKey].lastLogin; + + const expectedKeys = Object.keys(testUsers[0]); + expectedKeys.splice(expectedKeys.indexOf('password'), 1); + assert.containsAllKeys(data[userKey], expectedKeys); + } + } + }) + .then(done) + .catch(done); + }); + + it('UserAPI.get()', done => { + + Promise.all([httpDeviceHive.user.get(testUsers[0].id), wsDeviceHive.user.get(testUsers[0].id)]) + .then(dataAll => { + const expected = Object.assign({}, testUsers[0]); + delete expected.password; + for (const data of dataAll) { + assert.isObject(data); + assert.deepInclude(data, expected); + } + }) + .then(done) + .catch(done); + }); + + it('UserAPI.getCurrent()', done => { + + Promise.all([httpDeviceHive.user.getCurrent(), wsDeviceHive.user.getCurrent()]) + .then(dataAll => { + const expected = Object.assign({}, testUsers[0]); + delete expected.password; + for (const data of dataAll) { + const expectedKeys = Object.keys(testUsers[0]); + expectedKeys.splice(expectedKeys.indexOf('password'), 1); + + assert.isObject(data); + assert.containsAllKeys(data, expectedKeys); + } + }) + .then(done) + .catch(done); + }); + + + it('UserAPI.update()', done => { + + // Configurating User model + const User = DeviceHive.models.User; + + const user = new User(testUsers[0]); + const user2 = new User(testUsers[1]); + + Promise.all([httpDeviceHive.user.update(user), wsDeviceHive.user.update(user2)]) + .then(() => done()) + .catch(done); + + }); + + + it('UserAPI.updateCurrent()', done => { + + // Configurating User model + const user = new DeviceHive.models.User({ + status: 0 + }); + + Promise.all([httpDeviceHive.user.updateCurrent(user), wsDeviceHive.user.updateCurrent(user)]) + .then(() => done()) + .catch(done); + }); + + + it('UserAPI.count()', done => { + + // Configurating User List query + const userListQuery = new DeviceHive.models.query.UserCountQuery({ + login: 'login', + loginPattern: 'loginPattern', + role: '1', + status: '1', + }); + + Promise.all([httpDeviceHive.user.count(userListQuery), wsDeviceHive.user.count(userListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + assert.property(data, 'count'); + } + }) + .then(done) + .catch(done); + }); + + + it('UserAPI.getDeviceTypes()', done => { + + Promise.all([httpDeviceHive.user.getDeviceTypes(testUsers[0].id)]) + .then(() => done()) + .catch(done); + }); + + + it('UserAPI.assignAllDeviceTypes()', done => { + + Promise.all([httpDeviceHive.user.assignAllDeviceTypes(testUsers[0].id)]) + .then(() => done()) + .catch(done); + }); + + + it('UserAPI.unassignAllDeviceTypes()', done => { + + Promise.all([httpDeviceHive.user.unassignAllDeviceTypes(testUsers[0].id)]) + .then(() => done()) + .catch(done); + }); + + + it('UserAPI.assignDeviceType()', done => { + + Promise.all([httpDeviceHive.user.assignDeviceType(testUsers[0].id, 1)]) + .then(() => done()) + .catch(done); + }); + + + it('UserAPI.getDeviceType()', done => { + + Promise.all([httpDeviceHive.user.getDeviceType(testUsers[0].id, 1)]) + .then(dataAll => { + for (const data of dataAll) { + assert.isObject(data); + assert.property(data, 'deviceType'); + } + }) + .then(done) + .catch(done); + }); + + + it('UserAPI.unassignDeviceType()', done => { + + Promise.all([httpDeviceHive.user.unassignDeviceType(testUsers[0].id, 1)]) + .then(() => done()) + .catch(done); + }); + + + it('UserAPI.assignNetwork()', done => { + + httpDeviceHive.user.assignNetwork(testUsers[0].id, 1) + .then(() => wsDeviceHive.user.assignNetwork(testUsers[1].id, 1)) + .then(() => done()) + .catch(done); + }); + + + it('UserAPI.getNetwork()', done => { + + Promise.all([httpDeviceHive.user.getNetwork(testUsers[0].id, 1), wsDeviceHive.user.getNetwork(testUsers[1].id, 1)]) + .then(dataAll => { + for (const data of dataAll) { + assert.isObject(data); + assert.property(data, 'network'); + } + }) + .then(done) + .catch(done); + }); + + + it('UserAPI.unassignNetwork()', done => { + + httpDeviceHive.user.unassignNetwork(testUsers[0].id, 1) + .then(() => wsDeviceHive.user.unassignNetwork(testUsers[1].id, 1)) + .then(() => done()) + .catch(done); + }); + + + it('UserAPI.delete()', done => { + + Promise.all([httpDeviceHive.user.delete(testUsers[0].id), wsDeviceHive.user.delete(testUsers[1].id)]) + .then(() => done()) + .catch(done); + }); + +}); \ No newline at end of file diff --git a/test/unit/controllers/ConfigurationAPI.http.spec.js b/test/unit/controllers/ConfigurationAPI.http.spec.js index 69474d2..d26a741 100644 --- a/test/unit/controllers/ConfigurationAPI.http.spec.js +++ b/test/unit/controllers/ConfigurationAPI.http.spec.js @@ -84,8 +84,7 @@ describe('ConfigurationAPI HTTP', () => { // Configurating Configaration model const expectedBody = { name: 'myTestName', - value: 'string', - entityVersion: '1' + value: 'string' }; const configuration = new DeviceHive.models.Configuration(expectedBody); diff --git a/test/unit/controllers/DeviceAPI.http.spec.js b/test/unit/controllers/DeviceAPI.http.spec.js index 4df0037..3705d0e 100644 --- a/test/unit/controllers/DeviceAPI.http.spec.js +++ b/test/unit/controllers/DeviceAPI.http.spec.js @@ -107,7 +107,7 @@ describe('DeviceAPI', () => { name: 'myTestName', networkId: 1, deviceTypeId: 1, - blocked: false + isBlocked: false }; const device = new DeviceHive.models.Device(expectedBody); diff --git a/test/unit/controllers/DeviceAPI.ws.spec.js b/test/unit/controllers/DeviceAPI.ws.spec.js index b3b8c03..3ae25d4 100644 --- a/test/unit/controllers/DeviceAPI.ws.spec.js +++ b/test/unit/controllers/DeviceAPI.ws.spec.js @@ -97,7 +97,7 @@ describe('DeviceAPI WS', () => { name: 'myTestName', networkId: 1, deviceTypeId: 1, - blocked: false + isBlocked: false }; const device = new DeviceHive.models.Device(expected); diff --git a/test/unit/controllers/NotificationAPI.http.spec.js b/test/unit/controllers/DeviceNotificationAPI.http.spec.js similarity index 100% rename from test/unit/controllers/NotificationAPI.http.spec.js rename to test/unit/controllers/DeviceNotificationAPI.http.spec.js diff --git a/test/unit/controllers/NotificationAPI.ws.spec.js b/test/unit/controllers/DeviceNotificationAPI.ws.spec.js similarity index 100% rename from test/unit/controllers/NotificationAPI.ws.spec.js rename to test/unit/controllers/DeviceNotificationAPI.ws.spec.js diff --git a/test/unit/models/Configuration.spec.js b/test/unit/models/Configuration.spec.js index 38b92b9..e9d606d 100644 --- a/test/unit/models/Configuration.spec.js +++ b/test/unit/models/Configuration.spec.js @@ -6,8 +6,7 @@ describe('Configuration', () => { const expected = { name: 'string', - value: 'string', - entityVersion: 0 + value: 'string' }; diff --git a/test/unit/models/Device.spec.js b/test/unit/models/Device.spec.js index 6921455..ab37321 100644 --- a/test/unit/models/Device.spec.js +++ b/test/unit/models/Device.spec.js @@ -11,7 +11,7 @@ describe('Device', () => { }, networkId: 0, deviceTypeId: 0, - blocked: false + isBlocked: false }; From 9d8154165056c32c0b95fbfa507e103fb85daef0 Mon Sep 17 00:00:00 2001 From: Denis Antonenko Date: Fri, 16 Feb 2018 13:06:49 +0200 Subject: [PATCH 03/22] HTTP api transport improvement --- .../transportResolvers/HttpApiResolver.js | 19 +++++-- .../controllers/DeviceCommandAPI.http.spec.js | 49 ++++++++++++++----- .../controllers/NotificationAPI.http.spec.js | 35 +++++++++---- test/unit/controllers/TokenAPI.http.spec.js | 2 +- test/unit/controllers/UserAPI.http.spec.js | 2 +- 5 files changed, 80 insertions(+), 27 deletions(-) diff --git a/src/controllers/transportResolvers/HttpApiResolver.js b/src/controllers/transportResolvers/HttpApiResolver.js index c91e02a..b207d7b 100644 --- a/src/controllers/transportResolvers/HttpApiResolver.js +++ b/src/controllers/transportResolvers/HttpApiResolver.js @@ -13,9 +13,22 @@ class HttpApiResolver { * @param {object} parameters - URI parameters * @returns {string} */ - static buildUrl(base, parameters) { - const stringParameters = queryString.stringify(parameters); - const url = format(base, parameters); + static buildUrl(base, parameters = {}) { + // console.log(base, parameters); + const pathRegex = /[^{}]+(?=\})/g; + const pathParameterKeys = pathRegex.test(base) ? base.match(pathRegex) : []; + const pathParameters = {}; + const queryParameters = {}; + Object.keys(parameters).forEach(key => { + if (pathParameterKeys.includes(key)) { + pathParameters[key] = parameters[key]; + } else { + queryParameters[key] = parameters[key]; + } + }); + + const stringParameters = queryString.stringify(queryParameters); + const url = format(base, pathParameters); return stringParameters ? `${url}?${stringParameters}` : url; } diff --git a/test/unit/controllers/DeviceCommandAPI.http.spec.js b/test/unit/controllers/DeviceCommandAPI.http.spec.js index 5bf0ede..cabedca 100644 --- a/test/unit/controllers/DeviceCommandAPI.http.spec.js +++ b/test/unit/controllers/DeviceCommandAPI.http.spec.js @@ -79,7 +79,7 @@ describe('DeviceCommandAPI HTTP', () => { it('DeviceCommandAPI.list()', done => { - const expectedQuery = { + const source = { deviceId: 'deviceId', start: '2018-02-09T10:09:03.033Z', end: '2018-02-09T10:09:03.033Z', @@ -91,16 +91,27 @@ describe('DeviceCommandAPI HTTP', () => { skip: '1' }; + const expected = { + start: '2018-02-09T10:09:03.033Z', + end: '2018-02-09T10:09:03.033Z', + command: 'command', + status: 'status', + sortField: 'sortField', + sortOrder: 'sortOrder', + take: '1', + skip: '1' + }; + // Configurating Device List query - const commandListQuery = new DeviceHive.models.query.CommandListQuery(expectedQuery); + const commandListQuery = new DeviceHive.models.query.CommandListQuery(source); deviceHive.command.list(commandListQuery); // sent data events.once('request', data => { assert.equal(data.method, 'GET', 'Not correct method'); - assert.equal(data.url.pathname, `/device/${expectedQuery.deviceId}/command`, 'Not correct URL'); - assert.deepEqual(data.url.parameters, expectedQuery, 'Not correct query'); + assert.equal(data.url.pathname, `/device/${source.deviceId}/command`, 'Not correct URL'); + assert.deepEqual(data.url.parameters, expected, 'Not correct query'); done(); }); @@ -180,7 +191,7 @@ describe('DeviceCommandAPI HTTP', () => { it('DeviceCommandAPI.poll()', done => { - const expectedQuery = { + const source = { deviceId: 'deviceId', names: 'names', timestamp: '2018-02-09T10:09:03.033Z', @@ -189,16 +200,24 @@ describe('DeviceCommandAPI HTTP', () => { limit: '1', }; + const expected = { + names: 'names', + timestamp: '2018-02-09T10:09:03.033Z', + returnUpdatedCommands: 'returnUpdatedCommands', + waitTimeout: '10', + limit: '1', + }; + // Configurating Command List query - const commandPollQuery = new DeviceHive.models.query.CommandPollQuery(expectedQuery); + const commandPollQuery = new DeviceHive.models.query.CommandPollQuery(source); deviceHive.command.poll(commandPollQuery); // sent data events.once('request', data => { assert.equal(data.method, 'GET', 'Not correct method'); - assert.equal(data.url.pathname, `/device/${expectedQuery.deviceId}/command/poll`, 'Not correct URL'); - assert.deepEqual(data.url.parameters, expectedQuery, 'Not correct query'); + assert.equal(data.url.pathname, `/device/${source.deviceId}/command/poll`, 'Not correct URL'); + assert.deepEqual(data.url.parameters, expected, 'Not correct query'); done(); }); @@ -233,22 +252,26 @@ describe('DeviceCommandAPI HTTP', () => { it('DeviceCommandAPI.wait()', done => { - const expectedQuery = { + const source = { deviceId: '1', commandId: '1', waitTimeout: '1' }; + const expected = { + waitTimeout: '1' + }; + // Configurating Command List query - const commandWaitQuery = new DeviceHive.models.query.CommandWaitQuery(expectedQuery); + const commandWaitQuery = new DeviceHive.models.query.CommandWaitQuery(source); - deviceHive.command.wait(expectedQuery.deviceId, expectedQuery.commandId, commandWaitQuery); + deviceHive.command.wait(source.deviceId, source.commandId, commandWaitQuery); // sent data events.once('request', data => { assert.equal(data.method, 'GET', 'Not correct method'); - assert.equal(data.url.pathname, `/device/${expectedQuery.deviceId}/command/${expectedQuery.commandId}/poll`, 'Not correct URL'); - assert.deepEqual(data.url.parameters, expectedQuery, 'Not correct query'); + assert.equal(data.url.pathname, `/device/${source.deviceId}/command/${source.commandId}/poll`, 'Not correct URL'); + assert.deepEqual(data.url.parameters, expected, 'Not correct query'); done(); }); diff --git a/test/unit/controllers/NotificationAPI.http.spec.js b/test/unit/controllers/NotificationAPI.http.spec.js index fa2fd51..9332d71 100644 --- a/test/unit/controllers/NotificationAPI.http.spec.js +++ b/test/unit/controllers/NotificationAPI.http.spec.js @@ -11,7 +11,7 @@ const DeviceHive = require('../../../index'); let authService, mainService, deviceHive; -describe('NotificationAPI WS', () => { +describe('NotificationAPI HTTP', () => { before(done => { // authService @@ -79,7 +79,7 @@ describe('NotificationAPI WS', () => { it('NotificationAPI.list()', done => { - const expectedQuery = { + const source = { deviceId: 'deviceId', start: '2018-02-09T10:09:03.033Z', end: '2018-02-09T10:09:03.033Z', @@ -91,16 +91,27 @@ describe('NotificationAPI WS', () => { skip: '1' }; + const expected = { + start: '2018-02-09T10:09:03.033Z', + end: '2018-02-09T10:09:03.033Z', + notification: 'notification', + status: 'status', + sortField: 'sortField', + sortOrder: 'sortOrder', + take: '1', + skip: '1' + }; + // Configurating Notification List query - const notificationListQuery = new DeviceHive.models.query.NotificationListQuery(expectedQuery); + const notificationListQuery = new DeviceHive.models.query.NotificationListQuery(source); deviceHive.notification.list(notificationListQuery); // sent data events.once('request', data => { assert.equal(data.method, 'GET', 'Not correct method'); - assert.equal(data.url.pathname, `/device/${expectedQuery.deviceId}/notification`, 'Not correct URL'); - assert.deepEqual(data.url.parameters, expectedQuery, 'Not correct query'); + assert.equal(data.url.pathname, `/device/${source.deviceId}/notification`, 'Not correct URL'); + assert.deepEqual(data.url.parameters, expected, 'Not correct query'); done(); }); @@ -136,23 +147,29 @@ describe('NotificationAPI WS', () => { it('NotificationAPI.poll()', done => { - const expectedQuery = { + const source = { deviceId: 'deviceId', names: 'names', timestamp: '2018-02-09T10:09:03.033Z', waitTimeout: '10' }; + const expected = { + names: 'names', + timestamp: '2018-02-09T10:09:03.033Z', + waitTimeout: '10' + }; + // Configurating Notification List query - const notificationPollQuery = new DeviceHive.models.query.NotificationPollQuery(expectedQuery); + const notificationPollQuery = new DeviceHive.models.query.NotificationPollQuery(source); deviceHive.notification.poll(notificationPollQuery); // sent data events.once('request', data => { assert.equal(data.method, 'GET', 'Not correct method'); - assert.equal(data.url.pathname, `/device/${expectedQuery.deviceId}/notification/poll`, 'Not correct URL'); - assert.deepEqual(data.url.parameters, expectedQuery, 'Not correct query'); + assert.equal(data.url.pathname, `/device/${source.deviceId}/notification/poll`, 'Not correct URL'); + assert.deepEqual(data.url.parameters, expected, 'Not correct query'); done(); }); diff --git a/test/unit/controllers/TokenAPI.http.spec.js b/test/unit/controllers/TokenAPI.http.spec.js index 438f02d..aa58873 100644 --- a/test/unit/controllers/TokenAPI.http.spec.js +++ b/test/unit/controllers/TokenAPI.http.spec.js @@ -11,7 +11,7 @@ const DeviceHive = require('../../../index'); let authService, mainService, deviceHive; -describe('TokenAPI', () => { +describe('TokenAPI HTTP', () => { before(done => { // authService diff --git a/test/unit/controllers/UserAPI.http.spec.js b/test/unit/controllers/UserAPI.http.spec.js index 7c105b6..2f34cc0 100644 --- a/test/unit/controllers/UserAPI.http.spec.js +++ b/test/unit/controllers/UserAPI.http.spec.js @@ -11,7 +11,7 @@ const DeviceHive = require('../../../index'); let authService, mainService, deviceHive; -describe('UserAPI', () => { +describe('UserAPI HTTP', () => { before(done => { // authService From b29fe75d95314f780cb8964bd0b37cb8d068f2c5 Mon Sep 17 00:00:00 2001 From: Denis Antonenko Date: Wed, 21 Feb 2018 12:42:51 +0200 Subject: [PATCH 04/22] Integration tests & fixes --- package.json | 4 +- src/models/Configuration.js | 10 - src/models/Device.js | 16 +- src/models/query/PluginRegisterQuery.js | 3 +- test/integration/config.json | 16 ++ .../controllers/ConfigurationAPI.spec.js | 66 +++++ test/integration/controllers/Device.spec.js | 118 ++++++++ .../controllers/DeviceCommandAPI.spec.js | 185 ++++++++++++ .../controllers/DeviceNotificationAPI.spec.js | 135 +++++++++ .../controllers/DeviceTypeAPI.spec.js | 130 +++++++++ .../controllers/NetworkAPI.spec.js | 129 +++++++++ .../integration/controllers/PluginAPI.spec.js | 132 +++++++++ .../controllers/ServerInfoAPI.spec.js | 61 ++++ test/integration/controllers/TokenAPI.spec.js | 96 +++++++ test/integration/controllers/UserAPI.spec.js | 269 ++++++++++++++++++ .../controllers/ConfigurationAPI.http.spec.js | 3 +- test/unit/controllers/DeviceAPI.http.spec.js | 2 +- test/unit/controllers/DeviceAPI.ws.spec.js | 2 +- ....js => DeviceNotificationAPI.http.spec.js} | 0 ...ec.js => DeviceNotificationAPI.ws.spec.js} | 0 test/unit/models/Configuration.spec.js | 3 +- test/unit/models/Device.spec.js | 2 +- 22 files changed, 1354 insertions(+), 28 deletions(-) create mode 100644 test/integration/config.json create mode 100644 test/integration/controllers/ConfigurationAPI.spec.js create mode 100644 test/integration/controllers/Device.spec.js create mode 100644 test/integration/controllers/DeviceCommandAPI.spec.js create mode 100644 test/integration/controllers/DeviceNotificationAPI.spec.js create mode 100644 test/integration/controllers/DeviceTypeAPI.spec.js create mode 100644 test/integration/controllers/NetworkAPI.spec.js create mode 100644 test/integration/controllers/PluginAPI.spec.js create mode 100644 test/integration/controllers/ServerInfoAPI.spec.js create mode 100644 test/integration/controllers/TokenAPI.spec.js create mode 100644 test/integration/controllers/UserAPI.spec.js rename test/unit/controllers/{NotificationAPI.http.spec.js => DeviceNotificationAPI.http.spec.js} (100%) rename test/unit/controllers/{NotificationAPI.ws.spec.js => DeviceNotificationAPI.ws.spec.js} (100%) diff --git a/package.json b/package.json index ef7f6da..d99288b 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,9 @@ "main": "index.js", "scripts": { "build": "node build.js", - "test": "node_modules/.bin/mocha test/unit/**/**.spec.js --exit" + "test": "npm run unitTest & npm run integrationTest", + "unitTest": "node_modules/.bin/mocha test/unit/**/**.spec.js --exit", + "integrationTest": "node_modules/.bin/mocha test/integration/**/**.spec.js --timeout 10000 --exit" }, "repository": { "type": "git", diff --git a/src/models/Configuration.js b/src/models/Configuration.js index fb67d27..fd124b7 100644 --- a/src/models/Configuration.js +++ b/src/models/Configuration.js @@ -11,14 +11,12 @@ class Configuration extends BaseModel { * @param {Object} options - model options object * @param {string} options.name - Configuration parameter name. * @param {string} options.value - Configuration parameter value. - * @param {number} options.entityVersion - Specifies the version field or property of an entity class. */ constructor({ name, value, entityVersion } = {}) { super(); this.name = name; this.value = value; - this.entityVersion = entityVersion; } get name() { @@ -37,14 +35,6 @@ class Configuration extends BaseModel { this._value = value; } - get entityVersion() { - return this._entityVersion; - } - - set entityVersion(value) { - this._entityVersion = value; - } - /** * Returns instance as a plain JS object * @returns {Object} diff --git a/src/models/Device.js b/src/models/Device.js index f9eb193..0d29a94 100644 --- a/src/models/Device.js +++ b/src/models/Device.js @@ -14,9 +14,9 @@ class Device extends BaseModel { * @param {object} options.data - Device data, a JSON object with an arbitrary structure * @param {number} options.networkId - Associated network id * @param {number} options.deviceTypeId - Associated deviceType id - * @param {boolean} options.blocked - Indicates whether device is blocked + * @param {boolean} options.isBlocked - Indicates whether device is isBlocked */ - constructor({ id, name, data, networkId, deviceTypeId, blocked } = {}) { + constructor({ id, name, data, networkId, deviceTypeId, isBlocked } = {}) { super(); this.id = id; @@ -24,7 +24,7 @@ class Device extends BaseModel { this.data = data; this.networkId = networkId; this.deviceTypeId = deviceTypeId; - this.blocked = blocked; + this.isBlocked = isBlocked; } get id() { @@ -67,12 +67,12 @@ class Device extends BaseModel { this._deviceTypeId = value; } - get blocked() { - return this._blocked; + get isBlocked() { + return this._isBlocked; } - set blocked(value) { - this._blocked = value; + set isBlocked(value) { + this._isBlocked = value; } /** @@ -86,7 +86,7 @@ class Device extends BaseModel { data: this.data, networkId: this.networkId, deviceTypeId: this.deviceTypeId, - blocked: this.blocked + isBlocked: this.isBlocked }; } } diff --git a/src/models/query/PluginRegisterQuery.js b/src/models/query/PluginRegisterQuery.js index a485b62..29c5b59 100644 --- a/src/models/query/PluginRegisterQuery.js +++ b/src/models/query/PluginRegisterQuery.js @@ -17,9 +17,8 @@ class PluginRegisterQuery extends BaseModel { * @param {boolean} [options.returnUpdatedCommands] - Checks if updated commands should be returned * @param {boolean} [options.returnNotifications] - Checks if commands should be returned */ - constructor({ deviceId, networkIds, deviceTypeIds, names, returnCommands, returnUpdatedCommands, returnNotifications } = {}) { + constructor({ deviceId, networkIds, deviceTypeIds, names, returnCommands = true, returnUpdatedCommands = false, returnNotifications = false } = {}) { super(); - this.deviceId = deviceId; this.networkIds = networkIds; this.deviceTypeIds = deviceTypeIds; diff --git a/test/integration/config.json b/test/integration/config.json new file mode 100644 index 0000000..dab5212 --- /dev/null +++ b/test/integration/config.json @@ -0,0 +1,16 @@ +{ + "server": { + "http": { + "login": "dhadmin", + "password": "dhadmin_#911", + "mainServiceURL": "http://localhost:8080/dh/rest", + "authServiceURL": "http://localhost:8090/dh/rest", + "pluginServiceURL": "http://localhost:8110/dh/rest" + }, + "ws": { + "login": "dhadmin", + "password": "dhadmin_#911", + "mainServiceURL": "ws://localhost:8080/dh/websocket" + } + } +} \ No newline at end of file diff --git a/test/integration/controllers/ConfigurationAPI.spec.js b/test/integration/controllers/ConfigurationAPI.spec.js new file mode 100644 index 0000000..d4bf98a --- /dev/null +++ b/test/integration/controllers/ConfigurationAPI.spec.js @@ -0,0 +1,66 @@ +const chai = require(`chai`); +const assert = chai.assert; +const config = require('../config'); + +const EventEmitter = require('events'); +const events = new EventEmitter(); + +const DeviceHive = require('../../../index'); + +const httpDeviceHive = new DeviceHive(config.server.http); +const wsDeviceHive = new DeviceHive(config.server.ws) + + +const testConfigurations = [ + { + name: 'myTestName', + value: 'string' + }, + { + name: 'myTestName2', + value: 'string' + } +]; + +describe('ConfigurationAPI', () => { + + before(done => { + // Configaratuion DeviceHive + Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => done()); + }); + + + it('ConfigurationAPI.put()', done => { + + // Configurating Configaration model + const configuration = new DeviceHive.models.Configuration(testConfigurations[0]); + const configuration2 = new DeviceHive.models.Configuration(testConfigurations[1]); + + Promise.all([httpDeviceHive.configuration.put(configuration), wsDeviceHive.configuration.put(configuration2)]) + .then(() => done()) + .catch(done); + }); + + + it('ConfigurationAPI.get()', done => { + + Promise.all([httpDeviceHive.configuration.get(testConfigurations[0].name), wsDeviceHive.configuration.get(testConfigurations[1].name)]) + .then(dataAll => { + for (const key in dataAll) { + assert.isObject(dataAll[key]) + assert.include(dataAll[key], testConfigurations[key]); + } + }) + .then(done) + .catch(done); + }); + + + it('ConfigurationAPI.delete()', done => { + + Promise.all([httpDeviceHive.configuration.delete(testConfigurations[0].name), wsDeviceHive.configuration.delete(testConfigurations[1].name)]) + .then(() => done()) + .catch(done); + }); +}); \ No newline at end of file diff --git a/test/integration/controllers/Device.spec.js b/test/integration/controllers/Device.spec.js new file mode 100644 index 0000000..72b4512 --- /dev/null +++ b/test/integration/controllers/Device.spec.js @@ -0,0 +1,118 @@ +const chai = require(`chai`); +const assert = chai.assert; +const config = require('../config'); + +const EventEmitter = require('events'); +const events = new EventEmitter(); + +const DeviceHive = require('../../../index'); + +const httpDeviceHive = new DeviceHive(config.server.http); +const wsDeviceHive = new DeviceHive(config.server.ws) + + +const testDevices = [ + { + id: 'myTestId', + name: 'myTestName', + networkId: 1, + deviceTypeId: 1, + isBlocked: false + }, { + id: 'myTestId2', + name: 'myTestName', + networkId: 1, + deviceTypeId: 1, + isBlocked: false + } +]; + +describe('DeviceAPI', () => { + + before(done => { + // Configaratuion DeviceHive + + Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => done()); + }); + + + it('DeviceAPI.add()', done => { + + // Configurating Device model + const Device = DeviceHive.models.Device; + + const device = new Device(testDevices[0]); + const device2 = new Device(testDevices[1]); + + Promise.all([httpDeviceHive.device.add(device), wsDeviceHive.device.add(device2)]) + .then(() => done()) + .catch(done); + }); + + + it('DeviceAPI.get()', done => { + + const expected = { + deviceId: testDevices[0].id + }; + + Promise.all([httpDeviceHive.device.get(expected.deviceId), wsDeviceHive.device.get(expected.deviceId)]) + .then(dataAll => { + for (const data of dataAll) { + assert.isObject(data) + assert.include(data, testDevices[0]); + } + }) + .then(done) + .catch(done); + }); + + + it('DeviceAPI.list()', done => { + + // Configurating Device List query + const deviceListQuery = new DeviceHive.models.query.DeviceListQuery({ + networkId: 1 + }); + + + Promise.all([httpDeviceHive.device.list(deviceListQuery), wsDeviceHive.device.list(deviceListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + for (const device of data) { + assert.containsAllKeys(device, Object.keys(testDevices[0])); + } + } + }) + .then(done) + .catch(done); + + }); + + + it('DeviceAPI.count()', done => { + + // Configurating Device List query + const deviceListQuery = new DeviceHive.models.query.DeviceCountQuery({ + networkId: '1' + }); + + Promise.all([httpDeviceHive.device.count(deviceListQuery), wsDeviceHive.device.count(deviceListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + assert.property(data, 'count'); + } + }) + .then(done) + .catch(done); + }); + + + it('DeviceAPI.delete()', done => { + + Promise.all([httpDeviceHive.device.delete(testDevices[0].id), wsDeviceHive.device.delete(testDevices[1].id)]) + .then(() => done()) + .catch(done); + }); +}); \ No newline at end of file diff --git a/test/integration/controllers/DeviceCommandAPI.spec.js b/test/integration/controllers/DeviceCommandAPI.spec.js new file mode 100644 index 0000000..f139351 --- /dev/null +++ b/test/integration/controllers/DeviceCommandAPI.spec.js @@ -0,0 +1,185 @@ +const chai = require(`chai`); +const assert = chai.assert; +const config = require('../config'); + +const EventEmitter = require('events'); +const events = new EventEmitter(); + +const DeviceHive = require('../../../index'); + +const httpDeviceHive = new DeviceHive(config.server.http); +const wsDeviceHive = new DeviceHive(config.server.ws) + +const deviceId = 'e50d6085-2aba-48e9-b1c3-73c673e414be2'; + +const testDeviceCommands = [ + { + deviceId, + command: 'command', + timestamp: new Date().toISOString(), + lastUpdated: new Date().toISOString(), + userId: 1, + networkId: 1, + parameters: { + jsonString: 'jsonString' + }, + lifetime: 0, + status: 'status', + result: { + jsonString: 'jsonString' + } + }, + { + deviceId, + command: 'command2', + timestamp: new Date().toISOString(), + lastUpdated: new Date().toISOString(), + userId: 1, + networkId: 1, + parameters: { + jsonString: 'jsonString' + }, + lifetime: 0, + status: 'status', + result: { + jsonString: 'jsonString' + } + } +]; + +describe('DeviceCommandAPI', () => { + + before(done => { + // Configaratuion DeviceHive + Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => done()); + }); + + + it('DeviceCommandAPI.insert()', done => { + const command = new DeviceHive.models.Command(testDeviceCommands[0]); + const command2 = new DeviceHive.models.Command(testDeviceCommands[1]); + + Promise.all([httpDeviceHive.command.insert(deviceId, command), wsDeviceHive.command.insert(deviceId, command2)]) + .then(() => done()) + .catch(done); + }); + + + it('DeviceCommandAPI.list()', done => { + + // Configurating Device List query + const commandListQuery = new DeviceHive.models.query.CommandListQuery({ + deviceId, + command: 'command', + status: 'status', + sortField: 'id', + sortOrder: 'id', + take: 2, + skip: 0 + }); + + Promise.all([httpDeviceHive.command.list(commandListQuery), wsDeviceHive.command.list(commandListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + for (const deviceCommandKey in data) { + testDeviceCommands[deviceCommandKey].id = data[deviceCommandKey].id; + testDeviceCommands[deviceCommandKey].timestamp = data[deviceCommandKey].timestamp; + testDeviceCommands[deviceCommandKey].lastUpdated = data[deviceCommandKey].lastUpdated; + assert.containsAllKeys(data[deviceCommandKey], Object.keys(testDeviceCommands[0])); + } + } + }) + .then(done) + .catch(done); + }); + + + it('DeviceCommand API.get()', done => { + + + Promise.all([httpDeviceHive.command.get(deviceId, testDeviceCommands[0].id), wsDeviceHive.command.get(deviceId, testDeviceCommands[0].id)]) + .then(dataAll => { + const expected = testDeviceCommands[0]; + for (const data of dataAll) { + assert.isObject(data); + assert.deepInclude(data, expected); + } + }) + .then(done) + .catch(done); + }); + + + it('DeviceCommandAPI.update()', done => { + + const command = new DeviceHive.models.Command(testDeviceCommands[0], testDeviceCommands[0]); + const command2 = new DeviceHive.models.Command(testDeviceCommands[0], testDeviceCommands[1]); + + Promise.all([httpDeviceHive.command.update(command), wsDeviceHive.command.update(command2)]) + .then(() => done()) + .catch(done); + }); + + + it('DeviceCommandAPI.poll()', done => { + + // Configurating Command List query + const commandPollQuery = new DeviceHive.models.query.CommandPollQuery({ + deviceId, + returnUpdatedCommands: true, + limit: 1, + waitTimeout: 1 + }); + + httpDeviceHive.command.poll(commandPollQuery) + .then(() => done()) + .catch(done); + + // emit command + setTimeout(() => { + const command = new DeviceHive.models.Command(testDeviceCommands[0]); + httpDeviceHive.command.insert(deviceId, command); + }, 50); + }); + + + it('DeviceCommandAPI.pollMany()', done => { + + const commandPollManyQuery = new DeviceHive.models.query.CommandPollManyQuery({ + deviceIds: deviceId + }); + + httpDeviceHive.command.pollMany(commandPollManyQuery) + .then(() => done()) + .catch(done); + + // emit command + setTimeout(() => { + const command = new DeviceHive.models.Command(testDeviceCommands[0]); + httpDeviceHive.command.insert(deviceId, command); + }, 50); + }); + + + it('DeviceCommandAPI.wait()', done => { + + // TODO + done(); + + // Configurating Command List query + // const commandWaitQuery = new DeviceHive.models.query.CommandWaitQuery({ + // deviceId, + // commandId: testDeviceCommands[0].id, + // waitTimeout: 1 + // }); + + // httpDeviceHive.command.wait(commandWaitQuery.deviceId, commandWaitQuery.commandId, commandWaitQuery) + // .then(() => done()) + // .catch(done); + + // // emit command + // const command = new DeviceHive.models.Command(testDeviceCommands[0]); + // httpDeviceHive.command.insert(deviceId, command); + }); +}); \ No newline at end of file diff --git a/test/integration/controllers/DeviceNotificationAPI.spec.js b/test/integration/controllers/DeviceNotificationAPI.spec.js new file mode 100644 index 0000000..fb97e36 --- /dev/null +++ b/test/integration/controllers/DeviceNotificationAPI.spec.js @@ -0,0 +1,135 @@ +const chai = require(`chai`); +const assert = chai.assert; +const config = require('../config'); + +const EventEmitter = require('events'); +const events = new EventEmitter(); + +const DeviceHive = require('../../../index'); + +const httpDeviceHive = new DeviceHive(config.server.http); +const wsDeviceHive = new DeviceHive(config.server.ws) + +const deviceId = 'e50d6085-2aba-48e9-b1c3-73c673e414be2'; + +const testDeviceNotifications = [ + { + deviceId, + notification: 'notification', + timestamp: new Date().toISOString(), + parameters: { + jsonString: 'jsonString' + } + }, + { + deviceId, + notification: 'notification', + timestamp: new Date().toISOString(), + parameters: { + jsonString: 'jsonString' + } + }, +]; + +describe('NotificationAPI', () => { + + before(done => { + // Configaratuion DeviceHive + Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => done()); + }); + + + it('NotificationAPI.insert()', done => { + + const notification = new DeviceHive.models.Notification(testDeviceNotifications[0]); + const notification2 = new DeviceHive.models.Notification(testDeviceNotifications[1]); + + Promise.all([httpDeviceHive.notification.insert(deviceId, notification), wsDeviceHive.notification.insert(deviceId, notification2)]) + .then(() => done()) + .catch(done); + }); + + + it('NotificationAPI.list()', done => { + + // Configurating Device List query + const notificationListQuery = new DeviceHive.models.query.NotificationListQuery({ + deviceId, + notification: 'notification', + status: 'status', + sortField: 'id', + sortOrder: 'id', + take: 2, + skip: 0 + }); + + Promise.all([httpDeviceHive.notification.list(notificationListQuery), wsDeviceHive.notification.list(notificationListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + for (const deviceNotificationKey in data) { + testDeviceNotifications[deviceNotificationKey].id = data[deviceNotificationKey].id; + testDeviceNotifications[deviceNotificationKey].timestamp = data[deviceNotificationKey].timestamp; + assert.containsAllKeys(data[deviceNotificationKey], Object.keys(testDeviceNotifications[0])); + } + } + }) + .then(done) + .catch(done); + }); + + + it('NotificationAPI.get()', done => { + + Promise.all([httpDeviceHive.notification.get(deviceId, testDeviceNotifications[0].id), wsDeviceHive.notification.get(deviceId, testDeviceNotifications[0].id)]) + .then(dataAll => { + const expected = testDeviceNotifications[0]; + for (const data of dataAll) { + assert.isObject(data); + assert.deepInclude(data, expected); + } + }) + .then(done) + .catch(done); + }); + + + it('NotificationAPI.poll()', done => { + + // Configurating Notification List query + const notificationPollQuery = new DeviceHive.models.query.NotificationPollQuery({ + deviceId, + returnUpdatedNotifications: true, + limit: 1, + waitTimeout: 1 + }); + + httpDeviceHive.notification.poll(notificationPollQuery) + .then(() => done()) + .catch(done); + + // emit notification + setTimeout(() => { + const notification = new DeviceHive.models.Notification(testDeviceNotifications[0]); + httpDeviceHive.notification.insert(deviceId, notification); + }, 50); + }); + + + it('NotificationAPI.pollMany()', done => { + + const notificationPollManyQuery = new DeviceHive.models.query.NotificationPollManyQuery({ + deviceIds: deviceId + }); + + httpDeviceHive.notification.pollMany(notificationPollManyQuery) + .then(() => done()) + .catch(done); + + // emit notification + setTimeout(() => { + const notification = new DeviceHive.models.Notification(testDeviceNotifications[0]); + httpDeviceHive.notification.insert(deviceId, notification); + }, 50); + }); +}); \ No newline at end of file diff --git a/test/integration/controllers/DeviceTypeAPI.spec.js b/test/integration/controllers/DeviceTypeAPI.spec.js new file mode 100644 index 0000000..82cf932 --- /dev/null +++ b/test/integration/controllers/DeviceTypeAPI.spec.js @@ -0,0 +1,130 @@ +const chai = require(`chai`); +const assert = chai.assert; +const config = require('../config'); + +const EventEmitter = require('events'); +const events = new EventEmitter(); + +const DeviceHive = require('../../../index'); + +const httpDeviceHive = new DeviceHive(config.server.http); +const wsDeviceHive = new DeviceHive(config.server.ws) + + +const testDeviceTypes = [ + { + name: 'name', + description: 'description' + }, { + name: 'name2', + description: 'description2' + } +]; + +describe('DeviceTypeAPI', () => { + + before(done => { + // Configaratuion DeviceHive + + Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => done()); + }); + + + it('DeviceTypeAPI.insert()', done => { + + // Configurating DeviceType model + const DeviceType = DeviceHive.models.DeviceType; + + const deviceType = new DeviceType(testDeviceTypes[0]); + const deviceType2 = new DeviceType(testDeviceTypes[1]); + + Promise.all([httpDeviceHive.deviceType.insert(deviceType), wsDeviceHive.deviceType.insert(deviceType2)]) + .then(() => done()) + .catch(done); + }); + + + it('DeviceTypeAPI.list()', done => { + + + // Configurating Device List query + const deviceTypeListQuery = new DeviceHive.models.query.DeviceTypeListQuery({ + namePattern: 'name%', + sortField: 'name', + sortOrder: 'asc', + take: 2, + skip: 0 + }); + + + Promise.all([httpDeviceHive.deviceType.list(deviceTypeListQuery), wsDeviceHive.deviceType.list(deviceTypeListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + for (const deviceTypeKey in data) { + testDeviceTypes[deviceTypeKey].id = data[deviceTypeKey].id; + testDeviceTypes[deviceTypeKey].name = data[deviceTypeKey].name; + testDeviceTypes[deviceTypeKey].description = data[deviceTypeKey].description; + assert.containsAllKeys(data[deviceTypeKey], Object.keys(testDeviceTypes[0])); + } + } + }) + .then(done) + .catch(done); + }); + + + it('DeviceTypeAPI.get()', done => { + + Promise.all([httpDeviceHive.deviceType.get(testDeviceTypes[0].id), wsDeviceHive.deviceType.get(testDeviceTypes[0].id)]) + .then(dataAll => { + const expected = testDeviceTypes[0]; + for (const data of dataAll) { + assert.isObject(data); + assert.deepInclude(data, expected); + } + }) + .then(done) + .catch(done); + }); + + + it('DeviceTypeAPI.update()', done => { + + // Configurating DeviceType model + const DeviceType = DeviceHive.models.DeviceType; + + const deviceType = new DeviceType(testDeviceTypes[0]); + const deviceType2 = new DeviceType(testDeviceTypes[1]); + + Promise.all([httpDeviceHive.deviceType.update(deviceType), wsDeviceHive.deviceType.update(deviceType2)]) + .then(() => done()) + .catch(done); + + }); + + it('DeviceTypeAPI.count()', done => { + + // Configurating DeviceType List query + const deviceTypeListQuery = new DeviceHive.models.query.DeviceTypeCountQuery({ + name: 'name', + namePattern: 'namePattern' + }); + + Promise.all([httpDeviceHive.deviceType.count(deviceTypeListQuery), wsDeviceHive.deviceType.count(deviceTypeListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + assert.property(data, 'count'); + } + }) + .then(done) + .catch(done); + }); + + it('DeviceTypeAPI.delete()', done => { + + Promise.all([httpDeviceHive.deviceType.delete(testDeviceTypes[0].id), wsDeviceHive.deviceType.delete(testDeviceTypes[1].id)]) + .then(() => done()) + .catch(done); + }); +}); \ No newline at end of file diff --git a/test/integration/controllers/NetworkAPI.spec.js b/test/integration/controllers/NetworkAPI.spec.js new file mode 100644 index 0000000..12f6a6b --- /dev/null +++ b/test/integration/controllers/NetworkAPI.spec.js @@ -0,0 +1,129 @@ +const chai = require(`chai`); +const assert = chai.assert; +const config = require('../config'); + +const EventEmitter = require('events'); +const events = new EventEmitter(); + +const DeviceHive = require('../../../index'); + +const httpDeviceHive = new DeviceHive(config.server.http); +const wsDeviceHive = new DeviceHive(config.server.ws) + + +const testNetworks = [ + { + name: 'name', + description: 'description' + }, { + name: 'name2', + description: 'description2' + } +]; + +describe('NetworkAPI', () => { + + before(done => { + // Configaratuion DeviceHive + + Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => done()); + }); + + + it('NetworkAPI.insert()', done => { + + // Configurating Network model + const Network = DeviceHive.models.Network; + + const network = new Network(testNetworks[0]); + const network2 = new Network(testNetworks[1]); + + Promise.all([httpDeviceHive.network.insert(network), wsDeviceHive.network.insert(network2)]) + .then(() => done()) + .catch(done); + }); + + + it('NetworkAPI.list()', done => { + + // Configurating Device List query + const networkListQuery = new DeviceHive.models.query.NetworkListQuery({ + namePattern: 'name%', + sortField: 'name', + sortOrder: 'asc', + take: 2, + skip: 0 + }); + + + Promise.all([httpDeviceHive.network.list(networkListQuery), wsDeviceHive.network.list(networkListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + for (const networkKey in data) { + testNetworks[networkKey].id = data[networkKey].id; + testNetworks[networkKey].name = data[networkKey].name; + testNetworks[networkKey].description = data[networkKey].description; + assert.containsAllKeys(data[networkKey], Object.keys(testNetworks[0])); + } + } + }) + .then(done) + .catch(done); + }); + + + it('NetworkAPI.get()', done => { + + Promise.all([httpDeviceHive.network.get(testNetworks[0].id), wsDeviceHive.network.get(testNetworks[0].id)]) + .then(dataAll => { + const expected = testNetworks[0]; + for (const data of dataAll) { + assert.isObject(data); + assert.deepInclude(data, expected); + } + }) + .then(done) + .catch(done); + }); + + + it('NetworkAPI.update()', done => { + + // Configurating Network model + const Network = DeviceHive.models.Network; + + const network = new Network(testNetworks[0]); + const network2 = new Network(testNetworks[1]); + + Promise.all([httpDeviceHive.network.update(network), wsDeviceHive.network.update(network2)]) + .then(() => done()) + .catch(done); + + }); + + it('NetworkAPI.count()', done => { + + // Configurating Network List query + const networkListQuery = new DeviceHive.models.query.NetworkCountQuery({ + name: 'name', + namePattern: 'namePattern' + }); + + Promise.all([httpDeviceHive.network.count(networkListQuery), wsDeviceHive.network.count(networkListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + assert.property(data, 'count'); + } + }) + .then(done) + .catch(done); + }); + + it('NetworkAPI.delete()', done => { + + Promise.all([httpDeviceHive.network.delete(testNetworks[0].id), wsDeviceHive.network.delete(testNetworks[1].id)]) + .then(() => done()) + .catch(done); + }); +}); \ No newline at end of file diff --git a/test/integration/controllers/PluginAPI.spec.js b/test/integration/controllers/PluginAPI.spec.js new file mode 100644 index 0000000..fab0122 --- /dev/null +++ b/test/integration/controllers/PluginAPI.spec.js @@ -0,0 +1,132 @@ +const chai = require(`chai`); +const assert = chai.assert; +const config = require('../config'); + +const EventEmitter = require('events'); +const events = new EventEmitter(); + +const DeviceHive = require('../../../index'); + +const httpDeviceHive = new DeviceHive(config.server.http); +const wsDeviceHive = new DeviceHive(config.server.ws) + + +const testPlugins = [ + { + name: `testName${new Date().getMilliseconds()}`, + description: 'description', + parameters: { + jsonString: 'string' + } + } +]; + +describe('PluginAPI', () => { + + before(done => { + // Configaratuion DeviceHive + + Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => done()); + }); + + + it('PluginAPI.register()', done => { + const plugin = new DeviceHive.models.Plugin(testPlugins[0]); + const pluginQuery = new DeviceHive.models.query.PluginRegisterQuery({ + returnCommands: 'true', + returnUpdatedCommands: 'false', + returnNotifications: 'false' + }); + + Promise.all([httpDeviceHive.plugin.register(plugin, pluginQuery)]) + .then(dataAll => { + for (const data of dataAll) { + testPlugins[0] = Object.assign({}, testPlugins[0], data); + } + }) + .then(() => done()) + .catch(done); + }); + + it('PluginAPI.list()', done => { + + // Configurating Plugin List query + const pluginListQuery = new DeviceHive.models.query.PluginListQuery({ + take: 1, + skip: 0 + }); + + Promise.all([httpDeviceHive.plugin.list(pluginListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + assert.isArray(data); + } + }) + .then(() => done()) + .catch(done); + }); + + + // TODO + // it('PluginAPI.update()', done => { + // }); + + + it('PluginAPI.count()', done => { + + // Configurating Plugin List query + const pluginCountQuery = new DeviceHive.models.query.PluginCountQuery({ + status: '1' + }); + + Promise.all([httpDeviceHive.plugin.count(pluginCountQuery)]) + .then(dataAll => { + for (const data of dataAll) { + assert.property(data, 'count'); + } + }) + .then(() => done()) + .catch(done); + }); + + it('TokenAPI.createPluginToken()', done => { + + // Configurating Token model + const token = new DeviceHive.models.PluginToken({ + actions: [0], + expiration: '2018-02-09T10:09:03.033Z', + type: 0, + topicName: testPlugins[0].topicName + }); + + Promise.all([httpDeviceHive.token.createPluginToken(token)]) + .then(dataAll => { + for (const data of dataAll) { + const expectedKeys = ['accessToken', 'refreshToken'] + assert.containsAllKeys(data, expectedKeys); + } + }) + .then(done) + .catch(done); + }); + + it('TokenAPI.authPlugin()', done => { + Promise.all([httpDeviceHive.token.authPlugin(testPlugins[0].accessToken)]) + .then(dataAll => { + for (const data of dataAll) { + const expectedKeys = ['tpc', 'a', 'e', 't']; + assert.containsAllKeys(data, expectedKeys) + } + }) + .then(done) + .catch(done); + }); + + it('PluginAPI.delete()', done => { + + Promise.all([httpDeviceHive.plugin.delete(testPlugins[0].topicName)]) + .then(() => done()) + .catch(done); + }); +}); \ No newline at end of file diff --git a/test/integration/controllers/ServerInfoAPI.spec.js b/test/integration/controllers/ServerInfoAPI.spec.js new file mode 100644 index 0000000..4b21d60 --- /dev/null +++ b/test/integration/controllers/ServerInfoAPI.spec.js @@ -0,0 +1,61 @@ +const chai = require(`chai`); +const assert = chai.assert; +const config = require('../config'); + +const EventEmitter = require('events'); +const events = new EventEmitter(); + +const DeviceHive = require('../../../index'); + +const httpDeviceHive = new DeviceHive(config.server.http); +const wsDeviceHive = new DeviceHive(config.server.ws) + + +describe('ServerInfoAPI', () => { + + before(done => { + // Configaratuion DeviceHive + Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => done()); + }); + + + it('InfoAPI.getServerInfo()', done => { + + Promise.all([httpDeviceHive.info.getServerInfo(), wsDeviceHive.info.getServerInfo()]) + .then(dataAll => { + for (const data of dataAll) { + const expectedKeys = ['apiVersion', 'serverTimestamp'] + assert.isObject(data); + assert.containsAllKeys(data, expectedKeys); + } + }) + .then(done) + .catch(done); + }); + + it('InfoAPI.getCacheInfo()', done => { + + Promise.all([httpDeviceHive.info.getCacheInfo()]) + .then(dataAll => { + for (const data of dataAll) { + const expectedKeys = ['serverTimestamp', 'cacheStats'] + assert.isObject(data); + assert.containsAllKeys(data, expectedKeys); + } + }) + .then(done) + .catch(done); + }); + + it('InfoAPI.getClusterInfo()', done => { + Promise.all([httpDeviceHive.info.getClusterInfo(), wsDeviceHive.info.getClusterInfo()]) + .then(dataAll => { + for (const data of dataAll) { + assert.isObject(data); + } + }) + .then(done) + .catch(done); + }); +}); \ No newline at end of file diff --git a/test/integration/controllers/TokenAPI.spec.js b/test/integration/controllers/TokenAPI.spec.js new file mode 100644 index 0000000..d6e7aab --- /dev/null +++ b/test/integration/controllers/TokenAPI.spec.js @@ -0,0 +1,96 @@ +const chai = require(`chai`); +const assert = chai.assert; +const config = require('../config'); + +const EventEmitter = require('events'); +const events = new EventEmitter(); + +const DeviceHive = require('../../../index'); + +const httpDeviceHive = new DeviceHive(config.server.http); +const wsDeviceHive = new DeviceHive(config.server.ws) + + +const testToken = { + login: config.server.http.login, + password: config.server.http.password +}; + +describe('TokenAPI', () => { + + before(done => { + // Configaratuion DeviceHive + + Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => done()); + }); + + it('TokenAPI.createUserToken()', done => { + + // Configurating Token model + const token = new DeviceHive.models.UserToken({ + userId: 1, + actions: ['string'], + networkIds: ['string'], + deviceTypeIds: ['string'], + expiration: '2030-02-09T10:09:03.033Z' + }); + + Promise.all([httpDeviceHive.token.createUserToken(token), wsDeviceHive.token.createUserToken(token)]) + .then(dataAll => { + for (const data of dataAll) { + const expectedkeys = ['accessToken', 'refreshToken']; + assert.isObject(data); + assert.containsAllKeys(data, expectedkeys); + testToken.accessToken = data.accessToken; + testToken.refreshToken = data.refreshToken; + } + }) + .then(done) + .catch(done); + }); + + it('TokenAPI.refresh()', done => { + + // Configurating Token model + + Promise.all([httpDeviceHive.token.refresh(testToken.refreshToken)]) + .then(dataAll => { + for (const data of dataAll) { + const expectedkeys = ['accessToken']; + assert.isObject(data); + assert.containsAllKeys(data, expectedkeys); + testToken.accessToken = data.accessToken; + testToken.refreshToken = data.refreshToken; + } + }) + .then(done) + .catch(done); + + // sent data + events.once('request', data => { + assert.equal(data.method, 'POST', 'Not correct method'); + assert.equal(data.url.pathname, `/token/refresh`, 'Not correct URL'); + assert.deepEqual(data.body, expectedBody, 'Not correct body'); + + done(); + }); + }); + + + it('TokenAPI.login()', done => { + + Promise.all([httpDeviceHive.token.login(testToken.login, testToken.password), wsDeviceHive.token.login(testToken.login, testToken.password)]) + .then(dataAll => { + for (const data of dataAll) { + const expectedkeys = ['accessToken', 'refreshToken']; + assert.isObject(data); + assert.containsAllKeys(data, expectedkeys); + testToken.accessToken = data.accessToken; + testToken.refreshToken = data.refreshToken; + } + }) + .then(done) + .catch(done) + }); +}); \ No newline at end of file diff --git a/test/integration/controllers/UserAPI.spec.js b/test/integration/controllers/UserAPI.spec.js new file mode 100644 index 0000000..088c911 --- /dev/null +++ b/test/integration/controllers/UserAPI.spec.js @@ -0,0 +1,269 @@ +const chai = require(`chai`); +const assert = chai.assert; +const config = require('../config'); + +const EventEmitter = require('events'); +const events = new EventEmitter(); + +const DeviceHive = require('../../../index'); + +const httpDeviceHive = new DeviceHive(config.server.http); +const wsDeviceHive = new DeviceHive(config.server.ws) + + +const testUsers = [ + { + login: 'testLogin', + role: 1, + status: 1, + password: 'password', + lastLogin: '2018-02-09T10:09:03.033Z', + data: { + jsonString: 'jsonString' + }, + introReviewed: false, + allDeviceTypesAvailable: false + }, { + login: 'testLogin2', + role: 1, + status: 1, + password: 'password', + lastLogin: '2018-02-09T10:09:03.033Z', + data: { + jsonString: 'jsonString' + }, + introReviewed: false, + allDeviceTypesAvailable: false + } +]; + +describe('UserAPI', () => { + + before(done => { + // Configaratuion DeviceHive + + Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => done()); + }); + + it('UserAPI.insert()', done => { + + // Configurating User model + const User = DeviceHive.models.User; + + const user = new User(testUsers[0]); + const user2 = new User(testUsers[1]); + + Promise.all([httpDeviceHive.user.insert(user), wsDeviceHive.user.insert(user2)]) + .then(() => done()) + .catch(done); + }); + + + it('UserAPI.list()', done => { + + // Configurating User List query + const userListQuery = new DeviceHive.models.query.UserListQuery({ + loginPattern: 'testLogin%', + role: 1, + status: 1, + sortField: 'login', + sortOrder: 'asc', + take: 2, + skip: 0, + }); + + Promise.all([httpDeviceHive.user.list(userListQuery), wsDeviceHive.user.list(userListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + for (const userKey in data) { + testUsers[userKey].id = data[userKey].id; + testUsers[userKey].lastLogin = data[userKey].lastLogin; + + const expectedKeys = Object.keys(testUsers[0]); + expectedKeys.splice(expectedKeys.indexOf('password'), 1); + assert.containsAllKeys(data[userKey], expectedKeys); + } + } + }) + .then(done) + .catch(done); + }); + + it('UserAPI.get()', done => { + + Promise.all([httpDeviceHive.user.get(testUsers[0].id), wsDeviceHive.user.get(testUsers[0].id)]) + .then(dataAll => { + const expected = Object.assign({}, testUsers[0]); + delete expected.password; + for (const data of dataAll) { + assert.isObject(data); + assert.deepInclude(data, expected); + } + }) + .then(done) + .catch(done); + }); + + it('UserAPI.getCurrent()', done => { + + Promise.all([httpDeviceHive.user.getCurrent(), wsDeviceHive.user.getCurrent()]) + .then(dataAll => { + const expected = Object.assign({}, testUsers[0]); + delete expected.password; + for (const data of dataAll) { + const expectedKeys = Object.keys(testUsers[0]); + expectedKeys.splice(expectedKeys.indexOf('password'), 1); + + assert.isObject(data); + assert.containsAllKeys(data, expectedKeys); + } + }) + .then(done) + .catch(done); + }); + + + it('UserAPI.update()', done => { + + // Configurating User model + const User = DeviceHive.models.User; + + const user = new User(testUsers[0]); + const user2 = new User(testUsers[1]); + + Promise.all([httpDeviceHive.user.update(user), wsDeviceHive.user.update(user2)]) + .then(() => done()) + .catch(done); + + }); + + + it('UserAPI.updateCurrent()', done => { + + // Configurating User model + const user = new DeviceHive.models.User({ + status: 0 + }); + + Promise.all([httpDeviceHive.user.updateCurrent(user), wsDeviceHive.user.updateCurrent(user)]) + .then(() => done()) + .catch(done); + }); + + + it('UserAPI.count()', done => { + + // Configurating User List query + const userListQuery = new DeviceHive.models.query.UserCountQuery({ + login: 'login', + loginPattern: 'loginPattern', + role: '1', + status: '1', + }); + + Promise.all([httpDeviceHive.user.count(userListQuery), wsDeviceHive.user.count(userListQuery)]) + .then(dataAll => { + for (const data of dataAll) { + assert.property(data, 'count'); + } + }) + .then(done) + .catch(done); + }); + + + it('UserAPI.getDeviceTypes()', done => { + + Promise.all([httpDeviceHive.user.getDeviceTypes(testUsers[0].id)]) + .then(() => done()) + .catch(done); + }); + + + it('UserAPI.assignAllDeviceTypes()', done => { + + Promise.all([httpDeviceHive.user.assignAllDeviceTypes(testUsers[0].id)]) + .then(() => done()) + .catch(done); + }); + + + it('UserAPI.unassignAllDeviceTypes()', done => { + + Promise.all([httpDeviceHive.user.unassignAllDeviceTypes(testUsers[0].id)]) + .then(() => done()) + .catch(done); + }); + + + it('UserAPI.assignDeviceType()', done => { + + Promise.all([httpDeviceHive.user.assignDeviceType(testUsers[0].id, 1)]) + .then(() => done()) + .catch(done); + }); + + + it('UserAPI.getDeviceType()', done => { + + Promise.all([httpDeviceHive.user.getDeviceType(testUsers[0].id, 1)]) + .then(dataAll => { + for (const data of dataAll) { + assert.isObject(data); + assert.property(data, 'deviceType'); + } + }) + .then(done) + .catch(done); + }); + + + it('UserAPI.unassignDeviceType()', done => { + + Promise.all([httpDeviceHive.user.unassignDeviceType(testUsers[0].id, 1)]) + .then(() => done()) + .catch(done); + }); + + + it('UserAPI.assignNetwork()', done => { + + httpDeviceHive.user.assignNetwork(testUsers[0].id, 1) + .then(() => wsDeviceHive.user.assignNetwork(testUsers[1].id, 1)) + .then(() => done()) + .catch(done); + }); + + + it('UserAPI.getNetwork()', done => { + + Promise.all([httpDeviceHive.user.getNetwork(testUsers[0].id, 1), wsDeviceHive.user.getNetwork(testUsers[1].id, 1)]) + .then(dataAll => { + for (const data of dataAll) { + assert.isObject(data); + assert.property(data, 'network'); + } + }) + .then(done) + .catch(done); + }); + + + it('UserAPI.unassignNetwork()', done => { + + httpDeviceHive.user.unassignNetwork(testUsers[0].id, 1) + .then(() => wsDeviceHive.user.unassignNetwork(testUsers[1].id, 1)) + .then(() => done()) + .catch(done); + }); + + + it('UserAPI.delete()', done => { + + Promise.all([httpDeviceHive.user.delete(testUsers[0].id), wsDeviceHive.user.delete(testUsers[1].id)]) + .then(() => done()) + .catch(done); + }); + +}); \ No newline at end of file diff --git a/test/unit/controllers/ConfigurationAPI.http.spec.js b/test/unit/controllers/ConfigurationAPI.http.spec.js index 69474d2..d26a741 100644 --- a/test/unit/controllers/ConfigurationAPI.http.spec.js +++ b/test/unit/controllers/ConfigurationAPI.http.spec.js @@ -84,8 +84,7 @@ describe('ConfigurationAPI HTTP', () => { // Configurating Configaration model const expectedBody = { name: 'myTestName', - value: 'string', - entityVersion: '1' + value: 'string' }; const configuration = new DeviceHive.models.Configuration(expectedBody); diff --git a/test/unit/controllers/DeviceAPI.http.spec.js b/test/unit/controllers/DeviceAPI.http.spec.js index 4df0037..3705d0e 100644 --- a/test/unit/controllers/DeviceAPI.http.spec.js +++ b/test/unit/controllers/DeviceAPI.http.spec.js @@ -107,7 +107,7 @@ describe('DeviceAPI', () => { name: 'myTestName', networkId: 1, deviceTypeId: 1, - blocked: false + isBlocked: false }; const device = new DeviceHive.models.Device(expectedBody); diff --git a/test/unit/controllers/DeviceAPI.ws.spec.js b/test/unit/controllers/DeviceAPI.ws.spec.js index b3b8c03..3ae25d4 100644 --- a/test/unit/controllers/DeviceAPI.ws.spec.js +++ b/test/unit/controllers/DeviceAPI.ws.spec.js @@ -97,7 +97,7 @@ describe('DeviceAPI WS', () => { name: 'myTestName', networkId: 1, deviceTypeId: 1, - blocked: false + isBlocked: false }; const device = new DeviceHive.models.Device(expected); diff --git a/test/unit/controllers/NotificationAPI.http.spec.js b/test/unit/controllers/DeviceNotificationAPI.http.spec.js similarity index 100% rename from test/unit/controllers/NotificationAPI.http.spec.js rename to test/unit/controllers/DeviceNotificationAPI.http.spec.js diff --git a/test/unit/controllers/NotificationAPI.ws.spec.js b/test/unit/controllers/DeviceNotificationAPI.ws.spec.js similarity index 100% rename from test/unit/controllers/NotificationAPI.ws.spec.js rename to test/unit/controllers/DeviceNotificationAPI.ws.spec.js diff --git a/test/unit/models/Configuration.spec.js b/test/unit/models/Configuration.spec.js index 38b92b9..e9d606d 100644 --- a/test/unit/models/Configuration.spec.js +++ b/test/unit/models/Configuration.spec.js @@ -6,8 +6,7 @@ describe('Configuration', () => { const expected = { name: 'string', - value: 'string', - entityVersion: 0 + value: 'string' }; diff --git a/test/unit/models/Device.spec.js b/test/unit/models/Device.spec.js index 6921455..ab37321 100644 --- a/test/unit/models/Device.spec.js +++ b/test/unit/models/Device.spec.js @@ -11,7 +11,7 @@ describe('Device', () => { }, networkId: 0, deviceTypeId: 0, - blocked: false + isBlocked: false }; From cf2f30c3e7076a007c91538345c7b264172e5f7a Mon Sep 17 00:00:00 2001 From: itrambovetskiy Date: Fri, 23 Feb 2018 18:53:09 +0200 Subject: [PATCH 05/22] Autoupdate session --- example/node/index.js | 37 +++++++++------ package-lock.json | 105 ++++++++++++++++++++++++++++++++++++++++-- package.json | 1 + src/ApiStrategy.js | 8 +++- src/DeviceHive.js | 29 +++++++++--- src/utils/Utils.js | 16 +++++++ 6 files changed, 169 insertions(+), 27 deletions(-) diff --git a/example/node/index.js b/example/node/index.js index 31dc98d..c2d7a05 100644 --- a/example/node/index.js +++ b/example/node/index.js @@ -1,17 +1,20 @@ const DeviceHive = require(`../../index`); const httpDeviceHive = new DeviceHive({ - login: `dhadmin`, - password: `dhadmin_#911`, + // login: `dhadmin`, + // password: `dhadmin_#911`, + accessToken: "eyJhbGciOiJIUzI1NiJ9.eyJwYXlsb2FkIjp7ImEiOlswXSwiZSI6MTUxOTM5ODgxNjg5NCwidCI6MSwidSI6MSwibiI6WyIqIl0sImR0IjpbIioiXX19.cMQ5biZFHZMiCWZtdZAcT8Sb4yqG6h9Jj-Ht1yKydIM", mainServiceURL: 'http://localhost:8080/dh/rest', authServiceURL: 'http://localhost:8090/dh/rest', pluginServiceURL: 'http://localhost:8110/dh/rest' }); const wsDeviceHive = new DeviceHive({ - login: `dhadmin`, - password: `dhadmin_#911`, - mainServiceURL: 'ws://localhost:8080/dh/websocket' + // login: `dhadmin`, + // password: `dhadmin_#911`, + accessToken: "eyJhbGciOiJIUzI1NiJ9.eyJwYXlsb2FkIjp7ImEiOlswXSwiZSI6MTUxOTQwNDUyMTA5OSwidCI6MSwidSI6MSwibiI6WyIqIl0sImR0IjpbIioiXX19.P3MIy194dUgTM3U--KvPG7yc2pNgsEOABIY8Y5xXdGE", + mainServiceURL: 'ws://localhost:8080/dh/websocket', + autoUpdateSession: true }); const DeviceListQuery = DeviceHive.models.query.DeviceListQuery; @@ -27,18 +30,22 @@ const networkListQuery = new NetworkListQuery(); void async function start () { try { - await httpDeviceHive.connect(); + // await httpDeviceHive.connect(); await wsDeviceHive.connect(); - { - const {accessToken, refreshToken} = await httpDeviceHive.token.login('dhadmin', 'dhadmin_#911'); - console.log({accessToken, refreshToken}); - console.log(await httpDeviceHive.device.list(deviceListQuery)); - console.log(await httpDeviceHive.deviceType.list(deviceTypeListQuery)); - console.log(await httpDeviceHive.network.list(networkListQuery)); - console.log(await httpDeviceHive.network.list(networkListQuery)); - console.log(await httpDeviceHive.token.refresh(refreshToken)); - } + // { + // const {accessToken, refreshToken} = await httpDeviceHive.token.login('dhadmin', 'dhadmin_#911'); + // console.log({accessToken, refreshToken}); + // console.log(await httpDeviceHive.device.list(deviceListQuery)); + // console.log(await httpDeviceHive.deviceType.list(deviceTypeListQuery)); + // console.log(await httpDeviceHive.network.list(networkListQuery)); + // console.log(await httpDeviceHive.network.list(networkListQuery)); + // console.log(await httpDeviceHive.token.refresh(refreshToken)); + // + // setTimeout(async () => { + // console.log(await httpDeviceHive.network.list(networkListQuery)); + // }, 60000); + // } { const {accessToken, refreshToken} = await wsDeviceHive.token.login('dhadmin', 'dhadmin_#911'); diff --git a/package-lock.json b/package-lock.json index 8112900..a44acb9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1000,6 +1000,11 @@ "integrity": "sha512-dwVUVIXsBZXwTuwnXI9RK8sBmgq09NDHzyR9SAph9eqk76gKK2JSQmZARC2zRC81JC2QTtxD0ARU5qTS25gIGw==", "dev": true }, + "base64url": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/base64url/-/base64url-2.0.0.tgz", + "integrity": "sha1-6sFuA+oUOO/5Qj1puqNiYu0fcLs=" + }, "big.js": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/big.js/-/big.js-3.2.0.tgz", @@ -1349,6 +1354,11 @@ "ieee754": "1.1.8" } }, + "buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=" + }, "buffer-xor": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", @@ -1927,6 +1937,15 @@ } } }, + "ecdsa-sig-formatter": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.9.tgz", + "integrity": "sha1-S8kmJ07Dtau1AW5+HWCSGsJisqE=", + "requires": { + "base64url": "2.0.0", + "safe-buffer": "5.1.1" + } + }, "electron-to-chromium": { "version": "1.3.33", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.33.tgz", @@ -2714,6 +2733,51 @@ "integrity": "sha1-P02uSpH6wxX3EGL4UhzCOfE2YoA=", "dev": true }, + "jsonwebtoken": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.1.1.tgz", + "integrity": "sha512-+ijVOtfLMlCII8LJkvabaKX3+8tGrGjiCTfzoed2D1b/ebKTO1hIYBQUJHbd9dJ9Fa4kH+dhYEd1qDwyzDLUUw==", + "requires": { + "jws": "3.1.4", + "lodash.includes": "4.3.0", + "lodash.isboolean": "3.0.3", + "lodash.isinteger": "4.0.4", + "lodash.isnumber": "3.0.3", + "lodash.isplainobject": "4.0.6", + "lodash.isstring": "4.0.1", + "lodash.once": "4.1.1", + "ms": "2.1.1", + "xtend": "4.0.1" + }, + "dependencies": { + "ms": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", + "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" + } + } + }, + "jwa": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.1.5.tgz", + "integrity": "sha1-oFUs4CIHQs1S4VN3SjKQXDDnVuU=", + "requires": { + "base64url": "2.0.0", + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.9", + "safe-buffer": "5.1.1" + } + }, + "jws": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.1.4.tgz", + "integrity": "sha1-+ei5M46KhHJ31kRLFGT2GIDgUKI=", + "requires": { + "base64url": "2.0.0", + "jwa": "1.1.5", + "safe-buffer": "5.1.1" + } + }, "kind-of": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", @@ -2788,12 +2852,47 @@ "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", "dev": true }, + "lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8=" + }, + "lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY=" + }, + "lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha1-YZwK89A/iwTDH1iChAt3sRzWg0M=" + }, + "lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w=" + }, + "lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=" + }, + "lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=" + }, "lodash.memoize": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-3.0.4.tgz", "integrity": "sha1-LcvSwofLwKVcxCMovQxzYVDVPj8=", "dev": true }, + "lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w=" + }, "loose-envify": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.3.1.tgz", @@ -3571,8 +3670,7 @@ "safe-buffer": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", - "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==", - "dev": true + "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==" }, "scope-analyzer": { "version": "1.3.0", @@ -4122,8 +4220,7 @@ "xtend": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", - "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", - "dev": true + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=" } } } diff --git a/package.json b/package.json index d99288b..de663c7 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,7 @@ "license": "Apache-2.0", "dependencies": { "isomorphic-fetch": "^2.2.1", + "jsonwebtoken": "^8.1.1", "query-string": "^5.1.0", "string-template": "^1.0.0", "universal-websocket-client": "^1.0.1" diff --git a/src/ApiStrategy.js b/src/ApiStrategy.js index ec8db4e..6c5d12a 100644 --- a/src/ApiStrategy.js +++ b/src/ApiStrategy.js @@ -83,7 +83,13 @@ class ApiStrategy extends EventEmitter { } return me.strategy.send(sendData) - .then((response) => API.normalizeResponse(me.strategy.type, key, response)); + .then((response) => API.normalizeResponse(me.strategy.type, key, response)) + .catch(error => { + if (error === `Token expired`) { + } else { + throw error; + } + }); } } diff --git a/src/DeviceHive.js b/src/DeviceHive.js index 7cabbf2..958469c 100644 --- a/src/DeviceHive.js +++ b/src/DeviceHive.js @@ -1,3 +1,4 @@ +const Utils = require(`./utils/Utils`); const EventEmitter = require('events'); const APIStrategy = require('./ApiStrategy'); const InfoAPI = require('./controllers/ServerInfoAPI'); @@ -98,7 +99,7 @@ class DeviceHive extends EventEmitter { * @param {string} [options.authServiceURL] - Auth Service URL (required only for http) * @param {string} [options.pluginServiceURL] - Alug inServi ceURL (required only for http) */ - constructor({ accessToken, refreshToken, login, password, mainServiceURL, authServiceURL, pluginServiceURL }) { + constructor({ mainServiceURL, authServiceURL, pluginServiceURL, accessToken, refreshToken, login, password, autoUpdateSession }) { super(); const me = this; @@ -107,6 +108,7 @@ class DeviceHive extends EventEmitter { me.refreshToken = refreshToken; me.login = login; me.password = password; + me.autoUpdateSession = autoUpdateSession; me.strategy = new APIStrategy({ mainServiceURL, authServiceURL, pluginServiceURL }); @@ -130,19 +132,32 @@ class DeviceHive extends EventEmitter { * Connect to the DeviceHive service * @returns {Promise} */ - async connect() { + async connect({ accessToken, refreshToken, login, password } = {}) { const me = this; + me.accessToken = accessToken || me.accessToken; + me.refreshToken = refreshToken || me.refreshToken; + me.login = login || me.login; + me.password = password || me.password; + if (me.accessToken || me.refreshToken || (me.login && me.password)) { try { - if (me.accessToken) { - await me.strategy.authorize(me.accessToken); + if (me.login && me.password) { + const { accessToken } = await me.token.login(me.login, me.password); + await me.strategy.authorize(accessToken); } else if (me.refreshToken) { const accessToken = await me.token.refresh(me.refreshToken); await me.strategy.authorize(accessToken); - } else if (me.login && me.password) { - const { accessToken } = await me.token.login(me.login, me.password); - await me.strategy.authorize(accessToken); + } else if (me.accessToken) { + await me.strategy.authorize(me.accessToken); + + if (me.autoUpdateSession === true) { + const { accessToken, refreshToken } = await me.token.createUserToken( + Utils.createUserTokenFromJWT(me.accessToken)); + + me.accessToken = accessToken; + me.refreshToken = refreshToken; + } } } catch (error) { throw new InvalidCredentialsError(); diff --git a/src/utils/Utils.js b/src/utils/Utils.js index 7f99d1b..303fa54 100644 --- a/src/utils/Utils.js +++ b/src/utils/Utils.js @@ -1,3 +1,7 @@ +const jwt = require(`jsonwebtoken`); +const UserToken = require(`../models/UserToken`); + + /** * Utils */ @@ -25,6 +29,18 @@ class Utils { return `${firstPart}${secondPart}`; } + + static createUserTokenFromJWT(jwtToken) { + const tokenPayload = jwt.decode(jwtToken).payload; + + return new UserToken({ + userId: tokenPayload.u, + actions: tokenPayload.a, + networkIds: tokenPayload.n, + deviceTypeIds: tokenPayload.dt, + expiration: tokenPayload.e + }); + } } From 08703885cf8e0f9973e838ee559d81aefb98ef90 Mon Sep 17 00:00:00 2001 From: itrambovetskiy Date: Mon, 26 Feb 2018 15:08:41 +0200 Subject: [PATCH 06/22] Autoupdate session --- example/node/index.js | 40 +++---- package-lock.json | 108 ++---------------- package.json | 2 +- src/ApiStrategy.js | 7 +- src/DeviceHive.js | 49 +++++--- src/controllers/transportResolvers/ApiMap.js | 10 +- .../transportResolvers/HttpApiResolver.js | 5 +- src/error/InvalidCredentialsError.js | 4 +- src/transports/HTTP.js | 10 +- src/utils/Utils.js | 12 +- .../controllers/ConfigurationAPI.spec.js | 2 +- test/integration/controllers/Device.spec.js | 2 +- .../controllers/DeviceCommandAPI.spec.js | 4 +- .../controllers/DeviceNotificationAPI.spec.js | 6 +- .../controllers/DeviceTypeAPI.spec.js | 2 +- .../controllers/NetworkAPI.spec.js | 2 +- .../integration/controllers/PluginAPI.spec.js | 2 +- .../controllers/ServerInfoAPI.spec.js | 2 +- test/integration/controllers/TokenAPI.spec.js | 2 +- test/integration/controllers/UserAPI.spec.js | 4 +- 20 files changed, 104 insertions(+), 171 deletions(-) diff --git a/example/node/index.js b/example/node/index.js index c2d7a05..475cbe0 100644 --- a/example/node/index.js +++ b/example/node/index.js @@ -1,18 +1,19 @@ const DeviceHive = require(`../../index`); + const httpDeviceHive = new DeviceHive({ - // login: `dhadmin`, - // password: `dhadmin_#911`, - accessToken: "eyJhbGciOiJIUzI1NiJ9.eyJwYXlsb2FkIjp7ImEiOlswXSwiZSI6MTUxOTM5ODgxNjg5NCwidCI6MSwidSI6MSwibiI6WyIqIl0sImR0IjpbIioiXX19.cMQ5biZFHZMiCWZtdZAcT8Sb4yqG6h9Jj-Ht1yKydIM", + login: `dhadmin`, + password: `dhadmin_#911`, + accessToken: "eyJhbGciOiJIUzI1NiJ9.eyJwYXlsb2FkIjp7ImEiOlswXSwiZSI6MTUxOTY1MDIxMDgwNSwidCI6MSwidSI6MSwibiI6WyIqIl0sImR0IjpbIioiXX19.8MX7MiQeKmKCUGkNSqce1xCUTVBYX6GQKqgAwGvHB9Y", mainServiceURL: 'http://localhost:8080/dh/rest', authServiceURL: 'http://localhost:8090/dh/rest', pluginServiceURL: 'http://localhost:8110/dh/rest' }); const wsDeviceHive = new DeviceHive({ - // login: `dhadmin`, - // password: `dhadmin_#911`, - accessToken: "eyJhbGciOiJIUzI1NiJ9.eyJwYXlsb2FkIjp7ImEiOlswXSwiZSI6MTUxOTQwNDUyMTA5OSwidCI6MSwidSI6MSwibiI6WyIqIl0sImR0IjpbIioiXX19.P3MIy194dUgTM3U--KvPG7yc2pNgsEOABIY8Y5xXdGE", + login: `dhadmin`, + password: `dhadmin_#911`, + accessToken: "eyJhbGciOiJIUzI1NiJ9.eyJwYXlsb2FkIjp7ImEiOlswXSwiZSI6MTUxOTY0OTczMDgwNSwidCI6MSwidSI6MSwibiI6WyIqIl0sImR0IjpbIioiXX19.3Kb1Lkqza0VzG8gsX2tlp5B5BcL2w55gVmMM1aMsDbY", mainServiceURL: 'ws://localhost:8080/dh/websocket', autoUpdateSession: true }); @@ -30,22 +31,18 @@ const networkListQuery = new NetworkListQuery(); void async function start () { try { - // await httpDeviceHive.connect(); + await httpDeviceHive.connect(); await wsDeviceHive.connect(); - // { - // const {accessToken, refreshToken} = await httpDeviceHive.token.login('dhadmin', 'dhadmin_#911'); - // console.log({accessToken, refreshToken}); - // console.log(await httpDeviceHive.device.list(deviceListQuery)); - // console.log(await httpDeviceHive.deviceType.list(deviceTypeListQuery)); - // console.log(await httpDeviceHive.network.list(networkListQuery)); - // console.log(await httpDeviceHive.network.list(networkListQuery)); - // console.log(await httpDeviceHive.token.refresh(refreshToken)); - // - // setTimeout(async () => { - // console.log(await httpDeviceHive.network.list(networkListQuery)); - // }, 60000); - // } + { + const {accessToken, refreshToken} = await httpDeviceHive.token.login('dhadmin', 'dhadmin_#911'); + console.log({accessToken, refreshToken}); + console.log(await httpDeviceHive.device.list(deviceListQuery)); + console.log(await httpDeviceHive.deviceType.list(deviceTypeListQuery)); + console.log(await httpDeviceHive.network.list(networkListQuery)); + console.log(await httpDeviceHive.network.list(networkListQuery)); + console.log(await httpDeviceHive.token.refresh(refreshToken)); + } { const {accessToken, refreshToken} = await wsDeviceHive.token.login('dhadmin', 'dhadmin_#911'); @@ -55,7 +52,10 @@ void async function start () { console.log(await wsDeviceHive.network.list(networkListQuery)); console.log(await wsDeviceHive.token.refresh(refreshToken)); } + } catch (error) { console.warn(error); } + + process.exit(1); }(); \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index a44acb9..20ce356 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1000,11 +1000,6 @@ "integrity": "sha512-dwVUVIXsBZXwTuwnXI9RK8sBmgq09NDHzyR9SAph9eqk76gKK2JSQmZARC2zRC81JC2QTtxD0ARU5qTS25gIGw==", "dev": true }, - "base64url": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/base64url/-/base64url-2.0.0.tgz", - "integrity": "sha1-6sFuA+oUOO/5Qj1puqNiYu0fcLs=" - }, "big.js": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/big.js/-/big.js-3.2.0.tgz", @@ -1354,11 +1349,6 @@ "ieee754": "1.1.8" } }, - "buffer-equal-constant-time": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", - "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=" - }, "buffer-xor": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", @@ -1937,15 +1927,6 @@ } } }, - "ecdsa-sig-formatter": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.9.tgz", - "integrity": "sha1-S8kmJ07Dtau1AW5+HWCSGsJisqE=", - "requires": { - "base64url": "2.0.0", - "safe-buffer": "5.1.1" - } - }, "electron-to-chromium": { "version": "1.3.33", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.33.tgz", @@ -2733,50 +2714,10 @@ "integrity": "sha1-P02uSpH6wxX3EGL4UhzCOfE2YoA=", "dev": true }, - "jsonwebtoken": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.1.1.tgz", - "integrity": "sha512-+ijVOtfLMlCII8LJkvabaKX3+8tGrGjiCTfzoed2D1b/ebKTO1hIYBQUJHbd9dJ9Fa4kH+dhYEd1qDwyzDLUUw==", - "requires": { - "jws": "3.1.4", - "lodash.includes": "4.3.0", - "lodash.isboolean": "3.0.3", - "lodash.isinteger": "4.0.4", - "lodash.isnumber": "3.0.3", - "lodash.isplainobject": "4.0.6", - "lodash.isstring": "4.0.1", - "lodash.once": "4.1.1", - "ms": "2.1.1", - "xtend": "4.0.1" - }, - "dependencies": { - "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" - } - } - }, - "jwa": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.1.5.tgz", - "integrity": "sha1-oFUs4CIHQs1S4VN3SjKQXDDnVuU=", - "requires": { - "base64url": "2.0.0", - "buffer-equal-constant-time": "1.0.1", - "ecdsa-sig-formatter": "1.0.9", - "safe-buffer": "5.1.1" - } - }, - "jws": { - "version": "3.1.4", - "resolved": "https://registry.npmjs.org/jws/-/jws-3.1.4.tgz", - "integrity": "sha1-+ei5M46KhHJ31kRLFGT2GIDgUKI=", - "requires": { - "base64url": "2.0.0", - "jwa": "1.1.5", - "safe-buffer": "5.1.1" - } + "jwt-decode": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-2.2.0.tgz", + "integrity": "sha1-fYa9VmefWM5qhHBKZX3TkruoGnk=" }, "kind-of": { "version": "3.2.2", @@ -2852,47 +2793,12 @@ "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", "dev": true }, - "lodash.includes": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", - "integrity": "sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8=" - }, - "lodash.isboolean": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", - "integrity": "sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY=" - }, - "lodash.isinteger": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", - "integrity": "sha1-YZwK89A/iwTDH1iChAt3sRzWg0M=" - }, - "lodash.isnumber": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", - "integrity": "sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w=" - }, - "lodash.isplainobject": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", - "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=" - }, - "lodash.isstring": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", - "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=" - }, "lodash.memoize": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-3.0.4.tgz", "integrity": "sha1-LcvSwofLwKVcxCMovQxzYVDVPj8=", "dev": true }, - "lodash.once": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", - "integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w=" - }, "loose-envify": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.3.1.tgz", @@ -3670,7 +3576,8 @@ "safe-buffer": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", - "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==" + "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==", + "dev": true }, "scope-analyzer": { "version": "1.3.0", @@ -4220,7 +4127,8 @@ "xtend": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", - "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=" + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true } } } diff --git a/package.json b/package.json index de663c7..f7d3b85 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,7 @@ "license": "Apache-2.0", "dependencies": { "isomorphic-fetch": "^2.2.1", - "jsonwebtoken": "^8.1.1", + "jwt-decode": "^2.2.0", "query-string": "^5.1.0", "string-template": "^1.0.0", "universal-websocket-client": "^1.0.1" diff --git a/src/ApiStrategy.js b/src/ApiStrategy.js index 6c5d12a..ad0c299 100644 --- a/src/ApiStrategy.js +++ b/src/ApiStrategy.js @@ -40,6 +40,8 @@ class ApiStrategy extends EventEmitter { const me = this; + me.reconnectionHandler = null; + me.urlsMap = new Map(); me.urlsMap.set(API.MAIN_BASE, mainServiceURL); @@ -85,7 +87,10 @@ class ApiStrategy extends EventEmitter { return me.strategy.send(sendData) .then((response) => API.normalizeResponse(me.strategy.type, key, response)) .catch(error => { - if (error === `Token expired`) { + if (error === `Token expired` && me.reconnectionHandler) { + return me.reconnectionHandler() + .then(() => me.strategy.send(sendData)) + .then((response) => API.normalizeResponse(me.strategy.type, key, response)); } else { throw error; } diff --git a/src/DeviceHive.js b/src/DeviceHive.js index 958469c..283e0de 100644 --- a/src/DeviceHive.js +++ b/src/DeviceHive.js @@ -135,32 +135,45 @@ class DeviceHive extends EventEmitter { async connect({ accessToken, refreshToken, login, password } = {}) { const me = this; - me.accessToken = accessToken || me.accessToken; - me.refreshToken = refreshToken || me.refreshToken; - me.login = login || me.login; - me.password = password || me.password; + if (!accessToken && !refreshToken && !(login && password)) { + accessToken = accessToken || me.accessToken; + refreshToken = refreshToken || me.refreshToken; + login = login || me.login; + password = password || me.password; + } - if (me.accessToken || me.refreshToken || (me.login && me.password)) { + if (accessToken || refreshToken || (login && password)) { try { - if (me.login && me.password) { - const { accessToken } = await me.token.login(me.login, me.password); + if (login && password) { + const { accessToken, refreshToken } = await me.token.login(login, password); + + await me.strategy.authorize(accessToken); + + me.accessToken = accessToken; + me.refreshToken = refreshToken; + } else if (refreshToken) { + const { accessToken } = await me.token.refresh(refreshToken); + await me.strategy.authorize(accessToken); - } else if (me.refreshToken) { - const accessToken = await me.token.refresh(me.refreshToken); + + me.accessToken = accessToken; + me.refreshToken = refreshToken; + } else if (accessToken) { await me.strategy.authorize(accessToken); - } else if (me.accessToken) { - await me.strategy.authorize(me.accessToken); - if (me.autoUpdateSession === true) { - const { accessToken, refreshToken } = await me.token.createUserToken( - Utils.createUserTokenFromJWT(me.accessToken)); + me.accessToken = accessToken; + } + + if (me.autoUpdateSession === true) { + const userTokens = await me.token.createUserToken( + Utils.createUserTokenFromJWT(me.accessToken)); - me.accessToken = accessToken; - me.refreshToken = refreshToken; - } + me.accessToken = userTokens.accessToken; + me.refreshToken = userTokens.refreshToken; + me.strategy.reconnectionHandler = () => me.connect({ refreshToken: me.refreshToken }); } } catch (error) { - throw new InvalidCredentialsError(); + throw new InvalidCredentialsError(error); } } else { throw new NoAuthCredentialsError(); diff --git a/src/controllers/transportResolvers/ApiMap.js b/src/controllers/transportResolvers/ApiMap.js index 56138d1..25bf7f5 100644 --- a/src/controllers/transportResolvers/ApiMap.js +++ b/src/controllers/transportResolvers/ApiMap.js @@ -156,15 +156,15 @@ class ApiMap { } -apiMap.set(ApiMap.login, { http: { method: 'POST', uri: '/token', base: ApiMap.AUTH_BASE }, ws: { action: 'token', response: [`accessToken`, `refreshToken`] } }); +apiMap.set(ApiMap.login, { http: { method: 'POST', uri: '/token', base: ApiMap.AUTH_BASE, noAuth: true }, ws: { action: 'token', response: [`accessToken`, `refreshToken`] } }); apiMap.set(ApiMap.createUserToken, { http: { method: 'POST', uri: '/token/create', base: ApiMap.AUTH_BASE }, ws: { action: 'token/create', bodyKey: 'payload', response: [`accessToken`, `refreshToken`] } }); apiMap.set(ApiMap.createPluginToken, { http: { method: 'POST', uri: '/token/plugin/create', base: ApiMap.AUTH_BASE } }); -apiMap.set(ApiMap.refreshToken, { http: { method: 'POST', uri: '/token/refresh', base: ApiMap.AUTH_BASE }, ws: { action: 'token/refresh', response: [`accessToken`] } }); +apiMap.set(ApiMap.refreshToken, { http: { method: 'POST', uri: '/token/refresh', base: ApiMap.AUTH_BASE, noAuth: true }, ws: { action: 'token/refresh', response: [`accessToken`] } }); apiMap.set(ApiMap.authenticatePlugin, { http: { method: 'GET', uri: '/token/plugin/authenticate', base: ApiMap.AUTH_BASE } }); -apiMap.set(ApiMap.getServerInfo, { http: { method: 'GET', uri: '/info', base: ApiMap.MAIN_BASE }, ws: { action: 'server/info', response: { bodyKey: `info` } } }); -apiMap.set(ApiMap.getCacheInfo, { http: { method: 'GET', uri: '/info/cache', base: ApiMap.MAIN_BASE } }); -apiMap.set(ApiMap.getClusterInfo, { http: { method: 'GET', uri: '/info/config/cluster', base: ApiMap.MAIN_BASE }, ws: { action: 'cluster/info', response: { bodyKey: `clusterInfo` } } }); +apiMap.set(ApiMap.getServerInfo, { http: { method: 'GET', uri: '/info', base: ApiMap.MAIN_BASE, noAuth: true }, ws: { action: 'server/info', response: { bodyKey: `info` } } }); +apiMap.set(ApiMap.getCacheInfo, { http: { method: 'GET', uri: '/info/cache', base: ApiMap.MAIN_BASE, noAuth: true } }); +apiMap.set(ApiMap.getClusterInfo, { http: { method: 'GET', uri: '/info/config/cluster', base: ApiMap.MAIN_BASE, noAuth: true }, ws: { action: 'cluster/info', response: { bodyKey: `clusterInfo` } } }); apiMap.set(ApiMap.getConfiguration, { http: { method: 'GET', uri: '/configuration/{name}', base: ApiMap.MAIN_BASE }, ws: { action: 'configuration/get', response: { bodyKey: `configuration` } } }); apiMap.set(ApiMap.putConfiguration, { http: { method: 'PUT', uri: '/configuration/{name}', base: ApiMap.MAIN_BASE }, ws: { action: 'configuration/put', response: { bodyKey: `configuration` } } }); diff --git a/src/controllers/transportResolvers/HttpApiResolver.js b/src/controllers/transportResolvers/HttpApiResolver.js index b207d7b..26c1213 100644 --- a/src/controllers/transportResolvers/HttpApiResolver.js +++ b/src/controllers/transportResolvers/HttpApiResolver.js @@ -54,7 +54,7 @@ class HttpApiResolver { * @param {boolean} options.subscription * @param {boolean} options.unsubscription */ - constructor({ method, uri, base, subscription, unsubscription }) { + constructor({ method, uri, base, subscription, unsubscription, noAuth }) { const me = this; me.method = method; @@ -62,6 +62,7 @@ class HttpApiResolver { me.base = base; me.subscription = subscription; me.unsubscription = unsubscription; + me.noAuth = noAuth; } /** @@ -76,6 +77,7 @@ class HttpApiResolver { if (me.unsubscription === true) { result = { + noAuth: me.noAuth, unsubscription: me.unsubscription, body: { subscriptionId: parameters.subscriptionId @@ -83,6 +85,7 @@ class HttpApiResolver { }; } else { result = { + noAuth: me.noAuth, method: me.method, endpoint: HttpApiResolver.buildUrl(me.uri, parameters), base: me.base, diff --git a/src/error/InvalidCredentialsError.js b/src/error/InvalidCredentialsError.js index d0fd1d6..a93f4a6 100644 --- a/src/error/InvalidCredentialsError.js +++ b/src/error/InvalidCredentialsError.js @@ -6,10 +6,10 @@ class InvalidCredentialsError extends Error { /** * Creates new InvalidCredentialsError */ - constructor() { + constructor(message) { super(); - this.message = `Invalid credentials error during attempt to authenticate.`; + this.message = `Invalid credentials error during attempt to authenticate. Error: ${message}`; } } diff --git a/src/transports/HTTP.js b/src/transports/HTTP.js index 058c55d..d5ab869 100644 --- a/src/transports/HTTP.js +++ b/src/transports/HTTP.js @@ -37,7 +37,7 @@ class HTTP extends Transport { /** * Rest API send method */ - send({ endpoint, method, body, subscription, unsubscription }) { + send({ endpoint, method, body, subscription, unsubscription, noAuth }) { const me = this; if (subscription === true) { @@ -62,7 +62,7 @@ class HTTP extends Transport { return Promise.resolve({ status: `No such subscription` }) } } else { - return fetch(endpoint, { headers: me._getHeaders(), method: method, body: JSON.stringify(body) }) + return fetch(endpoint, { headers: me._getHeaders(noAuth), method: method, body: JSON.stringify(body) }) .then(response => response.text()) .then(responseText => { return responseText ? JSON.parse(responseText) : responseText @@ -110,15 +110,15 @@ class HTTP extends Transport { * @returns {Object} * @private */ - _getHeaders() { + _getHeaders(noAuth = false) { const me = this; const headers = { "Content-type": `application/json`, "Accept": `application/json` }; - if (me.token) { - headers[`Authorization`] = `Bearer ${me.token}`; + if (me.token && !noAuth) { + headers.Authorization = `Bearer ${me.token}`; } return headers; diff --git a/src/utils/Utils.js b/src/utils/Utils.js index 303fa54..5c614c1 100644 --- a/src/utils/Utils.js +++ b/src/utils/Utils.js @@ -1,4 +1,4 @@ -const jwt = require(`jsonwebtoken`); +const jwtDecode = require(`jwt-decode`); const UserToken = require(`../models/UserToken`); @@ -30,15 +30,19 @@ class Utils { return `${firstPart}${secondPart}`; } + /** + * Creates UserToken from jwt + * @param jwtToken + * @returns {UserToken} + */ static createUserTokenFromJWT(jwtToken) { - const tokenPayload = jwt.decode(jwtToken).payload; + const tokenPayload = jwtDecode(jwtToken).payload; return new UserToken({ userId: tokenPayload.u, actions: tokenPayload.a, networkIds: tokenPayload.n, - deviceTypeIds: tokenPayload.dt, - expiration: tokenPayload.e + deviceTypeIds: tokenPayload.dt }); } } diff --git a/test/integration/controllers/ConfigurationAPI.spec.js b/test/integration/controllers/ConfigurationAPI.spec.js index d4bf98a..508479e 100644 --- a/test/integration/controllers/ConfigurationAPI.spec.js +++ b/test/integration/controllers/ConfigurationAPI.spec.js @@ -8,7 +8,7 @@ const events = new EventEmitter(); const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); -const wsDeviceHive = new DeviceHive(config.server.ws) +const wsDeviceHive = new DeviceHive(config.server.ws); const testConfigurations = [ diff --git a/test/integration/controllers/Device.spec.js b/test/integration/controllers/Device.spec.js index 72b4512..e0329d7 100644 --- a/test/integration/controllers/Device.spec.js +++ b/test/integration/controllers/Device.spec.js @@ -8,7 +8,7 @@ const events = new EventEmitter(); const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); -const wsDeviceHive = new DeviceHive(config.server.ws) +const wsDeviceHive = new DeviceHive(config.server.ws); const testDevices = [ diff --git a/test/integration/controllers/DeviceCommandAPI.spec.js b/test/integration/controllers/DeviceCommandAPI.spec.js index f139351..eba276c 100644 --- a/test/integration/controllers/DeviceCommandAPI.spec.js +++ b/test/integration/controllers/DeviceCommandAPI.spec.js @@ -8,9 +8,9 @@ const events = new EventEmitter(); const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); -const wsDeviceHive = new DeviceHive(config.server.ws) +const wsDeviceHive = new DeviceHive(config.server.ws); -const deviceId = 'e50d6085-2aba-48e9-b1c3-73c673e414be2'; +const deviceId = 'e50d6085-2aba-48e9-b1c3-73c673e414be'; const testDeviceCommands = [ { diff --git a/test/integration/controllers/DeviceNotificationAPI.spec.js b/test/integration/controllers/DeviceNotificationAPI.spec.js index fb97e36..c4d42a8 100644 --- a/test/integration/controllers/DeviceNotificationAPI.spec.js +++ b/test/integration/controllers/DeviceNotificationAPI.spec.js @@ -8,9 +8,9 @@ const events = new EventEmitter(); const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); -const wsDeviceHive = new DeviceHive(config.server.ws) +const wsDeviceHive = new DeviceHive(config.server.ws); -const deviceId = 'e50d6085-2aba-48e9-b1c3-73c673e414be2'; +const deviceId = 'e50d6085-2aba-48e9-b1c3-73c673e414be'; const testDeviceNotifications = [ { @@ -28,7 +28,7 @@ const testDeviceNotifications = [ parameters: { jsonString: 'jsonString' } - }, + } ]; describe('NotificationAPI', () => { diff --git a/test/integration/controllers/DeviceTypeAPI.spec.js b/test/integration/controllers/DeviceTypeAPI.spec.js index 82cf932..cb6412d 100644 --- a/test/integration/controllers/DeviceTypeAPI.spec.js +++ b/test/integration/controllers/DeviceTypeAPI.spec.js @@ -8,7 +8,7 @@ const events = new EventEmitter(); const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); -const wsDeviceHive = new DeviceHive(config.server.ws) +const wsDeviceHive = new DeviceHive(config.server.ws); const testDeviceTypes = [ diff --git a/test/integration/controllers/NetworkAPI.spec.js b/test/integration/controllers/NetworkAPI.spec.js index 12f6a6b..2ce51e1 100644 --- a/test/integration/controllers/NetworkAPI.spec.js +++ b/test/integration/controllers/NetworkAPI.spec.js @@ -8,7 +8,7 @@ const events = new EventEmitter(); const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); -const wsDeviceHive = new DeviceHive(config.server.ws) +const wsDeviceHive = new DeviceHive(config.server.ws); const testNetworks = [ diff --git a/test/integration/controllers/PluginAPI.spec.js b/test/integration/controllers/PluginAPI.spec.js index fab0122..83bd822 100644 --- a/test/integration/controllers/PluginAPI.spec.js +++ b/test/integration/controllers/PluginAPI.spec.js @@ -8,7 +8,7 @@ const events = new EventEmitter(); const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); -const wsDeviceHive = new DeviceHive(config.server.ws) +const wsDeviceHive = new DeviceHive(config.server.ws); const testPlugins = [ diff --git a/test/integration/controllers/ServerInfoAPI.spec.js b/test/integration/controllers/ServerInfoAPI.spec.js index 4b21d60..0bc96df 100644 --- a/test/integration/controllers/ServerInfoAPI.spec.js +++ b/test/integration/controllers/ServerInfoAPI.spec.js @@ -8,7 +8,7 @@ const events = new EventEmitter(); const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); -const wsDeviceHive = new DeviceHive(config.server.ws) +const wsDeviceHive = new DeviceHive(config.server.ws); describe('ServerInfoAPI', () => { diff --git a/test/integration/controllers/TokenAPI.spec.js b/test/integration/controllers/TokenAPI.spec.js index d6e7aab..60f2fc3 100644 --- a/test/integration/controllers/TokenAPI.spec.js +++ b/test/integration/controllers/TokenAPI.spec.js @@ -8,7 +8,7 @@ const events = new EventEmitter(); const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); -const wsDeviceHive = new DeviceHive(config.server.ws) +const wsDeviceHive = new DeviceHive(config.server.ws); const testToken = { diff --git a/test/integration/controllers/UserAPI.spec.js b/test/integration/controllers/UserAPI.spec.js index 088c911..5d81fc7 100644 --- a/test/integration/controllers/UserAPI.spec.js +++ b/test/integration/controllers/UserAPI.spec.js @@ -8,7 +8,7 @@ const events = new EventEmitter(); const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); -const wsDeviceHive = new DeviceHive(config.server.ws) +const wsDeviceHive = new DeviceHive(config.server.ws); const testUsers = [ @@ -159,7 +159,7 @@ describe('UserAPI', () => { login: 'login', loginPattern: 'loginPattern', role: '1', - status: '1', + status: '1' }); Promise.all([httpDeviceHive.user.count(userListQuery), wsDeviceHive.user.count(userListQuery)]) From 69b80da21ff9f8daef412dad7666ebc640e61053 Mon Sep 17 00:00:00 2001 From: itrambovetskiy Date: Mon, 26 Feb 2018 15:11:12 +0200 Subject: [PATCH 07/22] Packages update --- package-lock.json | 37 +++++++++++++++++-------------------- package.json | 4 ++-- 2 files changed, 19 insertions(+), 22 deletions(-) diff --git a/package-lock.json b/package-lock.json index 20ce356..305e6f1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -851,9 +851,9 @@ } }, "babel-loader": { - "version": "8.0.0-beta.0", - "resolved": "https://registry.npmjs.org/babel-loader/-/babel-loader-8.0.0-beta.0.tgz", - "integrity": "sha512-qVXXyIqTrLBH3Ki2VCJog1fUd6qzKUk9lHS34WJPW93Bh0BUvXTFSD5ZkG3a5+Uxxje+RgCk8Y7RyB6zyK9rWw==", + "version": "8.0.0-beta.2", + "resolved": "https://registry.npmjs.org/babel-loader/-/babel-loader-8.0.0-beta.2.tgz", + "integrity": "sha512-P1zch1DvQy3RGmp/1CH78uPg5gTPQQ01S9r6ipCOWVamO0UIC8gnrx7m7LsUsXa470yB6IOZxhtEEwIUclRLNw==", "dev": true, "requires": { "find-cache-dir": "1.0.0", @@ -2267,7 +2267,7 @@ "dev": true, "requires": { "commondir": "1.0.1", - "make-dir": "1.1.0", + "make-dir": "1.2.0", "pkg-dir": "2.0.0" } }, @@ -2818,20 +2818,12 @@ } }, "make-dir": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-1.1.0.tgz", - "integrity": "sha512-0Pkui4wLJ7rxvmfUvs87skoEaxmu0hCUApF8nonzpl7q//FWp9zu8W61Scz4sd/kUiqDxvUhtoam2efDyiBzcA==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-1.2.0.tgz", + "integrity": "sha512-aNUAa4UMg/UougV25bbrU4ZaaKNjJ/3/xnvg/twpmKROPdKZPZ9wGgI0opdZzO8q/zUFawoUuixuOv33eZ61Iw==", "dev": true, "requires": { "pify": "3.0.0" - }, - "dependencies": { - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true - } } }, "md5.js": { @@ -3287,6 +3279,12 @@ "sha.js": "2.4.10" } }, + "pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", + "dev": true + }, "pkg-dir": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-2.0.0.tgz", @@ -4114,14 +4112,13 @@ "dev": true }, "ws": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-4.0.0.tgz", - "integrity": "sha512-QYslsH44bH8O7/W2815u5DpnCpXWpEK44FmaHffNwgJI4JMaSZONgPBTOfrxJ29mXKbXak+LsJ2uAkDTYq2ptQ==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-4.1.0.tgz", + "integrity": "sha512-ZGh/8kF9rrRNffkLFV4AzhvooEclrOH0xaugmqGsIfFgOE/pIz4fMc4Ef+5HSQqTEug2S9JZIWDR47duDSLfaA==", "dev": true, "requires": { "async-limiter": "1.0.0", - "safe-buffer": "5.1.1", - "ultron": "1.1.1" + "safe-buffer": "5.1.1" } }, "xtend": { diff --git a/package.json b/package.json index f7d3b85..686702e 100644 --- a/package.json +++ b/package.json @@ -26,13 +26,13 @@ "@babel/core": "^7.0.0-beta.40", "@babel/preset-env": "^7.0.0-beta.40", "babel-core": "^6.26.0", - "babel-loader": "^8.0.0-beta.0", + "babel-loader": "^8.0.0-beta.2", "babelify": "^8.0.0", "browserify": "^15.2.0", "chai": "^4.1.2", "exorcist": "^1.0.1", "mocha": "^5.0.1", "tinyify": "^2.4.0", - "ws": "^4.0.0" + "ws": "^4.1.0" } } From 6679fac365116f9684cd9bdcc60a5bd750ff65a5 Mon Sep 17 00:00:00 2001 From: itrambovetskiy Date: Mon, 26 Feb 2018 15:23:09 +0200 Subject: [PATCH 08/22] Slight improvements --- src/ApiStrategy.js | 6 +++--- src/DeviceHive.js | 2 +- src/utils/Utils.js | 2 ++ test/unit/controllers/ConfigurationAPI.http.spec.js | 3 ++- test/unit/controllers/ConfigurationAPI.ws.spec.js | 3 ++- test/unit/controllers/DeviceAPI.http.spec.js | 3 ++- test/unit/controllers/DeviceAPI.ws.spec.js | 3 ++- test/unit/controllers/DeviceCommandAPI.http.spec.js | 3 ++- test/unit/controllers/DeviceCommandAPI.ws.spec.js | 3 ++- test/unit/controllers/DeviceNotificationAPI.http.spec.js | 3 ++- test/unit/controllers/DeviceNotificationAPI.ws.spec.js | 3 ++- test/unit/controllers/DeviceTypeAPI.http.spec.js | 3 ++- test/unit/controllers/DeviceTypeAPI.ws.spec.js | 3 ++- test/unit/controllers/NetworkAPI.http.spec.js | 3 ++- test/unit/controllers/NetworkAPI.ws.spec.js | 3 ++- test/unit/controllers/PluginAPI.http.spec.js | 1 + test/unit/controllers/ServerInfoAPI.http.spec.js | 3 ++- test/unit/controllers/ServerInfoAPI.ws.spec.js | 3 ++- test/unit/controllers/TokenAPI.http.spec.js | 3 ++- test/unit/controllers/TokenAPI.ws.spec.js | 3 ++- test/unit/controllers/UserAPI.http.spec.js | 3 ++- test/unit/controllers/UserAPI.ws.spec.js | 3 ++- 22 files changed, 43 insertions(+), 22 deletions(-) diff --git a/src/ApiStrategy.js b/src/ApiStrategy.js index ad0c299..73a0296 100644 --- a/src/ApiStrategy.js +++ b/src/ApiStrategy.js @@ -20,9 +20,9 @@ class ApiStrategy extends EventEmitter { static getType(url) { let result; - if (url.startsWith('http') || url.startsWith('https')) { + if (url.startsWith(HTTP.TYPE)) { result = HTTP; - } else if (url.startsWith('ws') || url.startsWith('wss')) { + } else if (url.startsWith(WS.TYPE)) { result = WS; } else { throw new UnsupportedTransportError(); @@ -87,7 +87,7 @@ class ApiStrategy extends EventEmitter { return me.strategy.send(sendData) .then((response) => API.normalizeResponse(me.strategy.type, key, response)) .catch(error => { - if (error === `Token expired` && me.reconnectionHandler) { + if (error === Utils.TOKEN_EXPIRED_MARK && me.reconnectionHandler) { return me.reconnectionHandler() .then(() => me.strategy.send(sendData)) .then((response) => API.normalizeResponse(me.strategy.type, key, response)); diff --git a/src/DeviceHive.js b/src/DeviceHive.js index 283e0de..e606e23 100644 --- a/src/DeviceHive.js +++ b/src/DeviceHive.js @@ -99,7 +99,7 @@ class DeviceHive extends EventEmitter { * @param {string} [options.authServiceURL] - Auth Service URL (required only for http) * @param {string} [options.pluginServiceURL] - Alug inServi ceURL (required only for http) */ - constructor({ mainServiceURL, authServiceURL, pluginServiceURL, accessToken, refreshToken, login, password, autoUpdateSession }) { + constructor({ mainServiceURL, authServiceURL, pluginServiceURL, accessToken, refreshToken, login, password, autoUpdateSession = true }) { super(); const me = this; diff --git a/src/utils/Utils.js b/src/utils/Utils.js index 5c614c1..102e21c 100644 --- a/src/utils/Utils.js +++ b/src/utils/Utils.js @@ -7,6 +7,8 @@ const UserToken = require(`../models/UserToken`); */ class Utils { + static get TOKEN_EXPIRED_MARK() { return `Token expired`; } + /** * Checks that object is empty * @returns {boolean} - Is object empty diff --git a/test/unit/controllers/ConfigurationAPI.http.spec.js b/test/unit/controllers/ConfigurationAPI.http.spec.js index d26a741..e99c46d 100644 --- a/test/unit/controllers/ConfigurationAPI.http.spec.js +++ b/test/unit/controllers/ConfigurationAPI.http.spec.js @@ -50,7 +50,8 @@ describe('ConfigurationAPI HTTP', () => { login: `dhadmin`, password: `dhadmin_#911`, mainServiceURL: 'http://localhost:3390', - authServiceURL: 'http://localhost:3391' + authServiceURL: 'http://localhost:3391', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/ConfigurationAPI.ws.spec.js b/test/unit/controllers/ConfigurationAPI.ws.spec.js index 8cc4734..072afd1 100644 --- a/test/unit/controllers/ConfigurationAPI.ws.spec.js +++ b/test/unit/controllers/ConfigurationAPI.ws.spec.js @@ -40,7 +40,8 @@ describe('ConfigurationAPI WS', () => { deviceHive = new DeviceHive({ login: `dhadmin`, password: `dhadmin_#911`, - mainServiceURL: 'ws://localhost:4390' + mainServiceURL: 'ws://localhost:4390', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/DeviceAPI.http.spec.js b/test/unit/controllers/DeviceAPI.http.spec.js index 3705d0e..3ab1849 100644 --- a/test/unit/controllers/DeviceAPI.http.spec.js +++ b/test/unit/controllers/DeviceAPI.http.spec.js @@ -50,7 +50,8 @@ describe('DeviceAPI', () => { login: `dhadmin`, password: `dhadmin_#911`, mainServiceURL: 'http://localhost:3390', - authServiceURL: 'http://localhost:3391' + authServiceURL: 'http://localhost:3391', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/DeviceAPI.ws.spec.js b/test/unit/controllers/DeviceAPI.ws.spec.js index 3ae25d4..33cff90 100644 --- a/test/unit/controllers/DeviceAPI.ws.spec.js +++ b/test/unit/controllers/DeviceAPI.ws.spec.js @@ -40,7 +40,8 @@ describe('DeviceAPI WS', () => { deviceHive = new DeviceHive({ login: `dhadmin`, password: `dhadmin_#911`, - mainServiceURL: 'ws://localhost:4390' + mainServiceURL: 'ws://localhost:4390', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/DeviceCommandAPI.http.spec.js b/test/unit/controllers/DeviceCommandAPI.http.spec.js index cabedca..4cf17a6 100644 --- a/test/unit/controllers/DeviceCommandAPI.http.spec.js +++ b/test/unit/controllers/DeviceCommandAPI.http.spec.js @@ -50,7 +50,8 @@ describe('DeviceCommandAPI HTTP', () => { login: `dhadmin`, password: `dhadmin_#911`, mainServiceURL: 'http://localhost:3390', - authServiceURL: 'http://localhost:3391' + authServiceURL: 'http://localhost:3391', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/DeviceCommandAPI.ws.spec.js b/test/unit/controllers/DeviceCommandAPI.ws.spec.js index 364e317..a690828 100644 --- a/test/unit/controllers/DeviceCommandAPI.ws.spec.js +++ b/test/unit/controllers/DeviceCommandAPI.ws.spec.js @@ -40,7 +40,8 @@ describe('DeviceCommandAPI WS', () => { deviceHive = new DeviceHive({ login: `dhadmin`, password: `dhadmin_#911`, - mainServiceURL: 'ws://localhost:4390' + mainServiceURL: 'ws://localhost:4390', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/DeviceNotificationAPI.http.spec.js b/test/unit/controllers/DeviceNotificationAPI.http.spec.js index 9332d71..26fa6fb 100644 --- a/test/unit/controllers/DeviceNotificationAPI.http.spec.js +++ b/test/unit/controllers/DeviceNotificationAPI.http.spec.js @@ -50,7 +50,8 @@ describe('NotificationAPI HTTP', () => { login: `dhadmin`, password: `dhadmin_#911`, mainServiceURL: 'http://localhost:3390', - authServiceURL: 'http://localhost:3391' + authServiceURL: 'http://localhost:3391', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/DeviceNotificationAPI.ws.spec.js b/test/unit/controllers/DeviceNotificationAPI.ws.spec.js index 52558b3..0386e3d 100644 --- a/test/unit/controllers/DeviceNotificationAPI.ws.spec.js +++ b/test/unit/controllers/DeviceNotificationAPI.ws.spec.js @@ -40,7 +40,8 @@ describe('NotificationAPI WS', () => { deviceHive = new DeviceHive({ login: `dhadmin`, password: `dhadmin_#911`, - mainServiceURL: 'ws://localhost:4390' + mainServiceURL: 'ws://localhost:4390', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/DeviceTypeAPI.http.spec.js b/test/unit/controllers/DeviceTypeAPI.http.spec.js index ca56fa0..89c44da 100644 --- a/test/unit/controllers/DeviceTypeAPI.http.spec.js +++ b/test/unit/controllers/DeviceTypeAPI.http.spec.js @@ -50,7 +50,8 @@ describe('DeviceTypeAPI HTTP', () => { login: `dhadmin`, password: `dhadmin_#911`, mainServiceURL: 'http://localhost:3390', - authServiceURL: 'http://localhost:3391' + authServiceURL: 'http://localhost:3391', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/DeviceTypeAPI.ws.spec.js b/test/unit/controllers/DeviceTypeAPI.ws.spec.js index 9d67940..f041ff2 100644 --- a/test/unit/controllers/DeviceTypeAPI.ws.spec.js +++ b/test/unit/controllers/DeviceTypeAPI.ws.spec.js @@ -40,7 +40,8 @@ describe('DeviceTypeAPI WS', () => { deviceHive = new DeviceHive({ login: `dhadmin`, password: `dhadmin_#911`, - mainServiceURL: 'ws://localhost:4390' + mainServiceURL: 'ws://localhost:4390', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/NetworkAPI.http.spec.js b/test/unit/controllers/NetworkAPI.http.spec.js index a60633e..b654370 100644 --- a/test/unit/controllers/NetworkAPI.http.spec.js +++ b/test/unit/controllers/NetworkAPI.http.spec.js @@ -50,7 +50,8 @@ describe('NetworkAPI', () => { login: `dhadmin`, password: `dhadmin_#911`, mainServiceURL: 'http://localhost:3390', - authServiceURL: 'http://localhost:3391' + authServiceURL: 'http://localhost:3391', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/NetworkAPI.ws.spec.js b/test/unit/controllers/NetworkAPI.ws.spec.js index 73f3e8e..a330a88 100644 --- a/test/unit/controllers/NetworkAPI.ws.spec.js +++ b/test/unit/controllers/NetworkAPI.ws.spec.js @@ -40,7 +40,8 @@ describe('NetworkAPI WS', () => { deviceHive = new DeviceHive({ login: `dhadmin`, password: `dhadmin_#911`, - mainServiceURL: 'ws://localhost:4390' + mainServiceURL: 'ws://localhost:4390', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/PluginAPI.http.spec.js b/test/unit/controllers/PluginAPI.http.spec.js index a7f8a39..fda4d71 100644 --- a/test/unit/controllers/PluginAPI.http.spec.js +++ b/test/unit/controllers/PluginAPI.http.spec.js @@ -73,6 +73,7 @@ describe('PluginAPI HTTP', () => { mainServiceURL: 'http://localhost:3390', authServiceURL: 'http://localhost:3391', pluginServiceURL: 'http://localhost:3392', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/ServerInfoAPI.http.spec.js b/test/unit/controllers/ServerInfoAPI.http.spec.js index 152ab7b..0f9a048 100644 --- a/test/unit/controllers/ServerInfoAPI.http.spec.js +++ b/test/unit/controllers/ServerInfoAPI.http.spec.js @@ -50,7 +50,8 @@ describe('InfoAPI HTTP', () => { login: `dhadmin`, password: `dhadmin_#911`, mainServiceURL: 'http://localhost:3390', - authServiceURL: 'http://localhost:3391' + authServiceURL: 'http://localhost:3391', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/ServerInfoAPI.ws.spec.js b/test/unit/controllers/ServerInfoAPI.ws.spec.js index 5f61a50..d41e76f 100644 --- a/test/unit/controllers/ServerInfoAPI.ws.spec.js +++ b/test/unit/controllers/ServerInfoAPI.ws.spec.js @@ -40,7 +40,8 @@ describe('InfoAPI WS', () => { deviceHive = new DeviceHive({ login: `dhadmin`, password: `dhadmin_#911`, - mainServiceURL: 'ws://localhost:4390' + mainServiceURL: 'ws://localhost:4390', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/TokenAPI.http.spec.js b/test/unit/controllers/TokenAPI.http.spec.js index aa58873..e75fb20 100644 --- a/test/unit/controllers/TokenAPI.http.spec.js +++ b/test/unit/controllers/TokenAPI.http.spec.js @@ -51,7 +51,8 @@ describe('TokenAPI HTTP', () => { login: `dhadmin`, password: `dhadmin_#911`, mainServiceURL: 'http://localhost:3390', - authServiceURL: 'http://localhost:3391' + authServiceURL: 'http://localhost:3391', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/TokenAPI.ws.spec.js b/test/unit/controllers/TokenAPI.ws.spec.js index de64cca..a1a455a 100644 --- a/test/unit/controllers/TokenAPI.ws.spec.js +++ b/test/unit/controllers/TokenAPI.ws.spec.js @@ -40,7 +40,8 @@ describe('TokenAPI WS', () => { deviceHive = new DeviceHive({ login: `dhadmin`, password: `dhadmin_#911`, - mainServiceURL: 'ws://localhost:4390' + mainServiceURL: 'ws://localhost:4390', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/UserAPI.http.spec.js b/test/unit/controllers/UserAPI.http.spec.js index 2f34cc0..a69244a 100644 --- a/test/unit/controllers/UserAPI.http.spec.js +++ b/test/unit/controllers/UserAPI.http.spec.js @@ -50,7 +50,8 @@ describe('UserAPI HTTP', () => { login: `dhadmin`, password: `dhadmin_#911`, mainServiceURL: 'http://localhost:3390', - authServiceURL: 'http://localhost:3391' + authServiceURL: 'http://localhost:3391', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/UserAPI.ws.spec.js b/test/unit/controllers/UserAPI.ws.spec.js index ec91fb6..0b33f0b 100644 --- a/test/unit/controllers/UserAPI.ws.spec.js +++ b/test/unit/controllers/UserAPI.ws.spec.js @@ -40,7 +40,8 @@ describe('NetworkAPI WS', () => { deviceHive = new DeviceHive({ login: `dhadmin`, password: `dhadmin_#911`, - mainServiceURL: 'ws://localhost:4390' + mainServiceURL: 'ws://localhost:4390', + autoUpdateSession: false }); deviceHive.connect() From c7bc440e3decc66a6b3c2f8f713ee96bcbcdbd22 Mon Sep 17 00:00:00 2001 From: itrambovetskiy Date: Mon, 26 Feb 2018 16:21:56 +0200 Subject: [PATCH 09/22] Plugin update test improvements --- .../integration/controllers/PluginAPI.spec.js | 33 ++++++++++++------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/test/integration/controllers/PluginAPI.spec.js b/test/integration/controllers/PluginAPI.spec.js index 83bd822..e53b5a8 100644 --- a/test/integration/controllers/PluginAPI.spec.js +++ b/test/integration/controllers/PluginAPI.spec.js @@ -24,8 +24,6 @@ const testPlugins = [ describe('PluginAPI', () => { before(done => { - // Configaratuion DeviceHive - Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) .then(() => done()); }); @@ -50,8 +48,6 @@ describe('PluginAPI', () => { }); it('PluginAPI.list()', done => { - - // Configurating Plugin List query const pluginListQuery = new DeviceHive.models.query.PluginListQuery({ take: 1, skip: 0 @@ -68,14 +64,31 @@ describe('PluginAPI', () => { }); - // TODO - // it('PluginAPI.update()', done => { - // }); + it('PluginAPI.update()', done => { + const updatedName = `${testPlugins[0].name}-updated`; + const pluginUpdateQuery = new DeviceHive.models.query.PluginUpdateQuery({ + topicName: testPlugins[0].topicName, + name: updatedName + }); + const pluginListQuery = new DeviceHive.models.query.PluginListQuery({ + name: updatedName, + take: 1, + skip: 0 + }); + Promise.all([httpDeviceHive.plugin.update(pluginUpdateQuery)]) + .then(() => Promise.all([httpDeviceHive.plugin.list(pluginListQuery)])) + .then(dataAll => { + for (const data of dataAll) { + assert.strictEqual(data[0].name, updatedName); + } + }) + .then(() => done()) + .catch(done); + }); - it('PluginAPI.count()', done => { - // Configurating Plugin List query + it('PluginAPI.count()', done => { const pluginCountQuery = new DeviceHive.models.query.PluginCountQuery({ status: '1' }); @@ -91,8 +104,6 @@ describe('PluginAPI', () => { }); it('TokenAPI.createPluginToken()', done => { - - // Configurating Token model const token = new DeviceHive.models.PluginToken({ actions: [0], expiration: '2018-02-09T10:09:03.033Z', From c87da785186e38314745ecac05bc2e07aa8ca6a0 Mon Sep 17 00:00:00 2001 From: itrambovetskiy Date: Fri, 23 Feb 2018 18:53:09 +0200 Subject: [PATCH 10/22] Autoupdate session --- example/node/index.js | 37 +++++++++------ package-lock.json | 105 ++++++++++++++++++++++++++++++++++++++++-- package.json | 1 + src/ApiStrategy.js | 8 +++- src/DeviceHive.js | 29 +++++++++--- src/utils/Utils.js | 16 +++++++ 6 files changed, 169 insertions(+), 27 deletions(-) diff --git a/example/node/index.js b/example/node/index.js index 31dc98d..c2d7a05 100644 --- a/example/node/index.js +++ b/example/node/index.js @@ -1,17 +1,20 @@ const DeviceHive = require(`../../index`); const httpDeviceHive = new DeviceHive({ - login: `dhadmin`, - password: `dhadmin_#911`, + // login: `dhadmin`, + // password: `dhadmin_#911`, + accessToken: "eyJhbGciOiJIUzI1NiJ9.eyJwYXlsb2FkIjp7ImEiOlswXSwiZSI6MTUxOTM5ODgxNjg5NCwidCI6MSwidSI6MSwibiI6WyIqIl0sImR0IjpbIioiXX19.cMQ5biZFHZMiCWZtdZAcT8Sb4yqG6h9Jj-Ht1yKydIM", mainServiceURL: 'http://localhost:8080/dh/rest', authServiceURL: 'http://localhost:8090/dh/rest', pluginServiceURL: 'http://localhost:8110/dh/rest' }); const wsDeviceHive = new DeviceHive({ - login: `dhadmin`, - password: `dhadmin_#911`, - mainServiceURL: 'ws://localhost:8080/dh/websocket' + // login: `dhadmin`, + // password: `dhadmin_#911`, + accessToken: "eyJhbGciOiJIUzI1NiJ9.eyJwYXlsb2FkIjp7ImEiOlswXSwiZSI6MTUxOTQwNDUyMTA5OSwidCI6MSwidSI6MSwibiI6WyIqIl0sImR0IjpbIioiXX19.P3MIy194dUgTM3U--KvPG7yc2pNgsEOABIY8Y5xXdGE", + mainServiceURL: 'ws://localhost:8080/dh/websocket', + autoUpdateSession: true }); const DeviceListQuery = DeviceHive.models.query.DeviceListQuery; @@ -27,18 +30,22 @@ const networkListQuery = new NetworkListQuery(); void async function start () { try { - await httpDeviceHive.connect(); + // await httpDeviceHive.connect(); await wsDeviceHive.connect(); - { - const {accessToken, refreshToken} = await httpDeviceHive.token.login('dhadmin', 'dhadmin_#911'); - console.log({accessToken, refreshToken}); - console.log(await httpDeviceHive.device.list(deviceListQuery)); - console.log(await httpDeviceHive.deviceType.list(deviceTypeListQuery)); - console.log(await httpDeviceHive.network.list(networkListQuery)); - console.log(await httpDeviceHive.network.list(networkListQuery)); - console.log(await httpDeviceHive.token.refresh(refreshToken)); - } + // { + // const {accessToken, refreshToken} = await httpDeviceHive.token.login('dhadmin', 'dhadmin_#911'); + // console.log({accessToken, refreshToken}); + // console.log(await httpDeviceHive.device.list(deviceListQuery)); + // console.log(await httpDeviceHive.deviceType.list(deviceTypeListQuery)); + // console.log(await httpDeviceHive.network.list(networkListQuery)); + // console.log(await httpDeviceHive.network.list(networkListQuery)); + // console.log(await httpDeviceHive.token.refresh(refreshToken)); + // + // setTimeout(async () => { + // console.log(await httpDeviceHive.network.list(networkListQuery)); + // }, 60000); + // } { const {accessToken, refreshToken} = await wsDeviceHive.token.login('dhadmin', 'dhadmin_#911'); diff --git a/package-lock.json b/package-lock.json index 8112900..a44acb9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1000,6 +1000,11 @@ "integrity": "sha512-dwVUVIXsBZXwTuwnXI9RK8sBmgq09NDHzyR9SAph9eqk76gKK2JSQmZARC2zRC81JC2QTtxD0ARU5qTS25gIGw==", "dev": true }, + "base64url": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/base64url/-/base64url-2.0.0.tgz", + "integrity": "sha1-6sFuA+oUOO/5Qj1puqNiYu0fcLs=" + }, "big.js": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/big.js/-/big.js-3.2.0.tgz", @@ -1349,6 +1354,11 @@ "ieee754": "1.1.8" } }, + "buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=" + }, "buffer-xor": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", @@ -1927,6 +1937,15 @@ } } }, + "ecdsa-sig-formatter": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.9.tgz", + "integrity": "sha1-S8kmJ07Dtau1AW5+HWCSGsJisqE=", + "requires": { + "base64url": "2.0.0", + "safe-buffer": "5.1.1" + } + }, "electron-to-chromium": { "version": "1.3.33", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.33.tgz", @@ -2714,6 +2733,51 @@ "integrity": "sha1-P02uSpH6wxX3EGL4UhzCOfE2YoA=", "dev": true }, + "jsonwebtoken": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.1.1.tgz", + "integrity": "sha512-+ijVOtfLMlCII8LJkvabaKX3+8tGrGjiCTfzoed2D1b/ebKTO1hIYBQUJHbd9dJ9Fa4kH+dhYEd1qDwyzDLUUw==", + "requires": { + "jws": "3.1.4", + "lodash.includes": "4.3.0", + "lodash.isboolean": "3.0.3", + "lodash.isinteger": "4.0.4", + "lodash.isnumber": "3.0.3", + "lodash.isplainobject": "4.0.6", + "lodash.isstring": "4.0.1", + "lodash.once": "4.1.1", + "ms": "2.1.1", + "xtend": "4.0.1" + }, + "dependencies": { + "ms": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", + "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" + } + } + }, + "jwa": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.1.5.tgz", + "integrity": "sha1-oFUs4CIHQs1S4VN3SjKQXDDnVuU=", + "requires": { + "base64url": "2.0.0", + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.9", + "safe-buffer": "5.1.1" + } + }, + "jws": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.1.4.tgz", + "integrity": "sha1-+ei5M46KhHJ31kRLFGT2GIDgUKI=", + "requires": { + "base64url": "2.0.0", + "jwa": "1.1.5", + "safe-buffer": "5.1.1" + } + }, "kind-of": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", @@ -2788,12 +2852,47 @@ "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", "dev": true }, + "lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8=" + }, + "lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY=" + }, + "lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha1-YZwK89A/iwTDH1iChAt3sRzWg0M=" + }, + "lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w=" + }, + "lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=" + }, + "lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=" + }, "lodash.memoize": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-3.0.4.tgz", "integrity": "sha1-LcvSwofLwKVcxCMovQxzYVDVPj8=", "dev": true }, + "lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w=" + }, "loose-envify": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.3.1.tgz", @@ -3571,8 +3670,7 @@ "safe-buffer": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", - "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==", - "dev": true + "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==" }, "scope-analyzer": { "version": "1.3.0", @@ -4122,8 +4220,7 @@ "xtend": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", - "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", - "dev": true + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=" } } } diff --git a/package.json b/package.json index d99288b..de663c7 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,7 @@ "license": "Apache-2.0", "dependencies": { "isomorphic-fetch": "^2.2.1", + "jsonwebtoken": "^8.1.1", "query-string": "^5.1.0", "string-template": "^1.0.0", "universal-websocket-client": "^1.0.1" diff --git a/src/ApiStrategy.js b/src/ApiStrategy.js index ec8db4e..6c5d12a 100644 --- a/src/ApiStrategy.js +++ b/src/ApiStrategy.js @@ -83,7 +83,13 @@ class ApiStrategy extends EventEmitter { } return me.strategy.send(sendData) - .then((response) => API.normalizeResponse(me.strategy.type, key, response)); + .then((response) => API.normalizeResponse(me.strategy.type, key, response)) + .catch(error => { + if (error === `Token expired`) { + } else { + throw error; + } + }); } } diff --git a/src/DeviceHive.js b/src/DeviceHive.js index 7cabbf2..958469c 100644 --- a/src/DeviceHive.js +++ b/src/DeviceHive.js @@ -1,3 +1,4 @@ +const Utils = require(`./utils/Utils`); const EventEmitter = require('events'); const APIStrategy = require('./ApiStrategy'); const InfoAPI = require('./controllers/ServerInfoAPI'); @@ -98,7 +99,7 @@ class DeviceHive extends EventEmitter { * @param {string} [options.authServiceURL] - Auth Service URL (required only for http) * @param {string} [options.pluginServiceURL] - Alug inServi ceURL (required only for http) */ - constructor({ accessToken, refreshToken, login, password, mainServiceURL, authServiceURL, pluginServiceURL }) { + constructor({ mainServiceURL, authServiceURL, pluginServiceURL, accessToken, refreshToken, login, password, autoUpdateSession }) { super(); const me = this; @@ -107,6 +108,7 @@ class DeviceHive extends EventEmitter { me.refreshToken = refreshToken; me.login = login; me.password = password; + me.autoUpdateSession = autoUpdateSession; me.strategy = new APIStrategy({ mainServiceURL, authServiceURL, pluginServiceURL }); @@ -130,19 +132,32 @@ class DeviceHive extends EventEmitter { * Connect to the DeviceHive service * @returns {Promise} */ - async connect() { + async connect({ accessToken, refreshToken, login, password } = {}) { const me = this; + me.accessToken = accessToken || me.accessToken; + me.refreshToken = refreshToken || me.refreshToken; + me.login = login || me.login; + me.password = password || me.password; + if (me.accessToken || me.refreshToken || (me.login && me.password)) { try { - if (me.accessToken) { - await me.strategy.authorize(me.accessToken); + if (me.login && me.password) { + const { accessToken } = await me.token.login(me.login, me.password); + await me.strategy.authorize(accessToken); } else if (me.refreshToken) { const accessToken = await me.token.refresh(me.refreshToken); await me.strategy.authorize(accessToken); - } else if (me.login && me.password) { - const { accessToken } = await me.token.login(me.login, me.password); - await me.strategy.authorize(accessToken); + } else if (me.accessToken) { + await me.strategy.authorize(me.accessToken); + + if (me.autoUpdateSession === true) { + const { accessToken, refreshToken } = await me.token.createUserToken( + Utils.createUserTokenFromJWT(me.accessToken)); + + me.accessToken = accessToken; + me.refreshToken = refreshToken; + } } } catch (error) { throw new InvalidCredentialsError(); diff --git a/src/utils/Utils.js b/src/utils/Utils.js index 7f99d1b..303fa54 100644 --- a/src/utils/Utils.js +++ b/src/utils/Utils.js @@ -1,3 +1,7 @@ +const jwt = require(`jsonwebtoken`); +const UserToken = require(`../models/UserToken`); + + /** * Utils */ @@ -25,6 +29,18 @@ class Utils { return `${firstPart}${secondPart}`; } + + static createUserTokenFromJWT(jwtToken) { + const tokenPayload = jwt.decode(jwtToken).payload; + + return new UserToken({ + userId: tokenPayload.u, + actions: tokenPayload.a, + networkIds: tokenPayload.n, + deviceTypeIds: tokenPayload.dt, + expiration: tokenPayload.e + }); + } } From 14cc5f03994118a3e175bc3c5d6fa752de275a94 Mon Sep 17 00:00:00 2001 From: itrambovetskiy Date: Mon, 26 Feb 2018 15:08:41 +0200 Subject: [PATCH 11/22] Autoupdate session --- example/node/index.js | 40 +++---- package-lock.json | 108 ++---------------- package.json | 2 +- src/ApiStrategy.js | 7 +- src/DeviceHive.js | 49 +++++--- src/controllers/transportResolvers/ApiMap.js | 10 +- .../transportResolvers/HttpApiResolver.js | 5 +- src/error/InvalidCredentialsError.js | 4 +- src/transports/HTTP.js | 10 +- src/utils/Utils.js | 12 +- .../controllers/ConfigurationAPI.spec.js | 2 +- test/integration/controllers/Device.spec.js | 2 +- .../controllers/DeviceCommandAPI.spec.js | 4 +- .../controllers/DeviceNotificationAPI.spec.js | 6 +- .../controllers/DeviceTypeAPI.spec.js | 2 +- .../controllers/NetworkAPI.spec.js | 2 +- .../integration/controllers/PluginAPI.spec.js | 2 +- .../controllers/ServerInfoAPI.spec.js | 2 +- test/integration/controllers/TokenAPI.spec.js | 2 +- test/integration/controllers/UserAPI.spec.js | 4 +- 20 files changed, 104 insertions(+), 171 deletions(-) diff --git a/example/node/index.js b/example/node/index.js index c2d7a05..475cbe0 100644 --- a/example/node/index.js +++ b/example/node/index.js @@ -1,18 +1,19 @@ const DeviceHive = require(`../../index`); + const httpDeviceHive = new DeviceHive({ - // login: `dhadmin`, - // password: `dhadmin_#911`, - accessToken: "eyJhbGciOiJIUzI1NiJ9.eyJwYXlsb2FkIjp7ImEiOlswXSwiZSI6MTUxOTM5ODgxNjg5NCwidCI6MSwidSI6MSwibiI6WyIqIl0sImR0IjpbIioiXX19.cMQ5biZFHZMiCWZtdZAcT8Sb4yqG6h9Jj-Ht1yKydIM", + login: `dhadmin`, + password: `dhadmin_#911`, + accessToken: "eyJhbGciOiJIUzI1NiJ9.eyJwYXlsb2FkIjp7ImEiOlswXSwiZSI6MTUxOTY1MDIxMDgwNSwidCI6MSwidSI6MSwibiI6WyIqIl0sImR0IjpbIioiXX19.8MX7MiQeKmKCUGkNSqce1xCUTVBYX6GQKqgAwGvHB9Y", mainServiceURL: 'http://localhost:8080/dh/rest', authServiceURL: 'http://localhost:8090/dh/rest', pluginServiceURL: 'http://localhost:8110/dh/rest' }); const wsDeviceHive = new DeviceHive({ - // login: `dhadmin`, - // password: `dhadmin_#911`, - accessToken: "eyJhbGciOiJIUzI1NiJ9.eyJwYXlsb2FkIjp7ImEiOlswXSwiZSI6MTUxOTQwNDUyMTA5OSwidCI6MSwidSI6MSwibiI6WyIqIl0sImR0IjpbIioiXX19.P3MIy194dUgTM3U--KvPG7yc2pNgsEOABIY8Y5xXdGE", + login: `dhadmin`, + password: `dhadmin_#911`, + accessToken: "eyJhbGciOiJIUzI1NiJ9.eyJwYXlsb2FkIjp7ImEiOlswXSwiZSI6MTUxOTY0OTczMDgwNSwidCI6MSwidSI6MSwibiI6WyIqIl0sImR0IjpbIioiXX19.3Kb1Lkqza0VzG8gsX2tlp5B5BcL2w55gVmMM1aMsDbY", mainServiceURL: 'ws://localhost:8080/dh/websocket', autoUpdateSession: true }); @@ -30,22 +31,18 @@ const networkListQuery = new NetworkListQuery(); void async function start () { try { - // await httpDeviceHive.connect(); + await httpDeviceHive.connect(); await wsDeviceHive.connect(); - // { - // const {accessToken, refreshToken} = await httpDeviceHive.token.login('dhadmin', 'dhadmin_#911'); - // console.log({accessToken, refreshToken}); - // console.log(await httpDeviceHive.device.list(deviceListQuery)); - // console.log(await httpDeviceHive.deviceType.list(deviceTypeListQuery)); - // console.log(await httpDeviceHive.network.list(networkListQuery)); - // console.log(await httpDeviceHive.network.list(networkListQuery)); - // console.log(await httpDeviceHive.token.refresh(refreshToken)); - // - // setTimeout(async () => { - // console.log(await httpDeviceHive.network.list(networkListQuery)); - // }, 60000); - // } + { + const {accessToken, refreshToken} = await httpDeviceHive.token.login('dhadmin', 'dhadmin_#911'); + console.log({accessToken, refreshToken}); + console.log(await httpDeviceHive.device.list(deviceListQuery)); + console.log(await httpDeviceHive.deviceType.list(deviceTypeListQuery)); + console.log(await httpDeviceHive.network.list(networkListQuery)); + console.log(await httpDeviceHive.network.list(networkListQuery)); + console.log(await httpDeviceHive.token.refresh(refreshToken)); + } { const {accessToken, refreshToken} = await wsDeviceHive.token.login('dhadmin', 'dhadmin_#911'); @@ -55,7 +52,10 @@ void async function start () { console.log(await wsDeviceHive.network.list(networkListQuery)); console.log(await wsDeviceHive.token.refresh(refreshToken)); } + } catch (error) { console.warn(error); } + + process.exit(1); }(); \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index a44acb9..20ce356 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1000,11 +1000,6 @@ "integrity": "sha512-dwVUVIXsBZXwTuwnXI9RK8sBmgq09NDHzyR9SAph9eqk76gKK2JSQmZARC2zRC81JC2QTtxD0ARU5qTS25gIGw==", "dev": true }, - "base64url": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/base64url/-/base64url-2.0.0.tgz", - "integrity": "sha1-6sFuA+oUOO/5Qj1puqNiYu0fcLs=" - }, "big.js": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/big.js/-/big.js-3.2.0.tgz", @@ -1354,11 +1349,6 @@ "ieee754": "1.1.8" } }, - "buffer-equal-constant-time": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", - "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=" - }, "buffer-xor": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", @@ -1937,15 +1927,6 @@ } } }, - "ecdsa-sig-formatter": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.9.tgz", - "integrity": "sha1-S8kmJ07Dtau1AW5+HWCSGsJisqE=", - "requires": { - "base64url": "2.0.0", - "safe-buffer": "5.1.1" - } - }, "electron-to-chromium": { "version": "1.3.33", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.33.tgz", @@ -2733,50 +2714,10 @@ "integrity": "sha1-P02uSpH6wxX3EGL4UhzCOfE2YoA=", "dev": true }, - "jsonwebtoken": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.1.1.tgz", - "integrity": "sha512-+ijVOtfLMlCII8LJkvabaKX3+8tGrGjiCTfzoed2D1b/ebKTO1hIYBQUJHbd9dJ9Fa4kH+dhYEd1qDwyzDLUUw==", - "requires": { - "jws": "3.1.4", - "lodash.includes": "4.3.0", - "lodash.isboolean": "3.0.3", - "lodash.isinteger": "4.0.4", - "lodash.isnumber": "3.0.3", - "lodash.isplainobject": "4.0.6", - "lodash.isstring": "4.0.1", - "lodash.once": "4.1.1", - "ms": "2.1.1", - "xtend": "4.0.1" - }, - "dependencies": { - "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" - } - } - }, - "jwa": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.1.5.tgz", - "integrity": "sha1-oFUs4CIHQs1S4VN3SjKQXDDnVuU=", - "requires": { - "base64url": "2.0.0", - "buffer-equal-constant-time": "1.0.1", - "ecdsa-sig-formatter": "1.0.9", - "safe-buffer": "5.1.1" - } - }, - "jws": { - "version": "3.1.4", - "resolved": "https://registry.npmjs.org/jws/-/jws-3.1.4.tgz", - "integrity": "sha1-+ei5M46KhHJ31kRLFGT2GIDgUKI=", - "requires": { - "base64url": "2.0.0", - "jwa": "1.1.5", - "safe-buffer": "5.1.1" - } + "jwt-decode": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-2.2.0.tgz", + "integrity": "sha1-fYa9VmefWM5qhHBKZX3TkruoGnk=" }, "kind-of": { "version": "3.2.2", @@ -2852,47 +2793,12 @@ "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", "dev": true }, - "lodash.includes": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", - "integrity": "sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8=" - }, - "lodash.isboolean": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", - "integrity": "sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY=" - }, - "lodash.isinteger": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", - "integrity": "sha1-YZwK89A/iwTDH1iChAt3sRzWg0M=" - }, - "lodash.isnumber": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", - "integrity": "sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w=" - }, - "lodash.isplainobject": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", - "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=" - }, - "lodash.isstring": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", - "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=" - }, "lodash.memoize": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-3.0.4.tgz", "integrity": "sha1-LcvSwofLwKVcxCMovQxzYVDVPj8=", "dev": true }, - "lodash.once": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", - "integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w=" - }, "loose-envify": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.3.1.tgz", @@ -3670,7 +3576,8 @@ "safe-buffer": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", - "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==" + "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==", + "dev": true }, "scope-analyzer": { "version": "1.3.0", @@ -4220,7 +4127,8 @@ "xtend": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", - "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=" + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true } } } diff --git a/package.json b/package.json index de663c7..f7d3b85 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,7 @@ "license": "Apache-2.0", "dependencies": { "isomorphic-fetch": "^2.2.1", - "jsonwebtoken": "^8.1.1", + "jwt-decode": "^2.2.0", "query-string": "^5.1.0", "string-template": "^1.0.0", "universal-websocket-client": "^1.0.1" diff --git a/src/ApiStrategy.js b/src/ApiStrategy.js index 6c5d12a..ad0c299 100644 --- a/src/ApiStrategy.js +++ b/src/ApiStrategy.js @@ -40,6 +40,8 @@ class ApiStrategy extends EventEmitter { const me = this; + me.reconnectionHandler = null; + me.urlsMap = new Map(); me.urlsMap.set(API.MAIN_BASE, mainServiceURL); @@ -85,7 +87,10 @@ class ApiStrategy extends EventEmitter { return me.strategy.send(sendData) .then((response) => API.normalizeResponse(me.strategy.type, key, response)) .catch(error => { - if (error === `Token expired`) { + if (error === `Token expired` && me.reconnectionHandler) { + return me.reconnectionHandler() + .then(() => me.strategy.send(sendData)) + .then((response) => API.normalizeResponse(me.strategy.type, key, response)); } else { throw error; } diff --git a/src/DeviceHive.js b/src/DeviceHive.js index 958469c..283e0de 100644 --- a/src/DeviceHive.js +++ b/src/DeviceHive.js @@ -135,32 +135,45 @@ class DeviceHive extends EventEmitter { async connect({ accessToken, refreshToken, login, password } = {}) { const me = this; - me.accessToken = accessToken || me.accessToken; - me.refreshToken = refreshToken || me.refreshToken; - me.login = login || me.login; - me.password = password || me.password; + if (!accessToken && !refreshToken && !(login && password)) { + accessToken = accessToken || me.accessToken; + refreshToken = refreshToken || me.refreshToken; + login = login || me.login; + password = password || me.password; + } - if (me.accessToken || me.refreshToken || (me.login && me.password)) { + if (accessToken || refreshToken || (login && password)) { try { - if (me.login && me.password) { - const { accessToken } = await me.token.login(me.login, me.password); + if (login && password) { + const { accessToken, refreshToken } = await me.token.login(login, password); + + await me.strategy.authorize(accessToken); + + me.accessToken = accessToken; + me.refreshToken = refreshToken; + } else if (refreshToken) { + const { accessToken } = await me.token.refresh(refreshToken); + await me.strategy.authorize(accessToken); - } else if (me.refreshToken) { - const accessToken = await me.token.refresh(me.refreshToken); + + me.accessToken = accessToken; + me.refreshToken = refreshToken; + } else if (accessToken) { await me.strategy.authorize(accessToken); - } else if (me.accessToken) { - await me.strategy.authorize(me.accessToken); - if (me.autoUpdateSession === true) { - const { accessToken, refreshToken } = await me.token.createUserToken( - Utils.createUserTokenFromJWT(me.accessToken)); + me.accessToken = accessToken; + } + + if (me.autoUpdateSession === true) { + const userTokens = await me.token.createUserToken( + Utils.createUserTokenFromJWT(me.accessToken)); - me.accessToken = accessToken; - me.refreshToken = refreshToken; - } + me.accessToken = userTokens.accessToken; + me.refreshToken = userTokens.refreshToken; + me.strategy.reconnectionHandler = () => me.connect({ refreshToken: me.refreshToken }); } } catch (error) { - throw new InvalidCredentialsError(); + throw new InvalidCredentialsError(error); } } else { throw new NoAuthCredentialsError(); diff --git a/src/controllers/transportResolvers/ApiMap.js b/src/controllers/transportResolvers/ApiMap.js index 56138d1..25bf7f5 100644 --- a/src/controllers/transportResolvers/ApiMap.js +++ b/src/controllers/transportResolvers/ApiMap.js @@ -156,15 +156,15 @@ class ApiMap { } -apiMap.set(ApiMap.login, { http: { method: 'POST', uri: '/token', base: ApiMap.AUTH_BASE }, ws: { action: 'token', response: [`accessToken`, `refreshToken`] } }); +apiMap.set(ApiMap.login, { http: { method: 'POST', uri: '/token', base: ApiMap.AUTH_BASE, noAuth: true }, ws: { action: 'token', response: [`accessToken`, `refreshToken`] } }); apiMap.set(ApiMap.createUserToken, { http: { method: 'POST', uri: '/token/create', base: ApiMap.AUTH_BASE }, ws: { action: 'token/create', bodyKey: 'payload', response: [`accessToken`, `refreshToken`] } }); apiMap.set(ApiMap.createPluginToken, { http: { method: 'POST', uri: '/token/plugin/create', base: ApiMap.AUTH_BASE } }); -apiMap.set(ApiMap.refreshToken, { http: { method: 'POST', uri: '/token/refresh', base: ApiMap.AUTH_BASE }, ws: { action: 'token/refresh', response: [`accessToken`] } }); +apiMap.set(ApiMap.refreshToken, { http: { method: 'POST', uri: '/token/refresh', base: ApiMap.AUTH_BASE, noAuth: true }, ws: { action: 'token/refresh', response: [`accessToken`] } }); apiMap.set(ApiMap.authenticatePlugin, { http: { method: 'GET', uri: '/token/plugin/authenticate', base: ApiMap.AUTH_BASE } }); -apiMap.set(ApiMap.getServerInfo, { http: { method: 'GET', uri: '/info', base: ApiMap.MAIN_BASE }, ws: { action: 'server/info', response: { bodyKey: `info` } } }); -apiMap.set(ApiMap.getCacheInfo, { http: { method: 'GET', uri: '/info/cache', base: ApiMap.MAIN_BASE } }); -apiMap.set(ApiMap.getClusterInfo, { http: { method: 'GET', uri: '/info/config/cluster', base: ApiMap.MAIN_BASE }, ws: { action: 'cluster/info', response: { bodyKey: `clusterInfo` } } }); +apiMap.set(ApiMap.getServerInfo, { http: { method: 'GET', uri: '/info', base: ApiMap.MAIN_BASE, noAuth: true }, ws: { action: 'server/info', response: { bodyKey: `info` } } }); +apiMap.set(ApiMap.getCacheInfo, { http: { method: 'GET', uri: '/info/cache', base: ApiMap.MAIN_BASE, noAuth: true } }); +apiMap.set(ApiMap.getClusterInfo, { http: { method: 'GET', uri: '/info/config/cluster', base: ApiMap.MAIN_BASE, noAuth: true }, ws: { action: 'cluster/info', response: { bodyKey: `clusterInfo` } } }); apiMap.set(ApiMap.getConfiguration, { http: { method: 'GET', uri: '/configuration/{name}', base: ApiMap.MAIN_BASE }, ws: { action: 'configuration/get', response: { bodyKey: `configuration` } } }); apiMap.set(ApiMap.putConfiguration, { http: { method: 'PUT', uri: '/configuration/{name}', base: ApiMap.MAIN_BASE }, ws: { action: 'configuration/put', response: { bodyKey: `configuration` } } }); diff --git a/src/controllers/transportResolvers/HttpApiResolver.js b/src/controllers/transportResolvers/HttpApiResolver.js index b207d7b..26c1213 100644 --- a/src/controllers/transportResolvers/HttpApiResolver.js +++ b/src/controllers/transportResolvers/HttpApiResolver.js @@ -54,7 +54,7 @@ class HttpApiResolver { * @param {boolean} options.subscription * @param {boolean} options.unsubscription */ - constructor({ method, uri, base, subscription, unsubscription }) { + constructor({ method, uri, base, subscription, unsubscription, noAuth }) { const me = this; me.method = method; @@ -62,6 +62,7 @@ class HttpApiResolver { me.base = base; me.subscription = subscription; me.unsubscription = unsubscription; + me.noAuth = noAuth; } /** @@ -76,6 +77,7 @@ class HttpApiResolver { if (me.unsubscription === true) { result = { + noAuth: me.noAuth, unsubscription: me.unsubscription, body: { subscriptionId: parameters.subscriptionId @@ -83,6 +85,7 @@ class HttpApiResolver { }; } else { result = { + noAuth: me.noAuth, method: me.method, endpoint: HttpApiResolver.buildUrl(me.uri, parameters), base: me.base, diff --git a/src/error/InvalidCredentialsError.js b/src/error/InvalidCredentialsError.js index d0fd1d6..a93f4a6 100644 --- a/src/error/InvalidCredentialsError.js +++ b/src/error/InvalidCredentialsError.js @@ -6,10 +6,10 @@ class InvalidCredentialsError extends Error { /** * Creates new InvalidCredentialsError */ - constructor() { + constructor(message) { super(); - this.message = `Invalid credentials error during attempt to authenticate.`; + this.message = `Invalid credentials error during attempt to authenticate. Error: ${message}`; } } diff --git a/src/transports/HTTP.js b/src/transports/HTTP.js index 058c55d..d5ab869 100644 --- a/src/transports/HTTP.js +++ b/src/transports/HTTP.js @@ -37,7 +37,7 @@ class HTTP extends Transport { /** * Rest API send method */ - send({ endpoint, method, body, subscription, unsubscription }) { + send({ endpoint, method, body, subscription, unsubscription, noAuth }) { const me = this; if (subscription === true) { @@ -62,7 +62,7 @@ class HTTP extends Transport { return Promise.resolve({ status: `No such subscription` }) } } else { - return fetch(endpoint, { headers: me._getHeaders(), method: method, body: JSON.stringify(body) }) + return fetch(endpoint, { headers: me._getHeaders(noAuth), method: method, body: JSON.stringify(body) }) .then(response => response.text()) .then(responseText => { return responseText ? JSON.parse(responseText) : responseText @@ -110,15 +110,15 @@ class HTTP extends Transport { * @returns {Object} * @private */ - _getHeaders() { + _getHeaders(noAuth = false) { const me = this; const headers = { "Content-type": `application/json`, "Accept": `application/json` }; - if (me.token) { - headers[`Authorization`] = `Bearer ${me.token}`; + if (me.token && !noAuth) { + headers.Authorization = `Bearer ${me.token}`; } return headers; diff --git a/src/utils/Utils.js b/src/utils/Utils.js index 303fa54..5c614c1 100644 --- a/src/utils/Utils.js +++ b/src/utils/Utils.js @@ -1,4 +1,4 @@ -const jwt = require(`jsonwebtoken`); +const jwtDecode = require(`jwt-decode`); const UserToken = require(`../models/UserToken`); @@ -30,15 +30,19 @@ class Utils { return `${firstPart}${secondPart}`; } + /** + * Creates UserToken from jwt + * @param jwtToken + * @returns {UserToken} + */ static createUserTokenFromJWT(jwtToken) { - const tokenPayload = jwt.decode(jwtToken).payload; + const tokenPayload = jwtDecode(jwtToken).payload; return new UserToken({ userId: tokenPayload.u, actions: tokenPayload.a, networkIds: tokenPayload.n, - deviceTypeIds: tokenPayload.dt, - expiration: tokenPayload.e + deviceTypeIds: tokenPayload.dt }); } } diff --git a/test/integration/controllers/ConfigurationAPI.spec.js b/test/integration/controllers/ConfigurationAPI.spec.js index d4bf98a..508479e 100644 --- a/test/integration/controllers/ConfigurationAPI.spec.js +++ b/test/integration/controllers/ConfigurationAPI.spec.js @@ -8,7 +8,7 @@ const events = new EventEmitter(); const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); -const wsDeviceHive = new DeviceHive(config.server.ws) +const wsDeviceHive = new DeviceHive(config.server.ws); const testConfigurations = [ diff --git a/test/integration/controllers/Device.spec.js b/test/integration/controllers/Device.spec.js index 72b4512..e0329d7 100644 --- a/test/integration/controllers/Device.spec.js +++ b/test/integration/controllers/Device.spec.js @@ -8,7 +8,7 @@ const events = new EventEmitter(); const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); -const wsDeviceHive = new DeviceHive(config.server.ws) +const wsDeviceHive = new DeviceHive(config.server.ws); const testDevices = [ diff --git a/test/integration/controllers/DeviceCommandAPI.spec.js b/test/integration/controllers/DeviceCommandAPI.spec.js index f139351..eba276c 100644 --- a/test/integration/controllers/DeviceCommandAPI.spec.js +++ b/test/integration/controllers/DeviceCommandAPI.spec.js @@ -8,9 +8,9 @@ const events = new EventEmitter(); const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); -const wsDeviceHive = new DeviceHive(config.server.ws) +const wsDeviceHive = new DeviceHive(config.server.ws); -const deviceId = 'e50d6085-2aba-48e9-b1c3-73c673e414be2'; +const deviceId = 'e50d6085-2aba-48e9-b1c3-73c673e414be'; const testDeviceCommands = [ { diff --git a/test/integration/controllers/DeviceNotificationAPI.spec.js b/test/integration/controllers/DeviceNotificationAPI.spec.js index fb97e36..c4d42a8 100644 --- a/test/integration/controllers/DeviceNotificationAPI.spec.js +++ b/test/integration/controllers/DeviceNotificationAPI.spec.js @@ -8,9 +8,9 @@ const events = new EventEmitter(); const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); -const wsDeviceHive = new DeviceHive(config.server.ws) +const wsDeviceHive = new DeviceHive(config.server.ws); -const deviceId = 'e50d6085-2aba-48e9-b1c3-73c673e414be2'; +const deviceId = 'e50d6085-2aba-48e9-b1c3-73c673e414be'; const testDeviceNotifications = [ { @@ -28,7 +28,7 @@ const testDeviceNotifications = [ parameters: { jsonString: 'jsonString' } - }, + } ]; describe('NotificationAPI', () => { diff --git a/test/integration/controllers/DeviceTypeAPI.spec.js b/test/integration/controllers/DeviceTypeAPI.spec.js index 82cf932..cb6412d 100644 --- a/test/integration/controllers/DeviceTypeAPI.spec.js +++ b/test/integration/controllers/DeviceTypeAPI.spec.js @@ -8,7 +8,7 @@ const events = new EventEmitter(); const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); -const wsDeviceHive = new DeviceHive(config.server.ws) +const wsDeviceHive = new DeviceHive(config.server.ws); const testDeviceTypes = [ diff --git a/test/integration/controllers/NetworkAPI.spec.js b/test/integration/controllers/NetworkAPI.spec.js index 12f6a6b..2ce51e1 100644 --- a/test/integration/controllers/NetworkAPI.spec.js +++ b/test/integration/controllers/NetworkAPI.spec.js @@ -8,7 +8,7 @@ const events = new EventEmitter(); const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); -const wsDeviceHive = new DeviceHive(config.server.ws) +const wsDeviceHive = new DeviceHive(config.server.ws); const testNetworks = [ diff --git a/test/integration/controllers/PluginAPI.spec.js b/test/integration/controllers/PluginAPI.spec.js index fab0122..83bd822 100644 --- a/test/integration/controllers/PluginAPI.spec.js +++ b/test/integration/controllers/PluginAPI.spec.js @@ -8,7 +8,7 @@ const events = new EventEmitter(); const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); -const wsDeviceHive = new DeviceHive(config.server.ws) +const wsDeviceHive = new DeviceHive(config.server.ws); const testPlugins = [ diff --git a/test/integration/controllers/ServerInfoAPI.spec.js b/test/integration/controllers/ServerInfoAPI.spec.js index 4b21d60..0bc96df 100644 --- a/test/integration/controllers/ServerInfoAPI.spec.js +++ b/test/integration/controllers/ServerInfoAPI.spec.js @@ -8,7 +8,7 @@ const events = new EventEmitter(); const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); -const wsDeviceHive = new DeviceHive(config.server.ws) +const wsDeviceHive = new DeviceHive(config.server.ws); describe('ServerInfoAPI', () => { diff --git a/test/integration/controllers/TokenAPI.spec.js b/test/integration/controllers/TokenAPI.spec.js index d6e7aab..60f2fc3 100644 --- a/test/integration/controllers/TokenAPI.spec.js +++ b/test/integration/controllers/TokenAPI.spec.js @@ -8,7 +8,7 @@ const events = new EventEmitter(); const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); -const wsDeviceHive = new DeviceHive(config.server.ws) +const wsDeviceHive = new DeviceHive(config.server.ws); const testToken = { diff --git a/test/integration/controllers/UserAPI.spec.js b/test/integration/controllers/UserAPI.spec.js index 088c911..5d81fc7 100644 --- a/test/integration/controllers/UserAPI.spec.js +++ b/test/integration/controllers/UserAPI.spec.js @@ -8,7 +8,7 @@ const events = new EventEmitter(); const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); -const wsDeviceHive = new DeviceHive(config.server.ws) +const wsDeviceHive = new DeviceHive(config.server.ws); const testUsers = [ @@ -159,7 +159,7 @@ describe('UserAPI', () => { login: 'login', loginPattern: 'loginPattern', role: '1', - status: '1', + status: '1' }); Promise.all([httpDeviceHive.user.count(userListQuery), wsDeviceHive.user.count(userListQuery)]) From 6c32fdb200417b5c6b66433cffe5aa0fc3ec0a8b Mon Sep 17 00:00:00 2001 From: itrambovetskiy Date: Mon, 26 Feb 2018 15:11:12 +0200 Subject: [PATCH 12/22] Packages update --- package-lock.json | 37 +++++++++++++++++-------------------- package.json | 4 ++-- 2 files changed, 19 insertions(+), 22 deletions(-) diff --git a/package-lock.json b/package-lock.json index 20ce356..305e6f1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -851,9 +851,9 @@ } }, "babel-loader": { - "version": "8.0.0-beta.0", - "resolved": "https://registry.npmjs.org/babel-loader/-/babel-loader-8.0.0-beta.0.tgz", - "integrity": "sha512-qVXXyIqTrLBH3Ki2VCJog1fUd6qzKUk9lHS34WJPW93Bh0BUvXTFSD5ZkG3a5+Uxxje+RgCk8Y7RyB6zyK9rWw==", + "version": "8.0.0-beta.2", + "resolved": "https://registry.npmjs.org/babel-loader/-/babel-loader-8.0.0-beta.2.tgz", + "integrity": "sha512-P1zch1DvQy3RGmp/1CH78uPg5gTPQQ01S9r6ipCOWVamO0UIC8gnrx7m7LsUsXa470yB6IOZxhtEEwIUclRLNw==", "dev": true, "requires": { "find-cache-dir": "1.0.0", @@ -2267,7 +2267,7 @@ "dev": true, "requires": { "commondir": "1.0.1", - "make-dir": "1.1.0", + "make-dir": "1.2.0", "pkg-dir": "2.0.0" } }, @@ -2818,20 +2818,12 @@ } }, "make-dir": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-1.1.0.tgz", - "integrity": "sha512-0Pkui4wLJ7rxvmfUvs87skoEaxmu0hCUApF8nonzpl7q//FWp9zu8W61Scz4sd/kUiqDxvUhtoam2efDyiBzcA==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-1.2.0.tgz", + "integrity": "sha512-aNUAa4UMg/UougV25bbrU4ZaaKNjJ/3/xnvg/twpmKROPdKZPZ9wGgI0opdZzO8q/zUFawoUuixuOv33eZ61Iw==", "dev": true, "requires": { "pify": "3.0.0" - }, - "dependencies": { - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true - } } }, "md5.js": { @@ -3287,6 +3279,12 @@ "sha.js": "2.4.10" } }, + "pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", + "dev": true + }, "pkg-dir": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-2.0.0.tgz", @@ -4114,14 +4112,13 @@ "dev": true }, "ws": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-4.0.0.tgz", - "integrity": "sha512-QYslsH44bH8O7/W2815u5DpnCpXWpEK44FmaHffNwgJI4JMaSZONgPBTOfrxJ29mXKbXak+LsJ2uAkDTYq2ptQ==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-4.1.0.tgz", + "integrity": "sha512-ZGh/8kF9rrRNffkLFV4AzhvooEclrOH0xaugmqGsIfFgOE/pIz4fMc4Ef+5HSQqTEug2S9JZIWDR47duDSLfaA==", "dev": true, "requires": { "async-limiter": "1.0.0", - "safe-buffer": "5.1.1", - "ultron": "1.1.1" + "safe-buffer": "5.1.1" } }, "xtend": { diff --git a/package.json b/package.json index f7d3b85..686702e 100644 --- a/package.json +++ b/package.json @@ -26,13 +26,13 @@ "@babel/core": "^7.0.0-beta.40", "@babel/preset-env": "^7.0.0-beta.40", "babel-core": "^6.26.0", - "babel-loader": "^8.0.0-beta.0", + "babel-loader": "^8.0.0-beta.2", "babelify": "^8.0.0", "browserify": "^15.2.0", "chai": "^4.1.2", "exorcist": "^1.0.1", "mocha": "^5.0.1", "tinyify": "^2.4.0", - "ws": "^4.0.0" + "ws": "^4.1.0" } } From cd2f9d9cea8ec49b38d793c4ce6e26fb45b78746 Mon Sep 17 00:00:00 2001 From: itrambovetskiy Date: Mon, 26 Feb 2018 15:23:09 +0200 Subject: [PATCH 13/22] Slight improvements --- src/ApiStrategy.js | 6 +++--- src/DeviceHive.js | 2 +- src/utils/Utils.js | 2 ++ test/unit/controllers/ConfigurationAPI.http.spec.js | 3 ++- test/unit/controllers/ConfigurationAPI.ws.spec.js | 3 ++- test/unit/controllers/DeviceAPI.http.spec.js | 3 ++- test/unit/controllers/DeviceAPI.ws.spec.js | 3 ++- test/unit/controllers/DeviceCommandAPI.http.spec.js | 3 ++- test/unit/controllers/DeviceCommandAPI.ws.spec.js | 3 ++- test/unit/controllers/DeviceNotificationAPI.http.spec.js | 3 ++- test/unit/controllers/DeviceNotificationAPI.ws.spec.js | 3 ++- test/unit/controllers/DeviceTypeAPI.http.spec.js | 3 ++- test/unit/controllers/DeviceTypeAPI.ws.spec.js | 3 ++- test/unit/controllers/NetworkAPI.http.spec.js | 3 ++- test/unit/controllers/NetworkAPI.ws.spec.js | 3 ++- test/unit/controllers/PluginAPI.http.spec.js | 1 + test/unit/controllers/ServerInfoAPI.http.spec.js | 3 ++- test/unit/controllers/ServerInfoAPI.ws.spec.js | 3 ++- test/unit/controllers/TokenAPI.http.spec.js | 3 ++- test/unit/controllers/TokenAPI.ws.spec.js | 3 ++- test/unit/controllers/UserAPI.http.spec.js | 3 ++- test/unit/controllers/UserAPI.ws.spec.js | 3 ++- 22 files changed, 43 insertions(+), 22 deletions(-) diff --git a/src/ApiStrategy.js b/src/ApiStrategy.js index ad0c299..73a0296 100644 --- a/src/ApiStrategy.js +++ b/src/ApiStrategy.js @@ -20,9 +20,9 @@ class ApiStrategy extends EventEmitter { static getType(url) { let result; - if (url.startsWith('http') || url.startsWith('https')) { + if (url.startsWith(HTTP.TYPE)) { result = HTTP; - } else if (url.startsWith('ws') || url.startsWith('wss')) { + } else if (url.startsWith(WS.TYPE)) { result = WS; } else { throw new UnsupportedTransportError(); @@ -87,7 +87,7 @@ class ApiStrategy extends EventEmitter { return me.strategy.send(sendData) .then((response) => API.normalizeResponse(me.strategy.type, key, response)) .catch(error => { - if (error === `Token expired` && me.reconnectionHandler) { + if (error === Utils.TOKEN_EXPIRED_MARK && me.reconnectionHandler) { return me.reconnectionHandler() .then(() => me.strategy.send(sendData)) .then((response) => API.normalizeResponse(me.strategy.type, key, response)); diff --git a/src/DeviceHive.js b/src/DeviceHive.js index 283e0de..e606e23 100644 --- a/src/DeviceHive.js +++ b/src/DeviceHive.js @@ -99,7 +99,7 @@ class DeviceHive extends EventEmitter { * @param {string} [options.authServiceURL] - Auth Service URL (required only for http) * @param {string} [options.pluginServiceURL] - Alug inServi ceURL (required only for http) */ - constructor({ mainServiceURL, authServiceURL, pluginServiceURL, accessToken, refreshToken, login, password, autoUpdateSession }) { + constructor({ mainServiceURL, authServiceURL, pluginServiceURL, accessToken, refreshToken, login, password, autoUpdateSession = true }) { super(); const me = this; diff --git a/src/utils/Utils.js b/src/utils/Utils.js index 5c614c1..102e21c 100644 --- a/src/utils/Utils.js +++ b/src/utils/Utils.js @@ -7,6 +7,8 @@ const UserToken = require(`../models/UserToken`); */ class Utils { + static get TOKEN_EXPIRED_MARK() { return `Token expired`; } + /** * Checks that object is empty * @returns {boolean} - Is object empty diff --git a/test/unit/controllers/ConfigurationAPI.http.spec.js b/test/unit/controllers/ConfigurationAPI.http.spec.js index d26a741..e99c46d 100644 --- a/test/unit/controllers/ConfigurationAPI.http.spec.js +++ b/test/unit/controllers/ConfigurationAPI.http.spec.js @@ -50,7 +50,8 @@ describe('ConfigurationAPI HTTP', () => { login: `dhadmin`, password: `dhadmin_#911`, mainServiceURL: 'http://localhost:3390', - authServiceURL: 'http://localhost:3391' + authServiceURL: 'http://localhost:3391', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/ConfigurationAPI.ws.spec.js b/test/unit/controllers/ConfigurationAPI.ws.spec.js index 8cc4734..072afd1 100644 --- a/test/unit/controllers/ConfigurationAPI.ws.spec.js +++ b/test/unit/controllers/ConfigurationAPI.ws.spec.js @@ -40,7 +40,8 @@ describe('ConfigurationAPI WS', () => { deviceHive = new DeviceHive({ login: `dhadmin`, password: `dhadmin_#911`, - mainServiceURL: 'ws://localhost:4390' + mainServiceURL: 'ws://localhost:4390', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/DeviceAPI.http.spec.js b/test/unit/controllers/DeviceAPI.http.spec.js index 3705d0e..3ab1849 100644 --- a/test/unit/controllers/DeviceAPI.http.spec.js +++ b/test/unit/controllers/DeviceAPI.http.spec.js @@ -50,7 +50,8 @@ describe('DeviceAPI', () => { login: `dhadmin`, password: `dhadmin_#911`, mainServiceURL: 'http://localhost:3390', - authServiceURL: 'http://localhost:3391' + authServiceURL: 'http://localhost:3391', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/DeviceAPI.ws.spec.js b/test/unit/controllers/DeviceAPI.ws.spec.js index 3ae25d4..33cff90 100644 --- a/test/unit/controllers/DeviceAPI.ws.spec.js +++ b/test/unit/controllers/DeviceAPI.ws.spec.js @@ -40,7 +40,8 @@ describe('DeviceAPI WS', () => { deviceHive = new DeviceHive({ login: `dhadmin`, password: `dhadmin_#911`, - mainServiceURL: 'ws://localhost:4390' + mainServiceURL: 'ws://localhost:4390', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/DeviceCommandAPI.http.spec.js b/test/unit/controllers/DeviceCommandAPI.http.spec.js index cabedca..4cf17a6 100644 --- a/test/unit/controllers/DeviceCommandAPI.http.spec.js +++ b/test/unit/controllers/DeviceCommandAPI.http.spec.js @@ -50,7 +50,8 @@ describe('DeviceCommandAPI HTTP', () => { login: `dhadmin`, password: `dhadmin_#911`, mainServiceURL: 'http://localhost:3390', - authServiceURL: 'http://localhost:3391' + authServiceURL: 'http://localhost:3391', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/DeviceCommandAPI.ws.spec.js b/test/unit/controllers/DeviceCommandAPI.ws.spec.js index 364e317..a690828 100644 --- a/test/unit/controllers/DeviceCommandAPI.ws.spec.js +++ b/test/unit/controllers/DeviceCommandAPI.ws.spec.js @@ -40,7 +40,8 @@ describe('DeviceCommandAPI WS', () => { deviceHive = new DeviceHive({ login: `dhadmin`, password: `dhadmin_#911`, - mainServiceURL: 'ws://localhost:4390' + mainServiceURL: 'ws://localhost:4390', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/DeviceNotificationAPI.http.spec.js b/test/unit/controllers/DeviceNotificationAPI.http.spec.js index 9332d71..26fa6fb 100644 --- a/test/unit/controllers/DeviceNotificationAPI.http.spec.js +++ b/test/unit/controllers/DeviceNotificationAPI.http.spec.js @@ -50,7 +50,8 @@ describe('NotificationAPI HTTP', () => { login: `dhadmin`, password: `dhadmin_#911`, mainServiceURL: 'http://localhost:3390', - authServiceURL: 'http://localhost:3391' + authServiceURL: 'http://localhost:3391', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/DeviceNotificationAPI.ws.spec.js b/test/unit/controllers/DeviceNotificationAPI.ws.spec.js index 52558b3..0386e3d 100644 --- a/test/unit/controllers/DeviceNotificationAPI.ws.spec.js +++ b/test/unit/controllers/DeviceNotificationAPI.ws.spec.js @@ -40,7 +40,8 @@ describe('NotificationAPI WS', () => { deviceHive = new DeviceHive({ login: `dhadmin`, password: `dhadmin_#911`, - mainServiceURL: 'ws://localhost:4390' + mainServiceURL: 'ws://localhost:4390', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/DeviceTypeAPI.http.spec.js b/test/unit/controllers/DeviceTypeAPI.http.spec.js index ca56fa0..89c44da 100644 --- a/test/unit/controllers/DeviceTypeAPI.http.spec.js +++ b/test/unit/controllers/DeviceTypeAPI.http.spec.js @@ -50,7 +50,8 @@ describe('DeviceTypeAPI HTTP', () => { login: `dhadmin`, password: `dhadmin_#911`, mainServiceURL: 'http://localhost:3390', - authServiceURL: 'http://localhost:3391' + authServiceURL: 'http://localhost:3391', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/DeviceTypeAPI.ws.spec.js b/test/unit/controllers/DeviceTypeAPI.ws.spec.js index 9d67940..f041ff2 100644 --- a/test/unit/controllers/DeviceTypeAPI.ws.spec.js +++ b/test/unit/controllers/DeviceTypeAPI.ws.spec.js @@ -40,7 +40,8 @@ describe('DeviceTypeAPI WS', () => { deviceHive = new DeviceHive({ login: `dhadmin`, password: `dhadmin_#911`, - mainServiceURL: 'ws://localhost:4390' + mainServiceURL: 'ws://localhost:4390', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/NetworkAPI.http.spec.js b/test/unit/controllers/NetworkAPI.http.spec.js index a60633e..b654370 100644 --- a/test/unit/controllers/NetworkAPI.http.spec.js +++ b/test/unit/controllers/NetworkAPI.http.spec.js @@ -50,7 +50,8 @@ describe('NetworkAPI', () => { login: `dhadmin`, password: `dhadmin_#911`, mainServiceURL: 'http://localhost:3390', - authServiceURL: 'http://localhost:3391' + authServiceURL: 'http://localhost:3391', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/NetworkAPI.ws.spec.js b/test/unit/controllers/NetworkAPI.ws.spec.js index 73f3e8e..a330a88 100644 --- a/test/unit/controllers/NetworkAPI.ws.spec.js +++ b/test/unit/controllers/NetworkAPI.ws.spec.js @@ -40,7 +40,8 @@ describe('NetworkAPI WS', () => { deviceHive = new DeviceHive({ login: `dhadmin`, password: `dhadmin_#911`, - mainServiceURL: 'ws://localhost:4390' + mainServiceURL: 'ws://localhost:4390', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/PluginAPI.http.spec.js b/test/unit/controllers/PluginAPI.http.spec.js index a7f8a39..fda4d71 100644 --- a/test/unit/controllers/PluginAPI.http.spec.js +++ b/test/unit/controllers/PluginAPI.http.spec.js @@ -73,6 +73,7 @@ describe('PluginAPI HTTP', () => { mainServiceURL: 'http://localhost:3390', authServiceURL: 'http://localhost:3391', pluginServiceURL: 'http://localhost:3392', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/ServerInfoAPI.http.spec.js b/test/unit/controllers/ServerInfoAPI.http.spec.js index 152ab7b..0f9a048 100644 --- a/test/unit/controllers/ServerInfoAPI.http.spec.js +++ b/test/unit/controllers/ServerInfoAPI.http.spec.js @@ -50,7 +50,8 @@ describe('InfoAPI HTTP', () => { login: `dhadmin`, password: `dhadmin_#911`, mainServiceURL: 'http://localhost:3390', - authServiceURL: 'http://localhost:3391' + authServiceURL: 'http://localhost:3391', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/ServerInfoAPI.ws.spec.js b/test/unit/controllers/ServerInfoAPI.ws.spec.js index 5f61a50..d41e76f 100644 --- a/test/unit/controllers/ServerInfoAPI.ws.spec.js +++ b/test/unit/controllers/ServerInfoAPI.ws.spec.js @@ -40,7 +40,8 @@ describe('InfoAPI WS', () => { deviceHive = new DeviceHive({ login: `dhadmin`, password: `dhadmin_#911`, - mainServiceURL: 'ws://localhost:4390' + mainServiceURL: 'ws://localhost:4390', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/TokenAPI.http.spec.js b/test/unit/controllers/TokenAPI.http.spec.js index aa58873..e75fb20 100644 --- a/test/unit/controllers/TokenAPI.http.spec.js +++ b/test/unit/controllers/TokenAPI.http.spec.js @@ -51,7 +51,8 @@ describe('TokenAPI HTTP', () => { login: `dhadmin`, password: `dhadmin_#911`, mainServiceURL: 'http://localhost:3390', - authServiceURL: 'http://localhost:3391' + authServiceURL: 'http://localhost:3391', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/TokenAPI.ws.spec.js b/test/unit/controllers/TokenAPI.ws.spec.js index de64cca..a1a455a 100644 --- a/test/unit/controllers/TokenAPI.ws.spec.js +++ b/test/unit/controllers/TokenAPI.ws.spec.js @@ -40,7 +40,8 @@ describe('TokenAPI WS', () => { deviceHive = new DeviceHive({ login: `dhadmin`, password: `dhadmin_#911`, - mainServiceURL: 'ws://localhost:4390' + mainServiceURL: 'ws://localhost:4390', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/UserAPI.http.spec.js b/test/unit/controllers/UserAPI.http.spec.js index 2f34cc0..a69244a 100644 --- a/test/unit/controllers/UserAPI.http.spec.js +++ b/test/unit/controllers/UserAPI.http.spec.js @@ -50,7 +50,8 @@ describe('UserAPI HTTP', () => { login: `dhadmin`, password: `dhadmin_#911`, mainServiceURL: 'http://localhost:3390', - authServiceURL: 'http://localhost:3391' + authServiceURL: 'http://localhost:3391', + autoUpdateSession: false }); deviceHive.connect() diff --git a/test/unit/controllers/UserAPI.ws.spec.js b/test/unit/controllers/UserAPI.ws.spec.js index ec91fb6..0b33f0b 100644 --- a/test/unit/controllers/UserAPI.ws.spec.js +++ b/test/unit/controllers/UserAPI.ws.spec.js @@ -40,7 +40,8 @@ describe('NetworkAPI WS', () => { deviceHive = new DeviceHive({ login: `dhadmin`, password: `dhadmin_#911`, - mainServiceURL: 'ws://localhost:4390' + mainServiceURL: 'ws://localhost:4390', + autoUpdateSession: false }); deviceHive.connect() From c96981d9ef78803a3124edea898dec404d4eaf00 Mon Sep 17 00:00:00 2001 From: itrambovetskiy Date: Mon, 26 Feb 2018 16:21:56 +0200 Subject: [PATCH 14/22] Plugin update test improvements --- .../integration/controllers/PluginAPI.spec.js | 33 ++++++++++++------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/test/integration/controllers/PluginAPI.spec.js b/test/integration/controllers/PluginAPI.spec.js index 83bd822..e53b5a8 100644 --- a/test/integration/controllers/PluginAPI.spec.js +++ b/test/integration/controllers/PluginAPI.spec.js @@ -24,8 +24,6 @@ const testPlugins = [ describe('PluginAPI', () => { before(done => { - // Configaratuion DeviceHive - Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) .then(() => done()); }); @@ -50,8 +48,6 @@ describe('PluginAPI', () => { }); it('PluginAPI.list()', done => { - - // Configurating Plugin List query const pluginListQuery = new DeviceHive.models.query.PluginListQuery({ take: 1, skip: 0 @@ -68,14 +64,31 @@ describe('PluginAPI', () => { }); - // TODO - // it('PluginAPI.update()', done => { - // }); + it('PluginAPI.update()', done => { + const updatedName = `${testPlugins[0].name}-updated`; + const pluginUpdateQuery = new DeviceHive.models.query.PluginUpdateQuery({ + topicName: testPlugins[0].topicName, + name: updatedName + }); + const pluginListQuery = new DeviceHive.models.query.PluginListQuery({ + name: updatedName, + take: 1, + skip: 0 + }); + Promise.all([httpDeviceHive.plugin.update(pluginUpdateQuery)]) + .then(() => Promise.all([httpDeviceHive.plugin.list(pluginListQuery)])) + .then(dataAll => { + for (const data of dataAll) { + assert.strictEqual(data[0].name, updatedName); + } + }) + .then(() => done()) + .catch(done); + }); - it('PluginAPI.count()', done => { - // Configurating Plugin List query + it('PluginAPI.count()', done => { const pluginCountQuery = new DeviceHive.models.query.PluginCountQuery({ status: '1' }); @@ -91,8 +104,6 @@ describe('PluginAPI', () => { }); it('TokenAPI.createPluginToken()', done => { - - // Configurating Token model const token = new DeviceHive.models.PluginToken({ actions: [0], expiration: '2018-02-09T10:09:03.033Z', From 4e8f0fbeea20dd2b09f6ead51e22812a0a5c3433 Mon Sep 17 00:00:00 2001 From: itrambovetskiy Date: Tue, 27 Feb 2018 10:27:27 +0200 Subject: [PATCH 15/22] Slight improvements --- example/node/index.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/example/node/index.js b/example/node/index.js index 475cbe0..9503faf 100644 --- a/example/node/index.js +++ b/example/node/index.js @@ -4,7 +4,6 @@ const DeviceHive = require(`../../index`); const httpDeviceHive = new DeviceHive({ login: `dhadmin`, password: `dhadmin_#911`, - accessToken: "eyJhbGciOiJIUzI1NiJ9.eyJwYXlsb2FkIjp7ImEiOlswXSwiZSI6MTUxOTY1MDIxMDgwNSwidCI6MSwidSI6MSwibiI6WyIqIl0sImR0IjpbIioiXX19.8MX7MiQeKmKCUGkNSqce1xCUTVBYX6GQKqgAwGvHB9Y", mainServiceURL: 'http://localhost:8080/dh/rest', authServiceURL: 'http://localhost:8090/dh/rest', pluginServiceURL: 'http://localhost:8110/dh/rest' @@ -13,7 +12,6 @@ const httpDeviceHive = new DeviceHive({ const wsDeviceHive = new DeviceHive({ login: `dhadmin`, password: `dhadmin_#911`, - accessToken: "eyJhbGciOiJIUzI1NiJ9.eyJwYXlsb2FkIjp7ImEiOlswXSwiZSI6MTUxOTY0OTczMDgwNSwidCI6MSwidSI6MSwibiI6WyIqIl0sImR0IjpbIioiXX19.3Kb1Lkqza0VzG8gsX2tlp5B5BcL2w55gVmMM1aMsDbY", mainServiceURL: 'ws://localhost:8080/dh/websocket', autoUpdateSession: true }); From 689528b6f79281288cd988fb89f43c5c9f7674fe Mon Sep 17 00:00:00 2001 From: itrambovetskiy Date: Tue, 27 Feb 2018 10:29:59 +0200 Subject: [PATCH 16/22] Documentation improvements --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7242ee3..6e7fee2 100644 --- a/README.md +++ b/README.md @@ -137,10 +137,11 @@ DeviceHive module | [options.accessToken] | string | Access token | | [options.refreshToken] | string | Refresh token | | [options.login] | string | Login | -| [options.password] | string | Paaword | +| [options.password] | string | Password | | options.mainServiceURL | string | Main Service URL | | [options.authServiceURL] | string | Auth Service URL (required only for http) | -| [options.pluginServiceURL] | string | Alug inServi ceURL (required only for http) | +| [options.pluginServiceURL] | string | Plugin Service URL (required only for http) | +| [options.autoUpdateSession] | boolean | Flag to enable/disable autoupdating session. Default: true | From 25f5600fb6def993328ddfa213770b7eb90a15e8 Mon Sep 17 00:00:00 2001 From: itrambovetskiy Date: Tue, 27 Feb 2018 10:31:32 +0200 Subject: [PATCH 17/22] Documentation improvements --- README.md | 9 --------- 1 file changed, 9 deletions(-) diff --git a/README.md b/README.md index 6e7fee2..f281922 100644 --- a/README.md +++ b/README.md @@ -2622,12 +2622,3 @@ Creates User List Query ### userListQuery.toObject() ⇒ Object Returns instance as a plain JS object - - - -## License - -[DeviceHive] is developed by [DataArt] Apps and distributed under Open Source -[Apache 2.0 license](https://en.wikipedia.org/wiki/Apache_License). - -© Copyright 2018 [DataArt] Apps © All Rights Reservedstrong text \ No newline at end of file From f5088934d938ea3b287e6080881fc8491e59f197 Mon Sep 17 00:00:00 2001 From: itrambovetskiy Date: Tue, 27 Feb 2018 10:32:11 +0200 Subject: [PATCH 18/22] Documentation improvements --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f281922..8f158b7 100644 --- a/README.md +++ b/README.md @@ -2553,7 +2553,7 @@ Creates Plugin Update Query model | [options.returnCommands] | boolean | Checks if commands should be returned | | [options.returnUpdatedCommands] | boolean | Checks if updated commands should be returned | | [options.returnNotifications] | boolean | Checks if commands should be returned | -| [options.status] | string | Plugin status - active or disabled (ACTIVE | DISABLED | CREATED) | +| [options.status] | string | Plugin status - active or disabled (ACTIVE | INACTIVE | CREATED) | | [options.name] | string | Plugin name | | [options.description] | string | Plugin description | | [options.parameters] | string | Plugin parameters | From dd8d8bee6c19b9018180dd0f3271a8077f92417e Mon Sep 17 00:00:00 2001 From: itrambovetskiy Date: Wed, 28 Feb 2018 18:36:12 +0200 Subject: [PATCH 19/22] Integration tests improvements --- package-lock.json | 13 + package.json | 1 + src/ApiStrategy.js | 17 +- src/DeviceHive.js | 10 + src/models/query/NotificationListQuery.js | 13 +- src/transports/HTTP.js | 9 + src/transports/WS.js | 9 + src/transports/base/Transport.js | 7 + test/integration/config.json | 3 + .../controllers/ConfigurationAPI.spec.js | 91 +++-- test/integration/controllers/Device.spec.js | 148 ++++---- .../controllers/DeviceCommandAPI.spec.js | 316 +++++++++++++----- .../controllers/DeviceNotificationAPI.spec.js | 244 +++++++++----- .../controllers/DeviceTypeAPI.spec.js | 185 ++++++---- .../controllers/NetworkAPI.spec.js | 188 ++++++----- .../integration/controllers/PluginAPI.spec.js | 139 +++----- .../controllers/ServerInfoAPI.spec.js | 69 ++-- test/integration/controllers/TokenAPI.spec.js | 195 +++++++---- test/integration/controllers/UserAPI.spec.js | 271 ++++++++------- 19 files changed, 1208 insertions(+), 720 deletions(-) diff --git a/package-lock.json b/package-lock.json index 305e6f1..50c6c3e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -687,6 +687,11 @@ "integrity": "sha1-FziZ0//Rx9k4PkR5Ul2+J4yrXys=", "dev": true }, + "array-uniq": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.2.tgz", + "integrity": "sha1-X8w3OSB3VyPP1k1lxkvvU7+eum0=" + }, "array-unique": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.2.1.tgz", @@ -3425,6 +3430,14 @@ "safe-buffer": "5.1.1" } }, + "randomstring": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/randomstring/-/randomstring-1.1.5.tgz", + "integrity": "sha1-bfBij3XL1ZMpMNn+OrTpVqGFGMM=", + "requires": { + "array-uniq": "1.0.2" + } + }, "read-only-stream": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/read-only-stream/-/read-only-stream-2.0.0.tgz", diff --git a/package.json b/package.json index 686702e..b55b983 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,7 @@ "isomorphic-fetch": "^2.2.1", "jwt-decode": "^2.2.0", "query-string": "^5.1.0", + "randomstring": "^1.1.5", "string-template": "^1.0.0", "universal-websocket-client": "^1.0.1" }, diff --git a/src/ApiStrategy.js b/src/ApiStrategy.js index 73a0296..85d2b55 100644 --- a/src/ApiStrategy.js +++ b/src/ApiStrategy.js @@ -50,7 +50,13 @@ class ApiStrategy extends EventEmitter { me.strategy = new (ApiStrategy.getType(mainServiceURL))({ mainServiceURL, authServiceURL, pluginServiceURL }); - me.strategy.on(`message`, (message) => { me.emit(`message`, message) }); + me.strategy.on(`message`, (message) => { + if (message.subscriptionId && message.action) { + me.emit(`message`, message[message.action.split(`/`)[0]]); + } else { + me.emit(`message`, message); + } + }); } @@ -96,6 +102,15 @@ class ApiStrategy extends EventEmitter { } }); } + + /** + * Disconnects transport + */ + disconnect() { + const me = this; + + me.strategy.disconnect(); + } } diff --git a/src/DeviceHive.js b/src/DeviceHive.js index e606e23..82e3c5a 100644 --- a/src/DeviceHive.js +++ b/src/DeviceHive.js @@ -181,6 +181,16 @@ class DeviceHive extends EventEmitter { return me; } + + /** + * Disconnects from DeviceHive server + * @returns {*|void} + */ + disconnect() { + const me = this; + + return me.strategy.disconnect(); + } } diff --git a/src/models/query/NotificationListQuery.js b/src/models/query/NotificationListQuery.js index 8fdc3ba..01ac544 100644 --- a/src/models/query/NotificationListQuery.js +++ b/src/models/query/NotificationListQuery.js @@ -13,20 +13,18 @@ class NotificationListQuery extends BaseModel { * @param {string} options.start - Start timestamp * @param {string} options.end - End timestamp * @param {string} options.notification - Notification name - * @param {string} options.status - Command status * @param {string} options.sortField - Sort field * @param {string} options.sortOrder - Sort order * @param {number} options.take - Limit param * @param {number} options.skip - Skip param */ - constructor({ deviceId, start, end, notification, status, sortField, sortOrder, take, skip } = {}) { + constructor({ deviceId, start, end, notification, sortField, sortOrder, take, skip } = {}) { super(); this.deviceId = deviceId; this.start = start; this.end = end; this.notification = notification; - this.status = status; this.sortField = sortField; this.sortOrder = sortOrder; this.take = take; @@ -65,14 +63,6 @@ class NotificationListQuery extends BaseModel { this._notification = value; } - get status() { - return this._status; - } - - set status(value) { - this._status = value; - } - get sortField() { return this._sortField; } @@ -115,7 +105,6 @@ class NotificationListQuery extends BaseModel { start: this.start, end: this.end, notification: this.notification, - status: this.status, sortField: this.sortField, sortOrder: this.sortOrder, take: this.take, diff --git a/src/transports/HTTP.js b/src/transports/HTTP.js index d5ab869..cba6109 100644 --- a/src/transports/HTTP.js +++ b/src/transports/HTTP.js @@ -123,6 +123,15 @@ class HTTP extends Transport { return headers; } + + /** + * Disconnects HTTP transport + */ + disconnect() { + const me = this; + + me.token= ``; + } } diff --git a/src/transports/WS.js b/src/transports/WS.js index 2e88f24..4c6b792 100644 --- a/src/transports/WS.js +++ b/src/transports/WS.js @@ -98,6 +98,15 @@ class WS extends Transport { }); }); } + + /** + * Disconnects WS transport + */ + disconnect() { + const me = this; + + me.socket.close(); + } } diff --git a/src/transports/base/Transport.js b/src/transports/base/Transport.js index 0d832af..1e06051 100644 --- a/src/transports/base/Transport.js +++ b/src/transports/base/Transport.js @@ -20,6 +20,13 @@ class Transport extends EventEmitter { send() { console.warn(`Method "send" should be implemented in nested classes`); } + + /** + * Disconnects transport + */ + disconnect() { + console.warn(`Method "disconnect" should be implemented in nested classes`); + } } diff --git a/test/integration/config.json b/test/integration/config.json index dab5212..5711a14 100644 --- a/test/integration/config.json +++ b/test/integration/config.json @@ -1,4 +1,7 @@ { + "TEST_USER_ID": 1, + "TEST_USER_LOGIN": "dhadmin", + "TEST_USER_PASSWORD": "dhadmin_#911", "server": { "http": { "login": "dhadmin", diff --git a/test/integration/controllers/ConfigurationAPI.spec.js b/test/integration/controllers/ConfigurationAPI.spec.js index 508479e..2d9d7dc 100644 --- a/test/integration/controllers/ConfigurationAPI.spec.js +++ b/test/integration/controllers/ConfigurationAPI.spec.js @@ -1,66 +1,97 @@ const chai = require(`chai`); const assert = chai.assert; const config = require('../config'); - -const EventEmitter = require('events'); -const events = new EventEmitter(); - const DeviceHive = require('../../../index'); +const Configuration = DeviceHive.models.Configuration; const httpDeviceHive = new DeviceHive(config.server.http); const wsDeviceHive = new DeviceHive(config.server.ws); -const testConfigurations = [ - { - name: 'myTestName', - value: 'string' +const TEST_CONFIGURATIONS = { + HTTP: { + name: `myTestConfigurationName-HTTP}`, + value: `myTestConfigurationValue-HTTP}` }, - { - name: 'myTestName2', - value: 'string' + WS: { + name: `myTestConfigurationName-WS}`, + value: `myTestConfigurationValue-WS}` } -]; +}; describe('ConfigurationAPI', () => { before(done => { - // Configaratuion DeviceHive Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) .then(() => done()); }); + it(`should add new configuration with name ${TEST_CONFIGURATIONS.HTTP.name} and value ${TEST_CONFIGURATIONS.HTTP.value} via HTTP`, (done) => { + const configurationModel = new Configuration(TEST_CONFIGURATIONS.HTTP); - it('ConfigurationAPI.put()', done => { - - // Configurating Configaration model - const configuration = new DeviceHive.models.Configuration(testConfigurations[0]); - const configuration2 = new DeviceHive.models.Configuration(testConfigurations[1]); - - Promise.all([httpDeviceHive.configuration.put(configuration), wsDeviceHive.configuration.put(configuration2)]) + httpDeviceHive.configuration.put(configurationModel) .then(() => done()) .catch(done); }); + it(`should add new configuration with name ${TEST_CONFIGURATIONS.WS.name} and value ${TEST_CONFIGURATIONS.WS.value} via WS`, (done) => { + const configurationModel = new Configuration(TEST_CONFIGURATIONS.WS); - it('ConfigurationAPI.get()', done => { + wsDeviceHive.configuration.put(configurationModel) + .then(() => done()) + .catch(done); + }); - Promise.all([httpDeviceHive.configuration.get(testConfigurations[0].name), wsDeviceHive.configuration.get(testConfigurations[1].name)]) - .then(dataAll => { - for (const key in dataAll) { - assert.isObject(dataAll[key]) - assert.include(dataAll[key], testConfigurations[key]); - } + it(`should get configuration with name ${TEST_CONFIGURATIONS.HTTP.name} and value ${TEST_CONFIGURATIONS.HTTP.value} via HTTP`, done => { + httpDeviceHive.configuration.get(TEST_CONFIGURATIONS.HTTP.name) + .then(configuration => { + assert.isObject(configuration); + assert.equal(configuration.name, TEST_CONFIGURATIONS.HTTP.name); + assert.equal(configuration.value, TEST_CONFIGURATIONS.HTTP.value); }) - .then(done) + .then(() => done()) .catch(done); }); + it(`should get configuration with name ${TEST_CONFIGURATIONS.WS.name} and value ${TEST_CONFIGURATIONS.WS.value} via WS`, done => { + wsDeviceHive.configuration.get(TEST_CONFIGURATIONS.WS.name) + .then(configuration => { + assert.isObject(configuration); + assert.equal(configuration.name, TEST_CONFIGURATIONS.WS.name); + assert.equal(configuration.value, TEST_CONFIGURATIONS.WS.value); + }) + .then(() => done()) + .catch(done); + }); - it('ConfigurationAPI.delete()', done => { + it(`should delete configuration with name ${TEST_CONFIGURATIONS.HTTP.name} and value ${TEST_CONFIGURATIONS.HTTP.value} via HTTP`, done => { + httpDeviceHive.configuration.delete(TEST_CONFIGURATIONS.HTTP.name) + .then(() => done()) + .catch(done); + }); - Promise.all([httpDeviceHive.configuration.delete(testConfigurations[0].name), wsDeviceHive.configuration.delete(testConfigurations[1].name)]) + it(`should delete configuration with name ${TEST_CONFIGURATIONS.WS.name} and value ${TEST_CONFIGURATIONS.WS.value} via WS`, done => { + wsDeviceHive.configuration.delete(TEST_CONFIGURATIONS.WS.name) .then(() => done()) .catch(done); }); + + it(`should not get configuration with name ${TEST_CONFIGURATIONS.HTTP.name} and value ${TEST_CONFIGURATIONS.HTTP.value} via HTTP`, done => { + httpDeviceHive.configuration.get(TEST_CONFIGURATIONS.HTTP.name) + .then(() => done(new Error(`Configuration exists after deletion`))) + .catch(() => done()); + }); + + it(`should not get configuration with name ${TEST_CONFIGURATIONS.WS.name} and value ${TEST_CONFIGURATIONS.WS.value} via WS`, done => { + wsDeviceHive.configuration.get(TEST_CONFIGURATIONS.WS.name) + .then(() => done(new Error(`Configuration exists after deletion`))) + .catch(() => done()); + }); + + after(done => { + httpDeviceHive.disconnect(); + wsDeviceHive.disconnect(); + + done(); + }); }); \ No newline at end of file diff --git a/test/integration/controllers/Device.spec.js b/test/integration/controllers/Device.spec.js index e0329d7..7f349f3 100644 --- a/test/integration/controllers/Device.spec.js +++ b/test/integration/controllers/Device.spec.js @@ -1,118 +1,142 @@ const chai = require(`chai`); const assert = chai.assert; const config = require('../config'); - -const EventEmitter = require('events'); -const events = new EventEmitter(); - const DeviceHive = require('../../../index'); +const Device = DeviceHive.models.Device; +const DeviceListQuery = DeviceHive.models.query.DeviceListQuery; const httpDeviceHive = new DeviceHive(config.server.http); const wsDeviceHive = new DeviceHive(config.server.ws); -const testDevices = [ - { - id: 'myTestId', - name: 'myTestName', +const TEST_DEVICE_ID_PREFIX = `DH-JS-LIB-DEVICE-ID-`; +const TEST_DEVICE_NAME_PREFIX = `DH-JS-LIB-DEVICE-NAME-`; +const TEST_DEVICES = { + HTTP: { + id: `${TEST_DEVICE_ID_PREFIX}HTTP`, + name: `${TEST_DEVICE_NAME_PREFIX}HTTP`, networkId: 1, deviceTypeId: 1, - isBlocked: false - }, { - id: 'myTestId2', - name: 'myTestName', + isBlocked: false, + data: {} + }, + WS: { + id: `${TEST_DEVICE_ID_PREFIX}WS`, + name: `${TEST_DEVICE_NAME_PREFIX}WS`, networkId: 1, deviceTypeId: 1, - isBlocked: false + isBlocked: false, + data: {} } -]; +}; describe('DeviceAPI', () => { before(done => { - // Configaratuion DeviceHive - Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) .then(() => done()); }); + it(`should add new device with next configuration: ${JSON.stringify(TEST_DEVICES.HTTP)} via HTTP`, done => { + const deviceModel = new Device(TEST_DEVICES.HTTP); - it('DeviceAPI.add()', done => { - - // Configurating Device model - const Device = DeviceHive.models.Device; + httpDeviceHive.device.add(deviceModel) + .then(() => done()) + .catch(done); + }); - const device = new Device(testDevices[0]); - const device2 = new Device(testDevices[1]); + it(`should add new device with next configuration: ${JSON.stringify(TEST_DEVICES.WS)} via WS`, done => { + const deviceModel = new Device(TEST_DEVICES.WS); - Promise.all([httpDeviceHive.device.add(device), wsDeviceHive.device.add(device2)]) + wsDeviceHive.device.add(deviceModel) .then(() => done()) .catch(done); }); + it(`should get device with next configuration: ${JSON.stringify(TEST_DEVICES.HTTP)} via HTTP`, done => { + httpDeviceHive.device.get(TEST_DEVICES.HTTP.id) + .then(device => { + assert.isObject(device); + assert.deepEqual(device, TEST_DEVICES.HTTP); + }) + .then(() => done()) + .catch(done); + }); - it('DeviceAPI.get()', done => { + it(`should get device with next configuration: ${JSON.stringify(TEST_DEVICES.WS)} via WS`, done => { + wsDeviceHive.device.get(TEST_DEVICES.WS.id) + .then(device => { + assert.isObject(device); + assert.deepEqual(device, TEST_DEVICES.WS); + }) + .then(() => done()) + .catch(done); + }); - const expected = { - deviceId: testDevices[0].id - }; + it(`should list all devices with the next name pattern "${TEST_DEVICE_NAME_PREFIX}%" via HTTP`, done => { + const deviceListQuery = new DeviceListQuery({ namePattern: `${TEST_DEVICE_NAME_PREFIX}%` }); - Promise.all([httpDeviceHive.device.get(expected.deviceId), wsDeviceHive.device.get(expected.deviceId)]) - .then(dataAll => { - for (const data of dataAll) { - assert.isObject(data) - assert.include(data, testDevices[0]); - } + httpDeviceHive.device.list(deviceListQuery) + .then(devices => { + assert.equal(devices.length, Object.keys(TEST_DEVICES).length); }) - .then(done) + .then(() => done()) .catch(done); }); + it(`should list all devices with the next name pattern "${TEST_DEVICE_NAME_PREFIX}%" via WS`, done => { + const deviceListQuery = new DeviceListQuery({ namePattern: `${TEST_DEVICE_NAME_PREFIX}%` }); - it('DeviceAPI.list()', done => { - - // Configurating Device List query - const deviceListQuery = new DeviceHive.models.query.DeviceListQuery({ - networkId: 1 - }); + wsDeviceHive.device.list(deviceListQuery) + .then(devices => { + assert.equal(devices.length, Object.keys(TEST_DEVICES).length); + }) + .then(() => done()) + .catch(done); + }); + it(`should count devices with the next name pattern "${TEST_DEVICE_NAME_PREFIX}%" via HTTP`, done => { + const deviceListQuery = new DeviceListQuery({ namePattern: `${TEST_DEVICE_NAME_PREFIX}%` }); - Promise.all([httpDeviceHive.device.list(deviceListQuery), wsDeviceHive.device.list(deviceListQuery)]) - .then(dataAll => { - for (const data of dataAll) { - for (const device of data) { - assert.containsAllKeys(device, Object.keys(testDevices[0])); - } - } + httpDeviceHive.device.count(deviceListQuery) + .then(response => { + assert.equal(response.count, Object.keys(TEST_DEVICES).length); }) .then(done) .catch(done); - }); + it(`should count devices with the next name pattern "${TEST_DEVICE_NAME_PREFIX}%" via WS`, done => { + const deviceListQuery = new DeviceListQuery({ namePattern: `${TEST_DEVICE_NAME_PREFIX}%` }); - it('DeviceAPI.count()', done => { - - // Configurating Device List query - const deviceListQuery = new DeviceHive.models.query.DeviceCountQuery({ - networkId: '1' - }); - - Promise.all([httpDeviceHive.device.count(deviceListQuery), wsDeviceHive.device.count(deviceListQuery)]) - .then(dataAll => { - for (const data of dataAll) { - assert.property(data, 'count'); - } + wsDeviceHive.device.count(deviceListQuery) + .then(response => { + assert.equal(response.count, Object.keys(TEST_DEVICES).length); }) .then(done) .catch(done); }); + it(`should delete device with next configuration: ${JSON.stringify(TEST_DEVICES.HTTP)} via HTTP`, done => { + const deviceModel = new Device(TEST_DEVICES.HTTP); + + httpDeviceHive.device.delete(deviceModel.id) + .then(() => done()) + .catch(done); + }); - it('DeviceAPI.delete()', done => { + it(`should delete device with next configuration: ${JSON.stringify(TEST_DEVICES.WS)} via WS`, done => { + const deviceModel = new Device(TEST_DEVICES.WS); - Promise.all([httpDeviceHive.device.delete(testDevices[0].id), wsDeviceHive.device.delete(testDevices[1].id)]) + wsDeviceHive.device.delete(deviceModel.id) .then(() => done()) .catch(done); }); + + after(done => { + httpDeviceHive.disconnect(); + wsDeviceHive.disconnect(); + + done(); + }); }); \ No newline at end of file diff --git a/test/integration/controllers/DeviceCommandAPI.spec.js b/test/integration/controllers/DeviceCommandAPI.spec.js index eba276c..d1e4e52 100644 --- a/test/integration/controllers/DeviceCommandAPI.spec.js +++ b/test/integration/controllers/DeviceCommandAPI.spec.js @@ -1,25 +1,36 @@ +const randomString = require(`randomstring`); const chai = require(`chai`); const assert = chai.assert; const config = require('../config'); - -const EventEmitter = require('events'); -const events = new EventEmitter(); - const DeviceHive = require('../../../index'); +const Device = DeviceHive.models.Device; +const Command = DeviceHive.models.Command; +const CommandListQuery = DeviceHive.models.query.CommandListQuery; +const CommandPollQuery = DeviceHive.models.query.CommandPollQuery; +const CommandPollManyQuery = DeviceHive.models.query.CommandPollManyQuery; +const CommandWaitQuery = DeviceHive.models.query.CommandWaitQuery; const httpDeviceHive = new DeviceHive(config.server.http); const wsDeviceHive = new DeviceHive(config.server.ws); -const deviceId = 'e50d6085-2aba-48e9-b1c3-73c673e414be'; -const testDeviceCommands = [ - { - deviceId, - command: 'command', - timestamp: new Date().toISOString(), - lastUpdated: new Date().toISOString(), +const TIMESTAMP = new Date().toISOString(); +const DH_COMMANDS_TEST_DEVICE = { + id: randomString.generate(), + name: `DH_COMMANDS_TEST_DEVICE`, + networkId: 1, + deviceTypeId: 1, + isBlocked: false, + data: {} +}; +const TEST_DEVICE_COMMANDS = { + HTTP: { + deviceId: DH_COMMANDS_TEST_DEVICE.id, + command: `command-${randomString.generate()}`, + timestamp: TIMESTAMP, userId: 1, networkId: 1, + deviceTypeId: 1, parameters: { jsonString: 'jsonString' }, @@ -29,13 +40,13 @@ const testDeviceCommands = [ jsonString: 'jsonString' } }, - { - deviceId, - command: 'command2', - timestamp: new Date().toISOString(), - lastUpdated: new Date().toISOString(), + WS: { + deviceId: DH_COMMANDS_TEST_DEVICE.id, + command: `command-${randomString.generate()}`, + timestamp: TIMESTAMP, userId: 1, networkId: 1, + deviceTypeId: 1, parameters: { jsonString: 'jsonString' }, @@ -45,141 +56,262 @@ const testDeviceCommands = [ jsonString: 'jsonString' } } -]; +}; describe('DeviceCommandAPI', () => { before(done => { - // Configaratuion DeviceHive Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) - .then(() => done()); + .then(() => httpDeviceHive.device.add(new Device(DH_COMMANDS_TEST_DEVICE))) + .then(() => done()) + .catch(done); }); + it(`should insert new command with name ${TEST_DEVICE_COMMANDS.HTTP.command} via HTTP`, done => { + const commandModel = new Command(TEST_DEVICE_COMMANDS.HTTP); - it('DeviceCommandAPI.insert()', done => { - const command = new DeviceHive.models.Command(testDeviceCommands[0]); - const command2 = new DeviceHive.models.Command(testDeviceCommands[1]); + httpDeviceHive.command.insert(DH_COMMANDS_TEST_DEVICE.id, commandModel) + .then((commandResponse) => { + TEST_DEVICE_COMMANDS.HTTP.id = commandResponse.id; - Promise.all([httpDeviceHive.command.insert(deviceId, command), wsDeviceHive.command.insert(deviceId, command2)]) - .then(() => done()) + done(); + }) .catch(done); }); + it(`should insert new command with name ${TEST_DEVICE_COMMANDS.WS.command} via WS`, done => { + const commandModel = new Command(TEST_DEVICE_COMMANDS.WS); - it('DeviceCommandAPI.list()', done => { + wsDeviceHive.command.insert(DH_COMMANDS_TEST_DEVICE.id, commandModel) + .then((commandResponse) => { + TEST_DEVICE_COMMANDS.WS.id = commandResponse.id; - // Configurating Device List query - const commandListQuery = new DeviceHive.models.query.CommandListQuery({ - deviceId, - command: 'command', - status: 'status', - sortField: 'id', - sortOrder: 'id', - take: 2, - skip: 0 + done(); + }) + .catch(done); + }); + + it(`should list all commands for device with id ${DH_COMMANDS_TEST_DEVICE.id} via HTTP`, done => { + const commandListQuery = new CommandListQuery({ + deviceId: DH_COMMANDS_TEST_DEVICE.id }); - Promise.all([httpDeviceHive.command.list(commandListQuery), wsDeviceHive.command.list(commandListQuery)]) - .then(dataAll => { - for (const data of dataAll) { - for (const deviceCommandKey in data) { - testDeviceCommands[deviceCommandKey].id = data[deviceCommandKey].id; - testDeviceCommands[deviceCommandKey].timestamp = data[deviceCommandKey].timestamp; - testDeviceCommands[deviceCommandKey].lastUpdated = data[deviceCommandKey].lastUpdated; - assert.containsAllKeys(data[deviceCommandKey], Object.keys(testDeviceCommands[0])); - } - } + httpDeviceHive.command.list(commandListQuery) + .then(commands => { + assert.equal(commands.length, Object.keys(TEST_DEVICE_COMMANDS).length); }) - .then(done) + .then(() => done()) .catch(done); }); + it(`should list all commands for device with id ${DH_COMMANDS_TEST_DEVICE.id} via WS`, done => { + const commandListQuery = new CommandListQuery({ + deviceId: DH_COMMANDS_TEST_DEVICE.id + }); - it('DeviceCommand API.get()', done => { + wsDeviceHive.command.list(commandListQuery) + .then(commands => { + assert.equal(commands.length, Object.keys(TEST_DEVICE_COMMANDS).length); + }) + .then(() => done()) + .catch(done); + }); + it(`should get command with id ${TEST_DEVICE_COMMANDS.HTTP.id} for device with id ${DH_COMMANDS_TEST_DEVICE.id} via HTTP`, done => { + httpDeviceHive.command.get(DH_COMMANDS_TEST_DEVICE.id, TEST_DEVICE_COMMANDS.HTTP.id) + .then(command => { + assert.equal(command.id, TEST_DEVICE_COMMANDS.HTTP.id); + }) + .then(done) + .catch(done); + }); - Promise.all([httpDeviceHive.command.get(deviceId, testDeviceCommands[0].id), wsDeviceHive.command.get(deviceId, testDeviceCommands[0].id)]) - .then(dataAll => { - const expected = testDeviceCommands[0]; - for (const data of dataAll) { - assert.isObject(data); - assert.deepInclude(data, expected); - } + it(`should get command with id ${TEST_DEVICE_COMMANDS.WS.id} for device with id ${DH_COMMANDS_TEST_DEVICE.id} via WS`, done => { + wsDeviceHive.command.get(DH_COMMANDS_TEST_DEVICE.id, TEST_DEVICE_COMMANDS.WS.id) + .then(command => { + assert.equal(command.id, TEST_DEVICE_COMMANDS.WS.id); }) .then(done) .catch(done); }); + it(`should update command with id ${TEST_DEVICE_COMMANDS.HTTP.id} for device with id ${DH_COMMANDS_TEST_DEVICE.id} via HTTP`, done => { + TEST_DEVICE_COMMANDS.HTTP.status = `status-${randomString.generate()}`; - it('DeviceCommandAPI.update()', done => { + const commandModel = new Command(TEST_DEVICE_COMMANDS.HTTP); - const command = new DeviceHive.models.Command(testDeviceCommands[0], testDeviceCommands[0]); - const command2 = new DeviceHive.models.Command(testDeviceCommands[0], testDeviceCommands[1]); + httpDeviceHive.command.update(commandModel) + .then(() => httpDeviceHive.command.get(DH_COMMANDS_TEST_DEVICE.id, TEST_DEVICE_COMMANDS.HTTP.id)) + .then((command) => { + assert.equal(command.status, TEST_DEVICE_COMMANDS.HTTP.status); - Promise.all([httpDeviceHive.command.update(command), wsDeviceHive.command.update(command2)]) - .then(() => done()) + done(); + }) .catch(done); }); + it(`should update command with id ${TEST_DEVICE_COMMANDS.HTTP.id} for device with id ${DH_COMMANDS_TEST_DEVICE.id} via WS`, done => { + TEST_DEVICE_COMMANDS.WS.status = `status-${randomString.generate()}`; - it('DeviceCommandAPI.poll()', done => { + const commandModel = new Command(TEST_DEVICE_COMMANDS.WS); - // Configurating Command List query - const commandPollQuery = new DeviceHive.models.query.CommandPollQuery({ - deviceId, - returnUpdatedCommands: true, - limit: 1, + wsDeviceHive.command.update(commandModel) + .then(() => wsDeviceHive.command.get(DH_COMMANDS_TEST_DEVICE.id, TEST_DEVICE_COMMANDS.WS.id)) + .then((command) => { + assert.equal(command.status, TEST_DEVICE_COMMANDS.WS.status); + + done(); + }) + .catch(done); + }); + + it(`should poll new command for device with id ${DH_COMMANDS_TEST_DEVICE.id} via HTTP`, done => { + const commandPollQuery = new CommandPollQuery({ + deviceId: DH_COMMANDS_TEST_DEVICE.id, waitTimeout: 1 }); httpDeviceHive.command.poll(commandPollQuery) - .then(() => done()) + .then((commands) => { + assert.equal(commands.length, 1); + assert.equal(commands[0].command, TEST_DEVICE_COMMANDS.HTTP.command); + + TEST_DEVICE_COMMANDS.HTTP.id = commands[0].id; + done(); + }) .catch(done); - // emit command setTimeout(() => { - const command = new DeviceHive.models.Command(testDeviceCommands[0]); - httpDeviceHive.command.insert(deviceId, command); - }, 50); + TEST_DEVICE_COMMANDS.HTTP.command = `command-${randomString.generate()}`; + httpDeviceHive.command.insert(DH_COMMANDS_TEST_DEVICE.id, new Command(TEST_DEVICE_COMMANDS.HTTP)); + }, 100); }); + it(`should poll command update for device with id ${DH_COMMANDS_TEST_DEVICE.id} via HTTP`, done => { + const commandPollQuery = new CommandPollQuery({ + deviceId: DH_COMMANDS_TEST_DEVICE.id, + returnUpdatedCommands: true, + waitTimeout: 1 + }); - it('DeviceCommandAPI.pollMany()', done => { + httpDeviceHive.command.poll(commandPollQuery) + .then((commands) => { + assert.equal(commands.length, 1); + assert.equal(commands[0].command, TEST_DEVICE_COMMANDS.HTTP.command); + assert.equal(commands[0].status, TEST_DEVICE_COMMANDS.HTTP.status); - const commandPollManyQuery = new DeviceHive.models.query.CommandPollManyQuery({ - deviceIds: deviceId + TEST_DEVICE_COMMANDS.HTTP.id = commands[0].id; + done(); + }) + .catch(done); + + setTimeout(() => { + TEST_DEVICE_COMMANDS.HTTP.status = `status-${randomString.generate()}`; + httpDeviceHive.command.update(new Command(TEST_DEVICE_COMMANDS.HTTP)); + }, 100); + }); + + it(`should poll new command for network with id ${DH_COMMANDS_TEST_DEVICE.networkId} via HTTP`, done => { + const commandPollManyQuery = new CommandPollManyQuery({ + networkIds: [ DH_COMMANDS_TEST_DEVICE.networkId ], + waitTimeout: 1 }); httpDeviceHive.command.pollMany(commandPollManyQuery) - .then(() => done()) + .then((commands) => { + assert.equal(commands.length, 1); + assert.equal(commands[0].command, TEST_DEVICE_COMMANDS.HTTP.command); + + done(); + }) .catch(done); - // emit command setTimeout(() => { - const command = new DeviceHive.models.Command(testDeviceCommands[0]); - httpDeviceHive.command.insert(deviceId, command); - }, 50); + TEST_DEVICE_COMMANDS.HTTP.command = `command-${randomString.generate()}`; + httpDeviceHive.command.insert(DH_COMMANDS_TEST_DEVICE.id, new Command(TEST_DEVICE_COMMANDS.HTTP)); + }, 100); }); + it(`should wait while command will be processed by device with id ${DH_COMMANDS_TEST_DEVICE.id}`, done => { + const commandWaitQuery = new CommandWaitQuery({ waitTimeout: 1 }); + + httpDeviceHive.command.wait(DH_COMMANDS_TEST_DEVICE.id, TEST_DEVICE_COMMANDS.HTTP.id, commandWaitQuery) + .then((command) => { + assert.equal(command.status, TEST_DEVICE_COMMANDS.HTTP.status); + + done() + }) + .catch(done); + + setTimeout(() => { + TEST_DEVICE_COMMANDS.HTTP.command = `command-${randomString.generate()}`; - it('DeviceCommandAPI.wait()', done => { + httpDeviceHive.command.insert(DH_COMMANDS_TEST_DEVICE.id, new Command(TEST_DEVICE_COMMANDS.HTTP)) + .then(() => { + TEST_DEVICE_COMMANDS.HTTP.status = `status-${randomString.generate()}`; - // TODO - done(); + httpDeviceHive.command.update(new Command(TEST_DEVICE_COMMANDS.HTTP)); + }); + }, 100); + }); - // Configurating Command List query - // const commandWaitQuery = new DeviceHive.models.query.CommandWaitQuery({ - // deviceId, - // commandId: testDeviceCommands[0].id, - // waitTimeout: 1 - // }); + it(`should subscribe for command insertion notifications on device with id ${DH_COMMANDS_TEST_DEVICE.id} via HTTP`, done => { + const commandPollQuery = new CommandPollQuery({ deviceId: DH_COMMANDS_TEST_DEVICE.id }); + let subscriptionId; + + httpDeviceHive.command.subscribe(commandPollQuery) + .then((response) => { + subscriptionId = response.subscriptionId; + + setTimeout(() => { + httpDeviceHive.on(`message`, (command) => { + assert.equal(command.command, TEST_DEVICE_COMMANDS.HTTP.command); + httpDeviceHive.command.unsubscribe(subscriptionId) + .then(() => done()) + .catch(done); + }); + }, 200); + + setTimeout(() => { + TEST_DEVICE_COMMANDS.HTTP.command = `command-${randomString.generate()}`; + httpDeviceHive.command.insert(DH_COMMANDS_TEST_DEVICE.id, new Command(TEST_DEVICE_COMMANDS.HTTP)); + }, 300); + }) + .catch(done); + }); + + it(`should subscribe for command insertion notifications on device with id ${DH_COMMANDS_TEST_DEVICE.id} via WS`, done => { + const commandPollQuery = new CommandPollQuery({ deviceId: DH_COMMANDS_TEST_DEVICE.id }); + let subscriptionId; + + wsDeviceHive.command.subscribe(commandPollQuery) + .then((response) => { + subscriptionId = response.subscriptionId; + + setTimeout(() => { + wsDeviceHive.on(`message`, (command) => { + assert.equal(command.command, TEST_DEVICE_COMMANDS.WS.command); + wsDeviceHive.command.unsubscribe(subscriptionId) + .then(() => done()) + .catch(done); + }); + }, 200); + + setTimeout(() => { + TEST_DEVICE_COMMANDS.WS.command = `command-${randomString.generate()}`; + wsDeviceHive.command.insert(DH_COMMANDS_TEST_DEVICE.id, new Command(TEST_DEVICE_COMMANDS.WS)); + }, 300); + }) + .catch(done); + }); - // httpDeviceHive.command.wait(commandWaitQuery.deviceId, commandWaitQuery.commandId, commandWaitQuery) - // .then(() => done()) - // .catch(done); + after(done => { + httpDeviceHive.device.delete(DH_COMMANDS_TEST_DEVICE.id) + .then(() => { + httpDeviceHive.disconnect(); + wsDeviceHive.disconnect(); - // // emit command - // const command = new DeviceHive.models.Command(testDeviceCommands[0]); - // httpDeviceHive.command.insert(deviceId, command); + done(); + }); }); }); \ No newline at end of file diff --git a/test/integration/controllers/DeviceNotificationAPI.spec.js b/test/integration/controllers/DeviceNotificationAPI.spec.js index c4d42a8..f58124c 100644 --- a/test/integration/controllers/DeviceNotificationAPI.spec.js +++ b/test/integration/controllers/DeviceNotificationAPI.spec.js @@ -1,135 +1,227 @@ +const randomString = require(`randomstring`); const chai = require(`chai`); const assert = chai.assert; const config = require('../config'); - -const EventEmitter = require('events'); -const events = new EventEmitter(); - const DeviceHive = require('../../../index'); +const Device = DeviceHive.models.Device; +const Notification = DeviceHive.models.Notification; +const NotificationListQuery = DeviceHive.models.query.NotificationListQuery; +const NotificationPollQuery = DeviceHive.models.query.NotificationPollQuery; +const NotificationPollManyQuery = DeviceHive.models.query.NotificationPollManyQuery; const httpDeviceHive = new DeviceHive(config.server.http); const wsDeviceHive = new DeviceHive(config.server.ws); -const deviceId = 'e50d6085-2aba-48e9-b1c3-73c673e414be'; -const testDeviceNotifications = [ - { - deviceId, - notification: 'notification', - timestamp: new Date().toISOString(), +const TIMESTAMP = new Date().toISOString(); +const DH_NOTIFICATIONS_TEST_DEVICE = { + id: randomString.generate(), + name: `DH_COMMANDS_TEST_DEVICE`, + networkId: 1, + deviceTypeId: 1, + isBlocked: false, + data: {} +}; +const TEST_DEVICE_NOTIFICATIONS = { + HTTP: { + deviceId: DH_NOTIFICATIONS_TEST_DEVICE.id, + notification: `notification-${randomString.generate()}`, + timestamp: TIMESTAMP, parameters: { jsonString: 'jsonString' } }, - { - deviceId, - notification: 'notification', - timestamp: new Date().toISOString(), + WS: { + deviceId: DH_NOTIFICATIONS_TEST_DEVICE.id, + notification: `notification-${randomString.generate()}`, + timestamp: TIMESTAMP, parameters: { jsonString: 'jsonString' } } -]; +}; describe('NotificationAPI', () => { before(done => { - // Configaratuion DeviceHive Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) - .then(() => done()); + .then(() => httpDeviceHive.device.add(new Device(DH_NOTIFICATIONS_TEST_DEVICE))) + .then(() => done()) + .catch(done); }); + it(`should insert new notification with name ${TEST_DEVICE_NOTIFICATIONS.HTTP.notification} via HTTP`, done => { + const notificationModel = new Notification(TEST_DEVICE_NOTIFICATIONS.HTTP); - it('NotificationAPI.insert()', done => { - - const notification = new DeviceHive.models.Notification(testDeviceNotifications[0]); - const notification2 = new DeviceHive.models.Notification(testDeviceNotifications[1]); + httpDeviceHive.notification.insert(DH_NOTIFICATIONS_TEST_DEVICE.id, notificationModel) + .then((notification) => { + TEST_DEVICE_NOTIFICATIONS.HTTP.id = notification.id; - Promise.all([httpDeviceHive.notification.insert(deviceId, notification), wsDeviceHive.notification.insert(deviceId, notification2)]) - .then(() => done()) + done(); + }) .catch(done); }); + it(`should insert new notification with name ${TEST_DEVICE_NOTIFICATIONS.WS.notification} via WS`, done => { + const notificationModel = new Notification(TEST_DEVICE_NOTIFICATIONS.WS); - it('NotificationAPI.list()', done => { - - // Configurating Device List query - const notificationListQuery = new DeviceHive.models.query.NotificationListQuery({ - deviceId, - notification: 'notification', - status: 'status', - sortField: 'id', - sortOrder: 'id', - take: 2, - skip: 0 - }); + wsDeviceHive.notification.insert(DH_NOTIFICATIONS_TEST_DEVICE.id, notificationModel) + .then((notification) => { + TEST_DEVICE_NOTIFICATIONS.WS.id = notification.id; - Promise.all([httpDeviceHive.notification.list(notificationListQuery), wsDeviceHive.notification.list(notificationListQuery)]) - .then(dataAll => { - for (const data of dataAll) { - for (const deviceNotificationKey in data) { - testDeviceNotifications[deviceNotificationKey].id = data[deviceNotificationKey].id; - testDeviceNotifications[deviceNotificationKey].timestamp = data[deviceNotificationKey].timestamp; - assert.containsAllKeys(data[deviceNotificationKey], Object.keys(testDeviceNotifications[0])); - } - } + done(); }) - .then(done) .catch(done); }); + it(`should list all notifications for device with id ${DH_NOTIFICATIONS_TEST_DEVICE.id} via HTTP`, done => { + const notificationListQuery = new NotificationListQuery({ + deviceId: DH_NOTIFICATIONS_TEST_DEVICE.id, + notification: TEST_DEVICE_NOTIFICATIONS.HTTP.notification + }); + + setTimeout(() => { + httpDeviceHive.notification.list(notificationListQuery) + .then(notifications => { + assert.equal(notifications[0].notification, TEST_DEVICE_NOTIFICATIONS.HTTP.notification); + }) + .then(() => done()) + .catch(done); + }, 200); + }); + + it(`should list all notifications for device with id ${DH_NOTIFICATIONS_TEST_DEVICE.id} via WS`, done => { + const notificationListQuery = new NotificationListQuery({ + deviceId: DH_NOTIFICATIONS_TEST_DEVICE.id, + notification: TEST_DEVICE_NOTIFICATIONS.WS.notification + }); - it('NotificationAPI.get()', done => { + setTimeout(() => { + wsDeviceHive.notification.list(notificationListQuery) + .then(notifications => { + assert.equal(notifications[0].notification, TEST_DEVICE_NOTIFICATIONS.WS.notification); + }) + .then(() => done()) + .catch(done); + }, 200); + }); - Promise.all([httpDeviceHive.notification.get(deviceId, testDeviceNotifications[0].id), wsDeviceHive.notification.get(deviceId, testDeviceNotifications[0].id)]) - .then(dataAll => { - const expected = testDeviceNotifications[0]; - for (const data of dataAll) { - assert.isObject(data); - assert.deepInclude(data, expected); - } + it(`should get notification with id ${TEST_DEVICE_NOTIFICATIONS.HTTP.id} for device with id ${DH_NOTIFICATIONS_TEST_DEVICE.id} via HTTP`, done => { + httpDeviceHive.notification.get(DH_NOTIFICATIONS_TEST_DEVICE.id, TEST_DEVICE_NOTIFICATIONS.HTTP.id) + .then(notification => { + assert.equal(notification.id, TEST_DEVICE_NOTIFICATIONS.HTTP.id); }) - .then(done) + .then(() => done()) .catch(done); }); + it(`should get notification with id ${TEST_DEVICE_NOTIFICATIONS.WS.id} for device with id ${DH_NOTIFICATIONS_TEST_DEVICE.id} via WS`, done => { + wsDeviceHive.notification.get(DH_NOTIFICATIONS_TEST_DEVICE.id, TEST_DEVICE_NOTIFICATIONS.WS.id) + .then(command => { + assert.equal(command.id, TEST_DEVICE_NOTIFICATIONS.WS.id); + }) + .then(() => done()) + .catch(done); + }); - it('NotificationAPI.poll()', done => { - - // Configurating Notification List query - const notificationPollQuery = new DeviceHive.models.query.NotificationPollQuery({ - deviceId, - returnUpdatedNotifications: true, - limit: 1, + it(`should poll new notification for device with id ${DH_NOTIFICATIONS_TEST_DEVICE.id} via HTTP`, done => { + const notificationPollQuery = new NotificationPollQuery({ + deviceId: DH_NOTIFICATIONS_TEST_DEVICE.id, waitTimeout: 1 }); httpDeviceHive.notification.poll(notificationPollQuery) - .then(() => done()) + .then((notifications) => { + assert.equal(notifications.length, 1); + assert.equal(notifications[0].notification, TEST_DEVICE_NOTIFICATIONS.HTTP.notification); + + TEST_DEVICE_NOTIFICATIONS.HTTP.id = notifications[0].id; + done(); + }) .catch(done); - // emit notification setTimeout(() => { - const notification = new DeviceHive.models.Notification(testDeviceNotifications[0]); - httpDeviceHive.notification.insert(deviceId, notification); - }, 50); + TEST_DEVICE_NOTIFICATIONS.HTTP.notification = `notification-${randomString.generate()}`; + httpDeviceHive.notification.insert(DH_NOTIFICATIONS_TEST_DEVICE.id, new Notification(TEST_DEVICE_NOTIFICATIONS.HTTP)); + }, 100); }); - - it('NotificationAPI.pollMany()', done => { - - const notificationPollManyQuery = new DeviceHive.models.query.NotificationPollManyQuery({ - deviceIds: deviceId + it(`should poll new notification for network with id ${DH_NOTIFICATIONS_TEST_DEVICE.networkId} via HTTP`, done => { + const notificationPollManyQuery = new NotificationPollManyQuery({ + networkIds: [ DH_NOTIFICATIONS_TEST_DEVICE.networkId ], + waitTimeout: 1 }); httpDeviceHive.notification.pollMany(notificationPollManyQuery) - .then(() => done()) + .then((notifications) => { + assert.equal(notifications.length, 1); + assert.equal(notifications[0].notification, TEST_DEVICE_NOTIFICATIONS.HTTP.notification); + + done(); + }) .catch(done); - // emit notification setTimeout(() => { - const notification = new DeviceHive.models.Notification(testDeviceNotifications[0]); - httpDeviceHive.notification.insert(deviceId, notification); - }, 50); + TEST_DEVICE_NOTIFICATIONS.HTTP.notification = `notification-${randomString.generate()}`; + httpDeviceHive.notification.insert(DH_NOTIFICATIONS_TEST_DEVICE.id, new Notification(TEST_DEVICE_NOTIFICATIONS.HTTP)); + }, 100); + }); + + it(`should subscribe for notification insertion notifications on device with id ${DH_NOTIFICATIONS_TEST_DEVICE.id} via HTTP`, done => { + const notificationPollQuery = new NotificationPollQuery({ deviceId: DH_NOTIFICATIONS_TEST_DEVICE.id }); + let subscriptionId; + + httpDeviceHive.notification.subscribe(notificationPollQuery) + .then((response) => { + subscriptionId = response.subscriptionId; + + httpDeviceHive.on(`message`, (command) => { + assert.equal(command.notification, TEST_DEVICE_NOTIFICATIONS.HTTP.notification); + httpDeviceHive.notification.unsubscribe(subscriptionId) + .then(() => done()) + .catch(done); + }); + + setTimeout(() => { + TEST_DEVICE_NOTIFICATIONS.HTTP.notification = `command-${randomString.generate()}`; + httpDeviceHive.notification.insert(DH_NOTIFICATIONS_TEST_DEVICE.id, new Notification(TEST_DEVICE_NOTIFICATIONS.HTTP)); + }, 100); + }) + .catch(done); + }); + + it(`should subscribe for notification insertion notifications on device with id ${DH_NOTIFICATIONS_TEST_DEVICE.id} via WS`, done => { + const notificationPollQuery = new NotificationPollQuery({ deviceId: DH_NOTIFICATIONS_TEST_DEVICE.id }); + let subscriptionId; + + wsDeviceHive.notification.subscribe(notificationPollQuery) + .then((response) => { + subscriptionId = response.subscriptionId; + + setTimeout(() => { + wsDeviceHive.on(`message`, (command) => { + assert.equal(command.notification, TEST_DEVICE_NOTIFICATIONS.WS.notification); + wsDeviceHive.notification.unsubscribe(subscriptionId) + .then(() => done()) + .catch(done); + }); + }, 200); + + setTimeout(() => { + TEST_DEVICE_NOTIFICATIONS.WS.notification = `command-${randomString.generate()}`; + wsDeviceHive.notification.insert(DH_NOTIFICATIONS_TEST_DEVICE.id, new Notification(TEST_DEVICE_NOTIFICATIONS.WS)); + }, 300); + }) + .catch(done); + }); + + after(done => { + httpDeviceHive.device.delete(DH_NOTIFICATIONS_TEST_DEVICE.id) + .then(() => { + httpDeviceHive.disconnect(); + wsDeviceHive.disconnect(); + + done(); + }); }); }); \ No newline at end of file diff --git a/test/integration/controllers/DeviceTypeAPI.spec.js b/test/integration/controllers/DeviceTypeAPI.spec.js index cb6412d..e41b088 100644 --- a/test/integration/controllers/DeviceTypeAPI.spec.js +++ b/test/integration/controllers/DeviceTypeAPI.spec.js @@ -1,130 +1,167 @@ +const randomString = require(`randomstring`); const chai = require(`chai`); const assert = chai.assert; const config = require('../config'); - -const EventEmitter = require('events'); -const events = new EventEmitter(); - const DeviceHive = require('../../../index'); +const DeviceType = DeviceHive.models.DeviceType; +const DeviceTypeListQuery = DeviceHive.models.query.DeviceTypeListQuery; +const DeviceTypeCountQuery = DeviceHive.models.query.DeviceTypeCountQuery; const httpDeviceHive = new DeviceHive(config.server.http); const wsDeviceHive = new DeviceHive(config.server.ws); -const testDeviceTypes = [ - { - name: 'name', - description: 'description' - }, { - name: 'name2', - description: 'description2' +const TEST_DEVICE_TYPE_NAME_PREFIX = `DH-JS-LIB-DEVICE-TYPE-NAME-`; +const TEST_DEVICE_TYPE_DESCRIPTION_PREFIX = `DH-JS-LIB-DEVICE-TYPE-NAME-`; +const TEST_DEVICE_TYPES = { + HTTP: { + name: `${TEST_DEVICE_TYPE_NAME_PREFIX}-${randomString.generate()}`, + description: `${TEST_DEVICE_TYPE_DESCRIPTION_PREFIX}-${randomString.generate()}` + }, + WS: { + name: `${TEST_DEVICE_TYPE_NAME_PREFIX}-${randomString.generate()}`, + description: `${TEST_DEVICE_TYPE_DESCRIPTION_PREFIX}-${randomString.generate()}` } -]; +}; describe('DeviceTypeAPI', () => { before(done => { - // Configaratuion DeviceHive - Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) .then(() => done()); }); + it(`should insert new device type with next configuration: ${JSON.stringify(TEST_DEVICE_TYPES.HTTP)} via HTTP`, done => { + const deviceTypeModel = new DeviceType(TEST_DEVICE_TYPES.HTTP); - it('DeviceTypeAPI.insert()', done => { - - // Configurating DeviceType model - const DeviceType = DeviceHive.models.DeviceType; + httpDeviceHive.deviceType.insert(deviceTypeModel) + .then(({ id }) => { + TEST_DEVICE_TYPES.HTTP.id = id; + done(); + }) + .catch(done); + }); - const deviceType = new DeviceType(testDeviceTypes[0]); - const deviceType2 = new DeviceType(testDeviceTypes[1]); + it(`should insert new device type with next configuration: ${JSON.stringify(TEST_DEVICE_TYPES.WS)} via WS`, done => { + const deviceTypeModel = new DeviceType(TEST_DEVICE_TYPES.WS); - Promise.all([httpDeviceHive.deviceType.insert(deviceType), wsDeviceHive.deviceType.insert(deviceType2)]) - .then(() => done()) + wsDeviceHive.deviceType.insert(deviceTypeModel) + .then(({ id }) => { + TEST_DEVICE_TYPES.WS.id = id; + done(); + }) .catch(done); }); + it(`should list all device types with the next name pattern: ${TEST_DEVICE_TYPE_NAME_PREFIX}% via HTTP`, done => { + const deviceTypeListQuery = new DeviceTypeListQuery({ namePattern: `${TEST_DEVICE_TYPE_NAME_PREFIX}%` }); - it('DeviceTypeAPI.list()', done => { + httpDeviceHive.deviceType.list(deviceTypeListQuery) + .then(deviceTypes => { + assert(deviceTypes.length, Object.keys(TEST_DEVICE_TYPES).length); + }) + .then(() => done()) + .catch(done); + }); + it(`should list all device types with the next name pattern: ${TEST_DEVICE_TYPE_NAME_PREFIX}% via WS`, done => { + const deviceTypeListQuery = new DeviceTypeListQuery({ namePattern: `${TEST_DEVICE_TYPE_NAME_PREFIX}%` }); - // Configurating Device List query - const deviceTypeListQuery = new DeviceHive.models.query.DeviceTypeListQuery({ - namePattern: 'name%', - sortField: 'name', - sortOrder: 'asc', - take: 2, - skip: 0 - }); + wsDeviceHive.deviceType.list(deviceTypeListQuery) + .then(deviceTypes => { + assert(deviceTypes.length, Object.keys(TEST_DEVICE_TYPES).length); + }) + .then(() => done()) + .catch(done); + }); + it(`should get device type with name: ${TEST_DEVICE_TYPES.HTTP.name} via HTTP`, done => { + httpDeviceHive.deviceType.get(TEST_DEVICE_TYPES.HTTP.id) + .then(deviceType => { + assert.equal(deviceType.id, TEST_DEVICE_TYPES.HTTP.id); + assert.equal(deviceType.name, TEST_DEVICE_TYPES.HTTP.name); + }) + .then(() => done()) + .catch(done); + }); - Promise.all([httpDeviceHive.deviceType.list(deviceTypeListQuery), wsDeviceHive.deviceType.list(deviceTypeListQuery)]) - .then(dataAll => { - for (const data of dataAll) { - for (const deviceTypeKey in data) { - testDeviceTypes[deviceTypeKey].id = data[deviceTypeKey].id; - testDeviceTypes[deviceTypeKey].name = data[deviceTypeKey].name; - testDeviceTypes[deviceTypeKey].description = data[deviceTypeKey].description; - assert.containsAllKeys(data[deviceTypeKey], Object.keys(testDeviceTypes[0])); - } - } + it(`should get device type with name: ${TEST_DEVICE_TYPES.WS.name} via WS`, done => { + wsDeviceHive.deviceType.get(TEST_DEVICE_TYPES.WS.id) + .then(deviceType => { + assert.equal(deviceType.id, TEST_DEVICE_TYPES.WS.id); + assert.equal(deviceType.name, TEST_DEVICE_TYPES.WS.name); }) - .then(done) + .then(() => done()) .catch(done); }); + it(`should update device type with name: ${TEST_DEVICE_TYPES.HTTP.name} via HTTP`, done => { + TEST_DEVICE_TYPES.HTTP.description = `${TEST_DEVICE_TYPE_DESCRIPTION_PREFIX}-${randomString.generate()}`; - it('DeviceTypeAPI.get()', done => { + const deviceTypeModel = new DeviceType(TEST_DEVICE_TYPES.HTTP); - Promise.all([httpDeviceHive.deviceType.get(testDeviceTypes[0].id), wsDeviceHive.deviceType.get(testDeviceTypes[0].id)]) - .then(dataAll => { - const expected = testDeviceTypes[0]; - for (const data of dataAll) { - assert.isObject(data); - assert.deepInclude(data, expected); - } + httpDeviceHive.deviceType.update(deviceTypeModel) + .then(() => httpDeviceHive.deviceType.get(TEST_DEVICE_TYPES.HTTP.id)) + .then((deviceType) => { + assert.equal(deviceType.description, TEST_DEVICE_TYPES.HTTP.description); }) - .then(done) + .then(() => done()) .catch(done); + }); + it(`should update device type with name: ${TEST_DEVICE_TYPES.WS.name} via WS`, done => { + TEST_DEVICE_TYPES.WS.description = `${TEST_DEVICE_TYPE_DESCRIPTION_PREFIX}-${randomString.generate()}`; - it('DeviceTypeAPI.update()', done => { + const deviceTypeModel = new DeviceType(TEST_DEVICE_TYPES.WS); - // Configurating DeviceType model - const DeviceType = DeviceHive.models.DeviceType; + wsDeviceHive.deviceType.update(deviceTypeModel) + .then(() => wsDeviceHive.deviceType.get(TEST_DEVICE_TYPES.WS.id)) + .then((deviceType) => { + assert.equal(deviceType.description, TEST_DEVICE_TYPES.WS.description); + }) + .then(() => done()) + .catch(done); + }); - const deviceType = new DeviceType(testDeviceTypes[0]); - const deviceType2 = new DeviceType(testDeviceTypes[1]); + it(`should count device types with the next name pattern: ${TEST_DEVICE_TYPE_NAME_PREFIX}% via HTTP`, done => { + const deviceTypeCountQuery = new DeviceTypeCountQuery({ namePattern: `${TEST_DEVICE_TYPE_NAME_PREFIX}%` }); - Promise.all([httpDeviceHive.deviceType.update(deviceType), wsDeviceHive.deviceType.update(deviceType2)]) + httpDeviceHive.deviceType.count(deviceTypeCountQuery) + .then(({ count }) => { + assert.equal(count, Object.keys(TEST_DEVICE_TYPES).length); + }) .then(() => done()) .catch(done); - }); - it('DeviceTypeAPI.count()', done => { + it(`should count device types with the next name pattern: ${TEST_DEVICE_TYPE_NAME_PREFIX}% via WS`, done => { + const deviceTypeCountQuery = new DeviceTypeCountQuery({ namePattern: `${TEST_DEVICE_TYPE_NAME_PREFIX}%` }); - // Configurating DeviceType List query - const deviceTypeListQuery = new DeviceHive.models.query.DeviceTypeCountQuery({ - name: 'name', - namePattern: 'namePattern' - }); - - Promise.all([httpDeviceHive.deviceType.count(deviceTypeListQuery), wsDeviceHive.deviceType.count(deviceTypeListQuery)]) - .then(dataAll => { - for (const data of dataAll) { - assert.property(data, 'count'); - } + wsDeviceHive.deviceType.count(deviceTypeCountQuery) + .then(({ count }) => { + assert.equal(count, Object.keys(TEST_DEVICE_TYPES).length); }) - .then(done) + .then(() => done()) .catch(done); }); - it('DeviceTypeAPI.delete()', done => { - - Promise.all([httpDeviceHive.deviceType.delete(testDeviceTypes[0].id), wsDeviceHive.deviceType.delete(testDeviceTypes[1].id)]) + it(`should delete device type with name: ${TEST_DEVICE_TYPES.HTTP.name} via HTTP`, done => { + httpDeviceHive.deviceType.delete(TEST_DEVICE_TYPES.HTTP.id) .then(() => done()) .catch(done); }); + + it(`should delete device type with name: ${TEST_DEVICE_TYPES.WS.name} via WS`, done => { + wsDeviceHive.deviceType.delete(TEST_DEVICE_TYPES.WS.id) + .then(() => done()) + .catch(done); + }); + + after(done => { + httpDeviceHive.disconnect(); + wsDeviceHive.disconnect(); + + done(); + }); }); \ No newline at end of file diff --git a/test/integration/controllers/NetworkAPI.spec.js b/test/integration/controllers/NetworkAPI.spec.js index 2ce51e1..54378c7 100644 --- a/test/integration/controllers/NetworkAPI.spec.js +++ b/test/integration/controllers/NetworkAPI.spec.js @@ -1,129 +1,167 @@ +const randomString = require(`randomstring`); const chai = require(`chai`); const assert = chai.assert; const config = require('../config'); - -const EventEmitter = require('events'); -const events = new EventEmitter(); - const DeviceHive = require('../../../index'); +const Network = DeviceHive.models.Network; +const NetworkListQuery = DeviceHive.models.query.NetworkListQuery; +const NetworkCountQuery = DeviceHive.models.query.NetworkCountQuery; const httpDeviceHive = new DeviceHive(config.server.http); const wsDeviceHive = new DeviceHive(config.server.ws); -const testNetworks = [ - { - name: 'name', - description: 'description' - }, { - name: 'name2', - description: 'description2' +const TEST_NETWORK_NAME_PREFIX = `DH-JS-LIB-NETWORK-NAME-`; +const TEST_NETWORK_DESCRIPTION_PREFIX = `DH-JS-LIB-NETWORK-NAME-`; +const TEST_NETWORKS = { + HTTP: { + name: `${TEST_NETWORK_NAME_PREFIX}-${randomString.generate()}`, + description: `${TEST_NETWORK_DESCRIPTION_PREFIX}-${randomString.generate()}` + }, + WS: { + name: `${TEST_NETWORK_NAME_PREFIX}-${randomString.generate()}`, + description: `${TEST_NETWORK_DESCRIPTION_PREFIX}-${randomString.generate()}` } -]; +}; describe('NetworkAPI', () => { before(done => { - // Configaratuion DeviceHive - Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) .then(() => done()); }); + it(`should insert new network with next configuration: ${JSON.stringify(TEST_NETWORKS.HTTP)} via HTTP`, done => { + const networkModel = new Network(TEST_NETWORKS.HTTP); + + httpDeviceHive.network.insert(networkModel) + .then(({ id }) => { + TEST_NETWORKS.HTTP.id = id; + done(); + }) + .catch(done); + }); - it('NetworkAPI.insert()', done => { + it(`should insert new network with next configuration: ${JSON.stringify(TEST_NETWORKS.WS)} via WS`, done => { + const networkModel = new Network(TEST_NETWORKS.WS); - // Configurating Network model - const Network = DeviceHive.models.Network; + wsDeviceHive.network.insert(networkModel) + .then(({ id }) => { + TEST_NETWORKS.WS.id = id; + done(); + }) + .catch(done); + }); - const network = new Network(testNetworks[0]); - const network2 = new Network(testNetworks[1]); + it(`should list all device types with the next name pattern: ${TEST_NETWORK_NAME_PREFIX}% via HTTP`, done => { + const networkListQuery = new NetworkListQuery({ namePattern: `${TEST_NETWORK_NAME_PREFIX}%` }); - Promise.all([httpDeviceHive.network.insert(network), wsDeviceHive.network.insert(network2)]) + httpDeviceHive.network.list(networkListQuery) + .then(networks => { + assert(networks.length, Object.keys(TEST_NETWORKS).length); + }) .then(() => done()) .catch(done); }); + it(`should list all device types with the next name pattern: ${TEST_NETWORK_NAME_PREFIX}% via WS`, done => { + const networkListQuery = new NetworkListQuery({ namePattern: `${TEST_NETWORK_NAME_PREFIX}%` }); - it('NetworkAPI.list()', done => { - - // Configurating Device List query - const networkListQuery = new DeviceHive.models.query.NetworkListQuery({ - namePattern: 'name%', - sortField: 'name', - sortOrder: 'asc', - take: 2, - skip: 0 - }); - - - Promise.all([httpDeviceHive.network.list(networkListQuery), wsDeviceHive.network.list(networkListQuery)]) - .then(dataAll => { - for (const data of dataAll) { - for (const networkKey in data) { - testNetworks[networkKey].id = data[networkKey].id; - testNetworks[networkKey].name = data[networkKey].name; - testNetworks[networkKey].description = data[networkKey].description; - assert.containsAllKeys(data[networkKey], Object.keys(testNetworks[0])); - } - } + wsDeviceHive.network.list(networkListQuery) + .then(networks => { + assert(networks.length, Object.keys(TEST_NETWORKS).length); }) - .then(done) + .then(() => done()) .catch(done); }); + it(`should get network with name: ${TEST_NETWORKS.HTTP.name} via HTTP`, done => { + httpDeviceHive.network.get(TEST_NETWORKS.HTTP.id) + .then(network => { + assert.equal(network.id, TEST_NETWORKS.HTTP.id); + assert.equal(network.name, TEST_NETWORKS.HTTP.name); + }) + .then(() => done()) + .catch(done); + }); - it('NetworkAPI.get()', done => { - - Promise.all([httpDeviceHive.network.get(testNetworks[0].id), wsDeviceHive.network.get(testNetworks[0].id)]) - .then(dataAll => { - const expected = testNetworks[0]; - for (const data of dataAll) { - assert.isObject(data); - assert.deepInclude(data, expected); - } + it(`should get network with name: ${TEST_NETWORKS.WS.name} via WS`, done => { + wsDeviceHive.network.get(TEST_NETWORKS.WS.id) + .then(network => { + assert.equal(network.id, TEST_NETWORKS.WS.id); + assert.equal(network.name, TEST_NETWORKS.WS.name); }) - .then(done) + .then(() => done()) .catch(done); }); + it(`should update network with name: ${TEST_NETWORKS.HTTP.name} via HTTP`, done => { + TEST_NETWORKS.HTTP.description = `${TEST_NETWORK_DESCRIPTION_PREFIX}-${randomString.generate()}`; - it('NetworkAPI.update()', done => { + const networkModel = new Network(TEST_NETWORKS.HTTP); - // Configurating Network model - const Network = DeviceHive.models.Network; + httpDeviceHive.network.update(networkModel) + .then(() => httpDeviceHive.network.get(TEST_NETWORKS.HTTP.id)) + .then((network) => { + assert.equal(network.description, TEST_NETWORKS.HTTP.description); + }) + .then(() => done()) + .catch(done); + + }); - const network = new Network(testNetworks[0]); - const network2 = new Network(testNetworks[1]); + it(`should update network with name: ${TEST_NETWORKS.WS.name} via WS`, done => { + TEST_NETWORKS.WS.description = `${TEST_NETWORK_DESCRIPTION_PREFIX}-${randomString.generate()}`; - Promise.all([httpDeviceHive.network.update(network), wsDeviceHive.network.update(network2)]) + const networkModel = new Network(TEST_NETWORKS.WS); + + wsDeviceHive.network.update(networkModel) + .then(() => wsDeviceHive.network.get(TEST_NETWORKS.WS.id)) + .then((network) => { + assert.equal(network.description, TEST_NETWORKS.WS.description); + }) .then(() => done()) .catch(done); - }); - it('NetworkAPI.count()', done => { + it(`should count device types with the next name pattern: ${TEST_NETWORK_NAME_PREFIX}% via HTTP`, done => { + const networkCountQuery = new NetworkCountQuery({ namePattern: `${TEST_NETWORK_NAME_PREFIX}%` }); - // Configurating Network List query - const networkListQuery = new DeviceHive.models.query.NetworkCountQuery({ - name: 'name', - namePattern: 'namePattern' - }); + httpDeviceHive.network.count(networkCountQuery) + .then(({ count }) => { + assert.equal(count, Object.keys(TEST_NETWORKS).length); + }) + .then(() => done()) + .catch(done); + }); - Promise.all([httpDeviceHive.network.count(networkListQuery), wsDeviceHive.network.count(networkListQuery)]) - .then(dataAll => { - for (const data of dataAll) { - assert.property(data, 'count'); - } + it(`should count device types with the next name pattern: ${TEST_NETWORK_NAME_PREFIX}% via WS`, done => { + const networkCountQuery = new NetworkCountQuery({ namePattern: `${TEST_NETWORK_NAME_PREFIX}%` }); + + wsDeviceHive.network.count(networkCountQuery) + .then(({ count }) => { + assert.equal(count, Object.keys(TEST_NETWORKS).length); }) - .then(done) + .then(() => done()) .catch(done); }); - it('NetworkAPI.delete()', done => { - - Promise.all([httpDeviceHive.network.delete(testNetworks[0].id), wsDeviceHive.network.delete(testNetworks[1].id)]) + it(`should delete network with name: ${TEST_NETWORKS.HTTP.name} via HTTP`, done => { + httpDeviceHive.network.delete(TEST_NETWORKS.HTTP.id) .then(() => done()) .catch(done); }); + + it(`should delete network with name: ${TEST_NETWORKS.WS.name} via WS`, done => { + wsDeviceHive.network.delete(TEST_NETWORKS.WS.id) + .then(() => done()) + .catch(done); + }); + + after(done => { + httpDeviceHive.disconnect(); + wsDeviceHive.disconnect(); + + done(); + }); }); \ No newline at end of file diff --git a/test/integration/controllers/PluginAPI.spec.js b/test/integration/controllers/PluginAPI.spec.js index e53b5a8..088654d 100644 --- a/test/integration/controllers/PluginAPI.spec.js +++ b/test/integration/controllers/PluginAPI.spec.js @@ -1,143 +1,110 @@ +const randomString = require(`randomstring`); const chai = require(`chai`); const assert = chai.assert; -const config = require('../config'); - -const EventEmitter = require('events'); -const events = new EventEmitter(); - -const DeviceHive = require('../../../index'); +const config = require(`../config`); +const DeviceHive = require(`../../../index`); +const Plugin = DeviceHive.models.Plugin; +const PluginRegisterQuery = DeviceHive.models.query.PluginRegisterQuery; const httpDeviceHive = new DeviceHive(config.server.http); const wsDeviceHive = new DeviceHive(config.server.ws); -const testPlugins = [ - { - name: `testName${new Date().getMilliseconds()}`, - description: 'description', +const TEST_PLUGIN = { + HTTP: { + name: `plugin-${randomString.generate()}`, + description: `description`, parameters: { - jsonString: 'string' + jsonString: `string` } } -]; +}; -describe('PluginAPI', () => { +describe(`PluginAPI`, () => { before(done => { Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) .then(() => done()); }); - - it('PluginAPI.register()', done => { - const plugin = new DeviceHive.models.Plugin(testPlugins[0]); - const pluginQuery = new DeviceHive.models.query.PluginRegisterQuery({ - returnCommands: 'true', - returnUpdatedCommands: 'false', - returnNotifications: 'false' + it(`should register plugin with name: ${TEST_PLUGIN.HTTP.name} via HTTP`, done => { + const plugin = new Plugin(TEST_PLUGIN.HTTP); + const pluginQuery = new PluginRegisterQuery({ + returnCommands: true, + returnUpdatedCommands: false, + returnNotifications: false }); - Promise.all([httpDeviceHive.plugin.register(plugin, pluginQuery)]) - .then(dataAll => { - for (const data of dataAll) { - testPlugins[0] = Object.assign({}, testPlugins[0], data); - } + httpDeviceHive.plugin.register(plugin, pluginQuery) + .then(({ accessToken, refreshToken, topicName }) => { + assert.exists(accessToken); + assert.exists(refreshToken); + assert.exists(topicName); + + TEST_PLUGIN.HTTP.accessToken = accessToken; + TEST_PLUGIN.HTTP.refreshToken = refreshToken; + TEST_PLUGIN.HTTP.topicName = topicName; }) .then(() => done()) .catch(done); }); - it('PluginAPI.list()', done => { + it(`should get plugin with name: ${TEST_PLUGIN.HTTP.name} via HTTP`, done => { const pluginListQuery = new DeviceHive.models.query.PluginListQuery({ - take: 1, - skip: 0 + name: TEST_PLUGIN.HTTP.name }); - Promise.all([httpDeviceHive.plugin.list(pluginListQuery)]) - .then(dataAll => { - for (const data of dataAll) { - assert.isArray(data); - } + httpDeviceHive.plugin.list(pluginListQuery) + .then(plugins => { + assert.equal(plugins[0].name, TEST_PLUGIN.HTTP.name); }) .then(() => done()) .catch(done); }); + it(`should update plugin with name: ${TEST_PLUGIN.HTTP.name} via HTTP`, done => { + TEST_PLUGIN.HTTP.name = `plugin-${randomString.generate()}`; - it('PluginAPI.update()', done => { - const updatedName = `${testPlugins[0].name}-updated`; const pluginUpdateQuery = new DeviceHive.models.query.PluginUpdateQuery({ - topicName: testPlugins[0].topicName, - name: updatedName + topicName: TEST_PLUGIN.HTTP.topicName, + name: TEST_PLUGIN.HTTP.name }); const pluginListQuery = new DeviceHive.models.query.PluginListQuery({ - name: updatedName, - take: 1, - skip: 0 + name: TEST_PLUGIN.HTTP.name }); - Promise.all([httpDeviceHive.plugin.update(pluginUpdateQuery)]) - .then(() => Promise.all([httpDeviceHive.plugin.list(pluginListQuery)])) - .then(dataAll => { - for (const data of dataAll) { - assert.strictEqual(data[0].name, updatedName); - } + httpDeviceHive.plugin.update(pluginUpdateQuery) + .then(() => httpDeviceHive.plugin.list(pluginListQuery)) + .then(plugins => { + assert.equal(plugins[0].name, TEST_PLUGIN.HTTP.name); }) .then(() => done()) .catch(done); }); - - it('PluginAPI.count()', done => { + it(`should count plugin with name: ${TEST_PLUGIN.HTTP.name} via HTTP`, done => { const pluginCountQuery = new DeviceHive.models.query.PluginCountQuery({ - status: '1' + name: TEST_PLUGIN.HTTP.name }); - Promise.all([httpDeviceHive.plugin.count(pluginCountQuery)]) - .then(dataAll => { - for (const data of dataAll) { - assert.property(data, 'count'); - } + httpDeviceHive.plugin.count(pluginCountQuery) + .then(({ count }) => { + assert.equal(count, 1); }) .then(() => done()) .catch(done); }); - it('TokenAPI.createPluginToken()', done => { - const token = new DeviceHive.models.PluginToken({ - actions: [0], - expiration: '2018-02-09T10:09:03.033Z', - type: 0, - topicName: testPlugins[0].topicName - }); - - Promise.all([httpDeviceHive.token.createPluginToken(token)]) - .then(dataAll => { - for (const data of dataAll) { - const expectedKeys = ['accessToken', 'refreshToken'] - assert.containsAllKeys(data, expectedKeys); - } - }) - .then(done) - .catch(done); - }); - - it('TokenAPI.authPlugin()', done => { - Promise.all([httpDeviceHive.token.authPlugin(testPlugins[0].accessToken)]) - .then(dataAll => { - for (const data of dataAll) { - const expectedKeys = ['tpc', 'a', 'e', 't']; - assert.containsAllKeys(data, expectedKeys) - } - }) - .then(done) + it(`should delete plugin with name: ${TEST_PLUGIN.HTTP.name}`, done => { + httpDeviceHive.plugin.delete(TEST_PLUGIN.HTTP.topicName) + .then(() => done()) .catch(done); }); - it('PluginAPI.delete()', done => { + after(done => { + httpDeviceHive.disconnect(); + wsDeviceHive.disconnect(); - Promise.all([httpDeviceHive.plugin.delete(testPlugins[0].topicName)]) - .then(() => done()) - .catch(done); + done(); }); }); \ No newline at end of file diff --git a/test/integration/controllers/ServerInfoAPI.spec.js b/test/integration/controllers/ServerInfoAPI.spec.js index 0bc96df..ecc5138 100644 --- a/test/integration/controllers/ServerInfoAPI.spec.js +++ b/test/integration/controllers/ServerInfoAPI.spec.js @@ -1,10 +1,6 @@ const chai = require(`chai`); const assert = chai.assert; const config = require('../config'); - -const EventEmitter = require('events'); -const events = new EventEmitter(); - const DeviceHive = require('../../../index'); const httpDeviceHive = new DeviceHive(config.server.http); @@ -14,48 +10,59 @@ const wsDeviceHive = new DeviceHive(config.server.ws); describe('ServerInfoAPI', () => { before(done => { - // Configaratuion DeviceHive Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) .then(() => done()); }); + it('should get server info via HTTP', done => { + httpDeviceHive.info.getServerInfo() + .then(serverInfo => { + assert.exists(serverInfo); + }) + .then(() => done()) + .catch(done); + }); - it('InfoAPI.getServerInfo()', done => { - - Promise.all([httpDeviceHive.info.getServerInfo(), wsDeviceHive.info.getServerInfo()]) - .then(dataAll => { - for (const data of dataAll) { - const expectedKeys = ['apiVersion', 'serverTimestamp'] - assert.isObject(data); - assert.containsAllKeys(data, expectedKeys); - } + it('should get server info via WS', done => { + wsDeviceHive.info.getServerInfo() + .then(serverInfo => { + assert.exists(serverInfo); }) - .then(done) + .then(() => done()) .catch(done); }); - it('InfoAPI.getCacheInfo()', done => { + it('should get cache info via HTTP', done => { + httpDeviceHive.info.getCacheInfo() + .then(cacheInfo => { + assert.exists(cacheInfo); + }) + .then(() => done()) + .catch(done); + }); - Promise.all([httpDeviceHive.info.getCacheInfo()]) - .then(dataAll => { - for (const data of dataAll) { - const expectedKeys = ['serverTimestamp', 'cacheStats'] - assert.isObject(data); - assert.containsAllKeys(data, expectedKeys); - } + it('should get cluster info via HTTP', done => { + httpDeviceHive.info.getClusterInfo() + .then(clusterInfo => { + assert.exists(clusterInfo); }) - .then(done) + .then(() => done()) .catch(done); }); - it('InfoAPI.getClusterInfo()', done => { - Promise.all([httpDeviceHive.info.getClusterInfo(), wsDeviceHive.info.getClusterInfo()]) - .then(dataAll => { - for (const data of dataAll) { - assert.isObject(data); - } + it('should get cluster info via WS', done => { + wsDeviceHive.info.getClusterInfo() + .then(clusterInfo => { + assert.exists(clusterInfo); }) - .then(done) + .then(() => done()) .catch(done); }); + + after(done => { + httpDeviceHive.disconnect(); + wsDeviceHive.disconnect(); + + done(); + }); }); \ No newline at end of file diff --git a/test/integration/controllers/TokenAPI.spec.js b/test/integration/controllers/TokenAPI.spec.js index 60f2fc3..afd799f 100644 --- a/test/integration/controllers/TokenAPI.spec.js +++ b/test/integration/controllers/TokenAPI.spec.js @@ -1,96 +1,169 @@ +const randomString = require(`randomstring`); const chai = require(`chai`); const assert = chai.assert; -const config = require('../config'); - -const EventEmitter = require('events'); -const events = new EventEmitter(); - -const DeviceHive = require('../../../index'); +const config = require(`../config`); +const DeviceHive = require(`../../../index`); +const UserToken = DeviceHive.models.UserToken; +const Plugin = DeviceHive.models.Plugin; +const PluginRegisterQuery = DeviceHive.models.query.PluginRegisterQuery; const httpDeviceHive = new DeviceHive(config.server.http); const wsDeviceHive = new DeviceHive(config.server.ws); -const testToken = { - login: config.server.http.login, - password: config.server.http.password +const TEST_TOKENS = { + HTTP: {}, + WS: {} +}; +const TEST_PLUGIN = { + HTTP: { + name: `plugin-${randomString.generate()}`, + description: `description`, + parameters: { + jsonString: `string` + } + } }; -describe('TokenAPI', () => { +describe(`TokenAPI`, () => { before(done => { - // Configaratuion DeviceHive + const plugin = new Plugin(TEST_PLUGIN.HTTP); + const pluginQuery = new PluginRegisterQuery({ + returnCommands: true, + returnUpdatedCommands: false, + returnNotifications: false + }); Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => httpDeviceHive.plugin.register(plugin, pluginQuery)) + .then(({ accessToken, refreshToken, topicName }) => { + TEST_PLUGIN.HTTP.accessToken = accessToken; + TEST_PLUGIN.HTTP.refreshToken = refreshToken; + TEST_PLUGIN.HTTP.topicName = topicName; + }) .then(() => done()); }); - it('TokenAPI.createUserToken()', done => { + it(`should create token for user via HTTP`, done => { + const token = new UserToken({ + userId: config.TEST_USER_ID, + actions: [`*`], + networkIds: [`*`], + deviceTypeIds: [`*`], + expiration: `2050-02-09T10:09:03.033Z` + }); + + httpDeviceHive.token.createUserToken(token) + .then(({ accessToken, refreshToken }) => { + assert.exists(accessToken); + assert.exists(refreshToken); + + TEST_TOKENS.HTTP.accessToken = accessToken; + TEST_TOKENS.HTTP.refreshToken = refreshToken; + }) + .then(() => done()) + .catch(done); + }); - // Configurating Token model - const token = new DeviceHive.models.UserToken({ - userId: 1, - actions: ['string'], - networkIds: ['string'], - deviceTypeIds: ['string'], - expiration: '2030-02-09T10:09:03.033Z' + it(`should create token for user via WS`, done => { + const token = new UserToken({ + userId: config.TEST_USER_ID, + actions: [`*`], + networkIds: [`*`], + deviceTypeIds: [`*`], + expiration: `2050-02-09T10:09:03.033Z` }); - Promise.all([httpDeviceHive.token.createUserToken(token), wsDeviceHive.token.createUserToken(token)]) - .then(dataAll => { - for (const data of dataAll) { - const expectedkeys = ['accessToken', 'refreshToken']; - assert.isObject(data); - assert.containsAllKeys(data, expectedkeys); - testToken.accessToken = data.accessToken; - testToken.refreshToken = data.refreshToken; - } + wsDeviceHive.token.createUserToken(token) + .then(({ accessToken, refreshToken }) => { + assert.exists(accessToken); + assert.exists(refreshToken); + + TEST_TOKENS.WS.accessToken = accessToken; + TEST_TOKENS.WS.refreshToken = refreshToken; }) - .then(done) + .then(() => done()) .catch(done); }); - it('TokenAPI.refresh()', done => { - - // Configurating Token model - - Promise.all([httpDeviceHive.token.refresh(testToken.refreshToken)]) - .then(dataAll => { - for (const data of dataAll) { - const expectedkeys = ['accessToken']; - assert.isObject(data); - assert.containsAllKeys(data, expectedkeys); - testToken.accessToken = data.accessToken; - testToken.refreshToken = data.refreshToken; - } + it(`should refresh user access token via HTTP`, done => { + httpDeviceHive.token.refresh(TEST_TOKENS.HTTP.refreshToken) + .then(({ accessToken }) => { + assert.exists(accessToken); + + TEST_TOKENS.WS.accessToken = accessToken; }) - .then(done) + .then(() => done()) .catch(done); + }); - // sent data - events.once('request', data => { - assert.equal(data.method, 'POST', 'Not correct method'); - assert.equal(data.url.pathname, `/token/refresh`, 'Not correct URL'); - assert.deepEqual(data.body, expectedBody, 'Not correct body'); + it(`should refresh user access token via WS`, done => { + wsDeviceHive.token.refresh(TEST_TOKENS.WS.refreshToken) + .then(({ accessToken }) => { + assert.exists(accessToken); - done(); - }); + TEST_TOKENS.WS.accessToken = accessToken; + }) + .then(() => done()) + .catch(done); + }); + + it(`should log in user with given credentials: login ${config.TEST_USER_LOGIN}, password ${config.TEST_USER_PASSWORD} via HTTP`, done => { + httpDeviceHive.token.login(config.TEST_USER_LOGIN, config.TEST_USER_PASSWORD) + .then(({ accessToken, refreshToken }) => { + assert.exists(accessToken); + assert.exists(refreshToken); + }) + .then(() => done()) + .catch(done) }); + it(`should log in user with given credentials: login ${config.TEST_USER_LOGIN}, password ${config.TEST_USER_PASSWORD} via WS`, done => { + wsDeviceHive.token.login(config.TEST_USER_LOGIN, config.TEST_USER_PASSWORD) + .then(({ accessToken, refreshToken }) => { + assert.exists(accessToken); + assert.exists(refreshToken); + }) + .then(() => done()) + .catch(done) + }); - it('TokenAPI.login()', done => { + it(`should create plugin token for plugin with name: ${TEST_PLUGIN.HTTP.name} via HTTP`, done => { + const token = new DeviceHive.models.PluginToken({ + actions: [], + expiration: `2030-02-09T10:09:03.033Z`, + topicName: TEST_PLUGIN.HTTP.topicName + }); - Promise.all([httpDeviceHive.token.login(testToken.login, testToken.password), wsDeviceHive.token.login(testToken.login, testToken.password)]) - .then(dataAll => { - for (const data of dataAll) { - const expectedkeys = ['accessToken', 'refreshToken']; - assert.isObject(data); - assert.containsAllKeys(data, expectedkeys); - testToken.accessToken = data.accessToken; - testToken.refreshToken = data.refreshToken; - } + httpDeviceHive.token.createPluginToken(token) + .then(({ accessToken, refreshToken }) => { + assert.exists(accessToken); + assert.exists(refreshToken); + }) + .then(() => done()) + .catch(done); + }); + + it(`should authenticate plugin with name: ${TEST_PLUGIN.HTTP.name} via HTTP`, done => { + httpDeviceHive.token.authPlugin(TEST_PLUGIN.HTTP.accessToken) + .then(({ tpc, a, e, t }) => { + assert.exists(tpc); + assert.exists(a); + assert.exists(e); + assert.exists(t); }) .then(done) - .catch(done) + .catch(done); + }); + + after(done => { + httpDeviceHive.plugin.delete(TEST_PLUGIN.HTTP.topicName) + .then(() => { + httpDeviceHive.disconnect(); + wsDeviceHive.disconnect(); + + done(); + }); }); }); \ No newline at end of file diff --git a/test/integration/controllers/UserAPI.spec.js b/test/integration/controllers/UserAPI.spec.js index 5d81fc7..d5ca2ee 100644 --- a/test/integration/controllers/UserAPI.spec.js +++ b/test/integration/controllers/UserAPI.spec.js @@ -1,179 +1,204 @@ +const randomString = require(`randomstring`); const chai = require(`chai`); const assert = chai.assert; -const config = require('../config'); - -const EventEmitter = require('events'); -const events = new EventEmitter(); - -const DeviceHive = require('../../../index'); +const config = require(`../config`); +const DeviceHive = require(`../../../index`); +const User = DeviceHive.models.User; +const UserListQuery = DeviceHive.models.query.UserListQuery; +const UserCountQuery = DeviceHive.models.query.UserCountQuery; const httpDeviceHive = new DeviceHive(config.server.http); const wsDeviceHive = new DeviceHive(config.server.ws); -const testUsers = [ - { - login: 'testLogin', +const TEST_USER_LOGIN_PREFIX = `DH-JS-LIB-USER-LOGIN-`; +const TEST_USERS = { + HTTP: { + login: `${TEST_USER_LOGIN_PREFIX}-${randomString.generate()}`, role: 1, status: 1, - password: 'password', - lastLogin: '2018-02-09T10:09:03.033Z', + password: `password`, data: { - jsonString: 'jsonString' - }, - introReviewed: false, - allDeviceTypesAvailable: false - }, { - login: 'testLogin2', + jsonString: `jsonString` + } + }, + WS: { + login: `${TEST_USER_LOGIN_PREFIX}-${randomString.generate()}`, role: 1, status: 1, - password: 'password', - lastLogin: '2018-02-09T10:09:03.033Z', + password: `password`, data: { - jsonString: 'jsonString' - }, - introReviewed: false, - allDeviceTypesAvailable: false + jsonString: `jsonString` + } } -]; +}; -describe('UserAPI', () => { +describe(`UserAPI`, () => { before(done => { - // Configaratuion DeviceHive - Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) .then(() => done()); }); - it('UserAPI.insert()', done => { - - // Configurating User model - const User = DeviceHive.models.User; + it(`should add new user with login ${TEST_USERS.HTTP.login} via HTTP`, done => { + const userModel = new User(TEST_USERS.HTTP); - const user = new User(testUsers[0]); - const user2 = new User(testUsers[1]); + httpDeviceHive.user.insert(userModel) + .then(({ id }) => { + assert.exists(id); - Promise.all([httpDeviceHive.user.insert(user), wsDeviceHive.user.insert(user2)]) + TEST_USERS.HTTP.id = id; + }) .then(() => done()) .catch(done); }); + it(`should add new user with login ${TEST_USERS.WS.login} via WS`, done => { + const userModel = new User(TEST_USERS.WS); - it('UserAPI.list()', done => { - - // Configurating User List query - const userListQuery = new DeviceHive.models.query.UserListQuery({ - loginPattern: 'testLogin%', - role: 1, - status: 1, - sortField: 'login', - sortOrder: 'asc', - take: 2, - skip: 0, - }); + wsDeviceHive.user.insert(userModel) + .then(({ id }) => { + assert.exists(id); - Promise.all([httpDeviceHive.user.list(userListQuery), wsDeviceHive.user.list(userListQuery)]) - .then(dataAll => { - for (const data of dataAll) { - for (const userKey in data) { - testUsers[userKey].id = data[userKey].id; - testUsers[userKey].lastLogin = data[userKey].lastLogin; - - const expectedKeys = Object.keys(testUsers[0]); - expectedKeys.splice(expectedKeys.indexOf('password'), 1); - assert.containsAllKeys(data[userKey], expectedKeys); - } - } + TEST_USERS.WS.id = id; }) - .then(done) + .then(() => done()) .catch(done); }); - it('UserAPI.get()', done => { + it(`should list users with the next login pattern: ${TEST_USER_LOGIN_PREFIX}% via HTTP`, done => { + const userListQuery = new UserListQuery({ loginPattern: `${TEST_USER_LOGIN_PREFIX}%` }); - Promise.all([httpDeviceHive.user.get(testUsers[0].id), wsDeviceHive.user.get(testUsers[0].id)]) - .then(dataAll => { - const expected = Object.assign({}, testUsers[0]); - delete expected.password; - for (const data of dataAll) { - assert.isObject(data); - assert.deepInclude(data, expected); - } + httpDeviceHive.user.list(userListQuery) + .then(users => { + assert.equal(users.length, Object.keys(TEST_USERS).length); }) - .then(done) + .then(() => done()) .catch(done); }); - it('UserAPI.getCurrent()', done => { + it(`should list users with the next login pattern: ${TEST_USER_LOGIN_PREFIX}% via HTTP`, done => { + const userListQuery = new UserListQuery({ loginPattern: `${TEST_USER_LOGIN_PREFIX}%` }); - Promise.all([httpDeviceHive.user.getCurrent(), wsDeviceHive.user.getCurrent()]) - .then(dataAll => { - const expected = Object.assign({}, testUsers[0]); - delete expected.password; - for (const data of dataAll) { - const expectedKeys = Object.keys(testUsers[0]); - expectedKeys.splice(expectedKeys.indexOf('password'), 1); + wsDeviceHive.user.list(userListQuery) + .then(users => { + assert.equal(users.length, Object.keys(TEST_USERS).length); + }) + .then(() => done()) + .catch(done); + }); - assert.isObject(data); - assert.containsAllKeys(data, expectedKeys); - } + it(`should get user with name: ${TEST_USERS.HTTP.name} via HTTP`, done => { + httpDeviceHive.user.get(TEST_USERS.HTTP.id) + .then(user => { + assert.equal(user.name, TEST_USERS.HTTP.name); }) - .then(done) + .then(() => done()) + .catch(done); + }); + + it(`should get user with name: ${TEST_USERS.WS.name} via WS`, done => { + wsDeviceHive.user.get(TEST_USERS.WS.id) + .then(user => { + assert.equal(user.name, TEST_USERS.WS.name); + }) + .then(() => done()) .catch(done); }); + it(`should get current user: login ${config.TEST_USER_LOGIN}, password ${config.TEST_USER_PASSWORD} via HTTP`, done => { + httpDeviceHive.user.getCurrent() + .then(user => { + assert.equal(user.login, config.TEST_USER_LOGIN); + }) + .then(() => done()) + .catch(done); + }); - it('UserAPI.update()', done => { + it(`should get current user: login ${config.TEST_USER_LOGIN}, password ${config.TEST_USER_PASSWORD} via WS`, done => { + wsDeviceHive.user.getCurrent() + .then(user => { + assert.equal(user.login, config.TEST_USER_LOGIN); + }) + .then(() => done()) + .catch(done); + }); - // Configurating User model - const User = DeviceHive.models.User; + it(`should update user with login: ${TEST_USERS.HTTP.login} via HTTP`, done => { + TEST_USERS.HTTP.data = { update: true }; - const user = new User(testUsers[0]); - const user2 = new User(testUsers[1]); + const userModel = new User(TEST_USERS.HTTP); - Promise.all([httpDeviceHive.user.update(user), wsDeviceHive.user.update(user2)]) + httpDeviceHive.user.update(userModel) + .then(() => httpDeviceHive.user.get(TEST_USERS.HTTP.id)) + .then((user) => { + assert.deepEqual(user.data, TEST_USERS.HTTP.data); + }) .then(() => done()) .catch(done); - }); + it(`should update user with login: ${TEST_USERS.WS.login} via WS`, done => { + TEST_USERS.WS.data = { update: true }; - it('UserAPI.updateCurrent()', done => { + const userModel = new User(TEST_USERS.WS); + + wsDeviceHive.user.update(userModel) + .then(() => wsDeviceHive.user.get(TEST_USERS.WS.id)) + .then((user) => { + assert.deepEqual(user.data, TEST_USERS.WS.data); + }) + .then(() => done()) + .catch(done); + }); - // Configurating User model - const user = new DeviceHive.models.User({ - status: 0 - }); + it(`should update current user with login ${config.TEST_USER_LOGIN} via HTTP`, done => { + const userModel = new User({ status: 0 }); - Promise.all([httpDeviceHive.user.updateCurrent(user), wsDeviceHive.user.updateCurrent(user)]) + httpDeviceHive.user.updateCurrent(userModel) + .then(() => httpDeviceHive.user.getCurrent()) + .then(user => { + assert.equal(user.status, userModel.status); + }) .then(() => done()) .catch(done); }); + it(`should update current user with login ${config.TEST_USER_LOGIN} via WS`, done => { + const userModel = new User({ status: 1 }); - it('UserAPI.count()', done => { + wsDeviceHive.user.updateCurrent(userModel) + .then(() => wsDeviceHive.user.getCurrent()) + .then(user => { + assert.equal(user.status, userModel.status); + }) + .then(() => done()) + .catch(done); + }); - // Configurating User List query - const userListQuery = new DeviceHive.models.query.UserCountQuery({ - login: 'login', - loginPattern: 'loginPattern', - role: '1', - status: '1' - }); + it(`should count users with the next login pattern ${TEST_USER_LOGIN_PREFIX}% via HTTP`, done => { + const userListQuery = new UserCountQuery({ loginPattern: `${TEST_USER_LOGIN_PREFIX}%` }); - Promise.all([httpDeviceHive.user.count(userListQuery), wsDeviceHive.user.count(userListQuery)]) - .then(dataAll => { - for (const data of dataAll) { - assert.property(data, 'count'); - } + httpDeviceHive.user.count(userListQuery) + .then(({ count }) => { + assert.equal(count, Object.keys(TEST_USERS).length); }) - .then(done) + .then(() => done()) .catch(done); }); + it(`should count users with the next login pattern ${TEST_USER_LOGIN_PREFIX}% via WS`, done => { + const userListQuery = new UserCountQuery({ loginPattern: `${TEST_USER_LOGIN_PREFIX}%` }); + + wsDeviceHive.user.count(userListQuery) + .then(({ count }) => { + assert.equal(count, Object.keys(TEST_USERS).length); + }) + .then(() => done()) + .catch(done); + }); - it('UserAPI.getDeviceTypes()', done => { + it(`UserAPI.getDeviceTypes()`, done => { Promise.all([httpDeviceHive.user.getDeviceTypes(testUsers[0].id)]) .then(() => done()) @@ -181,7 +206,7 @@ describe('UserAPI', () => { }); - it('UserAPI.assignAllDeviceTypes()', done => { + it(`UserAPI.assignAllDeviceTypes()`, done => { Promise.all([httpDeviceHive.user.assignAllDeviceTypes(testUsers[0].id)]) .then(() => done()) @@ -189,7 +214,7 @@ describe('UserAPI', () => { }); - it('UserAPI.unassignAllDeviceTypes()', done => { + it(`UserAPI.unassignAllDeviceTypes()`, done => { Promise.all([httpDeviceHive.user.unassignAllDeviceTypes(testUsers[0].id)]) .then(() => done()) @@ -197,7 +222,7 @@ describe('UserAPI', () => { }); - it('UserAPI.assignDeviceType()', done => { + it(`UserAPI.assignDeviceType()`, done => { Promise.all([httpDeviceHive.user.assignDeviceType(testUsers[0].id, 1)]) .then(() => done()) @@ -205,13 +230,13 @@ describe('UserAPI', () => { }); - it('UserAPI.getDeviceType()', done => { + it(`UserAPI.getDeviceType()`, done => { Promise.all([httpDeviceHive.user.getDeviceType(testUsers[0].id, 1)]) .then(dataAll => { for (const data of dataAll) { assert.isObject(data); - assert.property(data, 'deviceType'); + assert.property(data, `deviceType`); } }) .then(done) @@ -219,7 +244,7 @@ describe('UserAPI', () => { }); - it('UserAPI.unassignDeviceType()', done => { + it(`UserAPI.unassignDeviceType()`, done => { Promise.all([httpDeviceHive.user.unassignDeviceType(testUsers[0].id, 1)]) .then(() => done()) @@ -227,7 +252,7 @@ describe('UserAPI', () => { }); - it('UserAPI.assignNetwork()', done => { + it(`UserAPI.assignNetwork()`, done => { httpDeviceHive.user.assignNetwork(testUsers[0].id, 1) .then(() => wsDeviceHive.user.assignNetwork(testUsers[1].id, 1)) @@ -236,13 +261,13 @@ describe('UserAPI', () => { }); - it('UserAPI.getNetwork()', done => { + it(`UserAPI.getNetwork()`, done => { Promise.all([httpDeviceHive.user.getNetwork(testUsers[0].id, 1), wsDeviceHive.user.getNetwork(testUsers[1].id, 1)]) .then(dataAll => { for (const data of dataAll) { assert.isObject(data); - assert.property(data, 'network'); + assert.property(data, `network`); } }) .then(done) @@ -250,7 +275,7 @@ describe('UserAPI', () => { }); - it('UserAPI.unassignNetwork()', done => { + it(`UserAPI.unassignNetwork()`, done => { httpDeviceHive.user.unassignNetwork(testUsers[0].id, 1) .then(() => wsDeviceHive.user.unassignNetwork(testUsers[1].id, 1)) @@ -259,11 +284,17 @@ describe('UserAPI', () => { }); - it('UserAPI.delete()', done => { + it(`UserAPI.delete()`, done => { Promise.all([httpDeviceHive.user.delete(testUsers[0].id), wsDeviceHive.user.delete(testUsers[1].id)]) .then(() => done()) .catch(done); }); + after(done => { + httpDeviceHive.disconnect(); + wsDeviceHive.disconnect(); + + done(); + }); }); \ No newline at end of file From dfb5a025f4ee13226abe13ab8ed9da7078c031a0 Mon Sep 17 00:00:00 2001 From: itrambovetskiy Date: Thu, 1 Mar 2018 13:58:39 +0200 Subject: [PATCH 20/22] Integration tests improvements --- .../controllers/DeviceTypeAPI.spec.js | 8 +- .../controllers/NetworkAPI.spec.js | 8 +- test/integration/controllers/UserAPI.spec.js | 176 +++++++++++------- 3 files changed, 119 insertions(+), 73 deletions(-) diff --git a/test/integration/controllers/DeviceTypeAPI.spec.js b/test/integration/controllers/DeviceTypeAPI.spec.js index e41b088..211a86c 100644 --- a/test/integration/controllers/DeviceTypeAPI.spec.js +++ b/test/integration/controllers/DeviceTypeAPI.spec.js @@ -15,12 +15,12 @@ const TEST_DEVICE_TYPE_NAME_PREFIX = `DH-JS-LIB-DEVICE-TYPE-NAME-`; const TEST_DEVICE_TYPE_DESCRIPTION_PREFIX = `DH-JS-LIB-DEVICE-TYPE-NAME-`; const TEST_DEVICE_TYPES = { HTTP: { - name: `${TEST_DEVICE_TYPE_NAME_PREFIX}-${randomString.generate()}`, - description: `${TEST_DEVICE_TYPE_DESCRIPTION_PREFIX}-${randomString.generate()}` + name: `${TEST_DEVICE_TYPE_NAME_PREFIX}${randomString.generate()}`, + description: `${TEST_DEVICE_TYPE_DESCRIPTION_PREFIX}${randomString.generate()}` }, WS: { - name: `${TEST_DEVICE_TYPE_NAME_PREFIX}-${randomString.generate()}`, - description: `${TEST_DEVICE_TYPE_DESCRIPTION_PREFIX}-${randomString.generate()}` + name: `${TEST_DEVICE_TYPE_NAME_PREFIX}${randomString.generate()}`, + description: `${TEST_DEVICE_TYPE_DESCRIPTION_PREFIX}${randomString.generate()}` } }; diff --git a/test/integration/controllers/NetworkAPI.spec.js b/test/integration/controllers/NetworkAPI.spec.js index 54378c7..cab6b77 100644 --- a/test/integration/controllers/NetworkAPI.spec.js +++ b/test/integration/controllers/NetworkAPI.spec.js @@ -15,12 +15,12 @@ const TEST_NETWORK_NAME_PREFIX = `DH-JS-LIB-NETWORK-NAME-`; const TEST_NETWORK_DESCRIPTION_PREFIX = `DH-JS-LIB-NETWORK-NAME-`; const TEST_NETWORKS = { HTTP: { - name: `${TEST_NETWORK_NAME_PREFIX}-${randomString.generate()}`, - description: `${TEST_NETWORK_DESCRIPTION_PREFIX}-${randomString.generate()}` + name: `${TEST_NETWORK_NAME_PREFIX}${randomString.generate()}`, + description: `${TEST_NETWORK_DESCRIPTION_PREFIX}${randomString.generate()}` }, WS: { - name: `${TEST_NETWORK_NAME_PREFIX}-${randomString.generate()}`, - description: `${TEST_NETWORK_DESCRIPTION_PREFIX}-${randomString.generate()}` + name: `${TEST_NETWORK_NAME_PREFIX}${randomString.generate()}`, + description: `${TEST_NETWORK_DESCRIPTION_PREFIX}${randomString.generate()}` } }; diff --git a/test/integration/controllers/UserAPI.spec.js b/test/integration/controllers/UserAPI.spec.js index d5ca2ee..41e760e 100644 --- a/test/integration/controllers/UserAPI.spec.js +++ b/test/integration/controllers/UserAPI.spec.js @@ -1,9 +1,12 @@ const randomString = require(`randomstring`); const chai = require(`chai`); const assert = chai.assert; +const expect = chai.expect; const config = require(`../config`); const DeviceHive = require(`../../../index`); const User = DeviceHive.models.User; +const DeviceType = DeviceHive.models.DeviceType; +const Network = DeviceHive.models.Network; const UserListQuery = DeviceHive.models.query.UserListQuery; const UserCountQuery = DeviceHive.models.query.UserCountQuery; @@ -14,29 +17,47 @@ const wsDeviceHive = new DeviceHive(config.server.ws); const TEST_USER_LOGIN_PREFIX = `DH-JS-LIB-USER-LOGIN-`; const TEST_USERS = { HTTP: { - login: `${TEST_USER_LOGIN_PREFIX}-${randomString.generate()}`, + login: `${TEST_USER_LOGIN_PREFIX}${randomString.generate()}`, role: 1, - status: 1, + status: 0, password: `password`, data: { jsonString: `jsonString` } }, WS: { - login: `${TEST_USER_LOGIN_PREFIX}-${randomString.generate()}`, + login: `${TEST_USER_LOGIN_PREFIX}${randomString.generate()}`, role: 1, - status: 1, + status: 0, password: `password`, data: { jsonString: `jsonString` } } }; +const TEST_DEVICE_TYPE_NAME_PREFIX = `DH-JS-LIB-DEVICE-TYPE-NAME-`; +const TEST_DEVICE_TYPE_DESCRIPTION_PREFIX = `DH-JS-LIB-DEVICE-TYPE-NAME-`; +const TEST_DEVICE_TYPE = { + name: `${TEST_DEVICE_TYPE_NAME_PREFIX}${randomString.generate()}`, + description: `${TEST_DEVICE_TYPE_DESCRIPTION_PREFIX}${randomString.generate()}` +}; +const TEST_NETWORK_NAME_PREFIX = `DH-JS-LIB-NETWORK-NAME-`; +const TEST_NETWORK_DESCRIPTION_PREFIX = `DH-JS-LIB-NETWORK-NAME-`; +const TEST_NETWORK = { + name: `${TEST_NETWORK_NAME_PREFIX}${randomString.generate()}`, + description: `${TEST_NETWORK_DESCRIPTION_PREFIX}${randomString.generate()}` +}; describe(`UserAPI`, () => { + const deviceTypeModel = new DeviceType(TEST_DEVICE_TYPE); + const networkModel = new Network(TEST_NETWORK); before(done => { Promise.all([httpDeviceHive.connect(), wsDeviceHive.connect()]) + .then(() => httpDeviceHive.deviceType.insert(deviceTypeModel)) + .then(({ id }) => TEST_DEVICE_TYPE.id = id) + .then(() => httpDeviceHive.network.insert(networkModel)) + .then(({ id }) => TEST_NETWORK.id = id) .then(() => done()); }); @@ -88,19 +109,19 @@ describe(`UserAPI`, () => { .catch(done); }); - it(`should get user with name: ${TEST_USERS.HTTP.name} via HTTP`, done => { + it(`should get user with login: ${TEST_USERS.HTTP.login} via HTTP`, done => { httpDeviceHive.user.get(TEST_USERS.HTTP.id) .then(user => { - assert.equal(user.name, TEST_USERS.HTTP.name); + assert.equal(user.login, TEST_USERS.HTTP.login); }) .then(() => done()) .catch(done); }); - it(`should get user with name: ${TEST_USERS.WS.name} via WS`, done => { + it(`should get user with login: ${TEST_USERS.WS.login} via WS`, done => { wsDeviceHive.user.get(TEST_USERS.WS.id) .then(user => { - assert.equal(user.name, TEST_USERS.WS.name); + assert.equal(user.login, TEST_USERS.WS.login); }) .then(() => done()) .catch(done); @@ -153,24 +174,24 @@ describe(`UserAPI`, () => { }); it(`should update current user with login ${config.TEST_USER_LOGIN} via HTTP`, done => { - const userModel = new User({ status: 0 }); + const userModel = new User({ data: { update: true } }); httpDeviceHive.user.updateCurrent(userModel) .then(() => httpDeviceHive.user.getCurrent()) .then(user => { - assert.equal(user.status, userModel.status); + assert.deepEqual(user.data, userModel.data); }) .then(() => done()) .catch(done); }); it(`should update current user with login ${config.TEST_USER_LOGIN} via WS`, done => { - const userModel = new User({ status: 1 }); + const userModel = new User({ data: { update: true } }); wsDeviceHive.user.updateCurrent(userModel) .then(() => wsDeviceHive.user.getCurrent()) .then(user => { - assert.equal(user.status, userModel.status); + assert.deepEqual(user.data, userModel.data); }) .then(() => done()) .catch(done); @@ -198,103 +219,128 @@ describe(`UserAPI`, () => { .catch(done); }); - it(`UserAPI.getDeviceTypes()`, done => { - - Promise.all([httpDeviceHive.user.getDeviceTypes(testUsers[0].id)]) + it(`should get user's deviceTypes via HTTP`, done => { + httpDeviceHive.user.getDeviceTypes(TEST_USERS.HTTP.id) + .then(deviceTypes => { + assert.exists(deviceTypes); + expect(deviceTypes).to.be.an('array'); + }) .then(() => done()) .catch(done); }); - - it(`UserAPI.assignAllDeviceTypes()`, done => { - - Promise.all([httpDeviceHive.user.assignAllDeviceTypes(testUsers[0].id)]) + it(`should unassign all device types from user with login: ${TEST_USERS.HTTP.login} via HTTP`, done => { + httpDeviceHive.user.unassignAllDeviceTypes(TEST_USERS.HTTP.id) + .then(() => httpDeviceHive.user.getDeviceTypes(TEST_USERS.HTTP.id)) + .then((deviceTypes) => { + assert.exists(deviceTypes); + expect(deviceTypes).to.be.an('array').that.is.empty; + }) .then(() => done()) .catch(done); }); - - it(`UserAPI.unassignAllDeviceTypes()`, done => { - - Promise.all([httpDeviceHive.user.unassignAllDeviceTypes(testUsers[0].id)]) + it(`should assign all device types to user with login: ${TEST_USERS.HTTP.login} via HTTP`, done => { + httpDeviceHive.user.assignAllDeviceTypes(TEST_USERS.HTTP.id) + .then(() => httpDeviceHive.user.getDeviceTypes(TEST_USERS.HTTP.id)) + .then((deviceTypes) => { + assert.exists(deviceTypes); + expect(deviceTypes).to.be.an('array').that.is.not.empty; + }) .then(() => done()) .catch(done); }); - - it(`UserAPI.assignDeviceType()`, done => { - - Promise.all([httpDeviceHive.user.assignDeviceType(testUsers[0].id, 1)]) + it(`should assign device type with name: ${TEST_DEVICE_TYPE.name} to user with login: ${TEST_USERS.HTTP.login} via HTTP`, done => { + httpDeviceHive.user.unassignAllDeviceTypes(TEST_USERS.HTTP.id) + .then(() => httpDeviceHive.user.assignDeviceType(TEST_USERS.HTTP.id, TEST_DEVICE_TYPE.id)) .then(() => done()) .catch(done); }); - - it(`UserAPI.getDeviceType()`, done => { - - Promise.all([httpDeviceHive.user.getDeviceType(testUsers[0].id, 1)]) - .then(dataAll => { - for (const data of dataAll) { - assert.isObject(data); - assert.property(data, `deviceType`); - } + it(`should get users device type with name: ${TEST_DEVICE_TYPE.name} via HTTP`, done => { + httpDeviceHive.user.getDeviceType(TEST_USERS.HTTP.id, TEST_DEVICE_TYPE.id) + .then(({ deviceType }) => { + assert.exists(deviceType); + assert.equal(deviceType.name, TEST_DEVICE_TYPE.name); }) - .then(done) + .then(() => done()) .catch(done); }); + it(`should unassign device type with name: ${TEST_DEVICE_TYPE.name} from user with login: ${TEST_USERS.HTTP.login} via HTTP`, done => { + httpDeviceHive.user.unassignDeviceType(TEST_USERS.HTTP.id, TEST_DEVICE_TYPE.id) + .then(() => httpDeviceHive.user.getDeviceType(TEST_USERS.HTTP.id, TEST_DEVICE_TYPE.id)) + .then(() => done(new Error(`Device type with id ${TEST_DEVICE_TYPE.id} for user with id ${TEST_USERS.HTTP.id} should not be found`))) + .catch(() => done()); + }); - it(`UserAPI.unassignDeviceType()`, done => { - - Promise.all([httpDeviceHive.user.unassignDeviceType(testUsers[0].id, 1)]) + it(`should assign network with name: ${TEST_NETWORK.name} to user with login: ${TEST_USERS.HTTP.login} via HTTP`, done => { + httpDeviceHive.user.assignNetwork(TEST_USERS.HTTP.id, TEST_NETWORK.id) .then(() => done()) .catch(done); }); - - it(`UserAPI.assignNetwork()`, done => { - - httpDeviceHive.user.assignNetwork(testUsers[0].id, 1) - .then(() => wsDeviceHive.user.assignNetwork(testUsers[1].id, 1)) + it(`should get users network with name: ${TEST_NETWORK.name} via HTTP`, done => { + httpDeviceHive.user.getNetwork(TEST_USERS.HTTP.id, TEST_NETWORK.id) + .then(({ network }) => { + assert.exists(network); + assert.equal(network.name, TEST_NETWORK.name); + }) .then(() => done()) .catch(done); }); + it(`should unassign network with name: ${TEST_NETWORK.name} from user with login: ${TEST_USERS.HTTP.login} via HTTP`, done => { + httpDeviceHive.user.unassignNetwork(TEST_USERS.HTTP.id, TEST_NETWORK.id) + .then(() => httpDeviceHive.user.getNetwork(TEST_USERS.HTTP.id, TEST_NETWORK.id)) + .then(() => done(new Error(`Network with id ${TEST_NETWORK.id} for user with id ${TEST_USERS.HTTP.id} should not be found`))) + .catch(() => done()); + }); - it(`UserAPI.getNetwork()`, done => { + it(`should assign network with name: ${TEST_NETWORK.name} to user with login: ${TEST_USERS.WS.login} via WS`, done => { + wsDeviceHive.user.assignNetwork(TEST_USERS.WS.id, TEST_NETWORK.id) + .then(() => done()) + .catch(done); + }); - Promise.all([httpDeviceHive.user.getNetwork(testUsers[0].id, 1), wsDeviceHive.user.getNetwork(testUsers[1].id, 1)]) - .then(dataAll => { - for (const data of dataAll) { - assert.isObject(data); - assert.property(data, `network`); - } + it(`should get users network with name: ${TEST_NETWORK.name} via WS`, done => { + wsDeviceHive.user.getNetwork(TEST_USERS.WS.id, TEST_NETWORK.id) + .then(({ network }) => { + assert.exists(network); + assert.equal(network.name, TEST_NETWORK.name); }) - .then(done) + .then(() => done()) .catch(done); }); + it(`should unassign network with name: ${TEST_NETWORK.name} from user with login: ${TEST_USERS.WS.login} via WS`, done => { + wsDeviceHive.user.unassignNetwork(TEST_USERS.WS.id, TEST_NETWORK.id) + .then(() => wsDeviceHive.user.getNetwork(TEST_USERS.WS.id, TEST_NETWORK.id)) + .then(() => done(new Error(`Network with id ${TEST_NETWORK.id} for user with id ${TEST_USERS.WS.id} should not be found`))) + .catch(() => done()); + }); - it(`UserAPI.unassignNetwork()`, done => { - - httpDeviceHive.user.unassignNetwork(testUsers[0].id, 1) - .then(() => wsDeviceHive.user.unassignNetwork(testUsers[1].id, 1)) + it(`should delete user with login: ${TEST_USERS.HTTP.login} via HTTP`, done => { + httpDeviceHive.user.delete(TEST_USERS.HTTP.id) .then(() => done()) .catch(done); }); - - - it(`UserAPI.delete()`, done => { - Promise.all([httpDeviceHive.user.delete(testUsers[0].id), wsDeviceHive.user.delete(testUsers[1].id)]) + it(`should delete user with login: ${TEST_USERS.WS.login} via WS`, done => { + wsDeviceHive.user.delete(TEST_USERS.WS.id) .then(() => done()) .catch(done); }); after(done => { - httpDeviceHive.disconnect(); - wsDeviceHive.disconnect(); - - done(); + httpDeviceHive.deviceType.delete(TEST_DEVICE_TYPE.id) + .then(() => httpDeviceHive.network.delete(TEST_NETWORK.id)) + .then(() => { + httpDeviceHive.disconnect(); + wsDeviceHive.disconnect(); + + done(); + }); }); }); \ No newline at end of file From 8952f796532042ebc5a93bce47cc999561c0f6d1 Mon Sep 17 00:00:00 2001 From: itrambovetskiy Date: Thu, 1 Mar 2018 14:14:29 +0200 Subject: [PATCH 21/22] Unit tests improvements --- test/integration/controllers/DeviceCommandAPI.spec.js | 8 ++++---- test/unit/controllers/DeviceNotificationAPI.http.spec.js | 1 - test/unit/controllers/DeviceNotificationAPI.ws.spec.js | 1 - test/unit/modelsQuery/NotificationListQuery.spec.js | 1 - 4 files changed, 4 insertions(+), 7 deletions(-) diff --git a/test/integration/controllers/DeviceCommandAPI.spec.js b/test/integration/controllers/DeviceCommandAPI.spec.js index d1e4e52..6e5d353 100644 --- a/test/integration/controllers/DeviceCommandAPI.spec.js +++ b/test/integration/controllers/DeviceCommandAPI.spec.js @@ -270,12 +270,12 @@ describe('DeviceCommandAPI', () => { .then(() => done()) .catch(done); }); - }, 200); + }, 300); setTimeout(() => { TEST_DEVICE_COMMANDS.HTTP.command = `command-${randomString.generate()}`; httpDeviceHive.command.insert(DH_COMMANDS_TEST_DEVICE.id, new Command(TEST_DEVICE_COMMANDS.HTTP)); - }, 300); + }, 500); }) .catch(done); }); @@ -295,12 +295,12 @@ describe('DeviceCommandAPI', () => { .then(() => done()) .catch(done); }); - }, 200); + }, 300); setTimeout(() => { TEST_DEVICE_COMMANDS.WS.command = `command-${randomString.generate()}`; wsDeviceHive.command.insert(DH_COMMANDS_TEST_DEVICE.id, new Command(TEST_DEVICE_COMMANDS.WS)); - }, 300); + }, 500); }) .catch(done); }); diff --git a/test/unit/controllers/DeviceNotificationAPI.http.spec.js b/test/unit/controllers/DeviceNotificationAPI.http.spec.js index 26fa6fb..260cc1a 100644 --- a/test/unit/controllers/DeviceNotificationAPI.http.spec.js +++ b/test/unit/controllers/DeviceNotificationAPI.http.spec.js @@ -96,7 +96,6 @@ describe('NotificationAPI HTTP', () => { start: '2018-02-09T10:09:03.033Z', end: '2018-02-09T10:09:03.033Z', notification: 'notification', - status: 'status', sortField: 'sortField', sortOrder: 'sortOrder', take: '1', diff --git a/test/unit/controllers/DeviceNotificationAPI.ws.spec.js b/test/unit/controllers/DeviceNotificationAPI.ws.spec.js index 0386e3d..fc3facd 100644 --- a/test/unit/controllers/DeviceNotificationAPI.ws.spec.js +++ b/test/unit/controllers/DeviceNotificationAPI.ws.spec.js @@ -76,7 +76,6 @@ describe('NotificationAPI WS', () => { start: '2018-02-09T10:09:03.033Z', end: '2018-02-09T10:09:03.033Z', notification: 'notification', - status: 'status', sortField: 'sortField', sortOrder: 'sortOrder', take: '1', diff --git a/test/unit/modelsQuery/NotificationListQuery.spec.js b/test/unit/modelsQuery/NotificationListQuery.spec.js index 96c0a05..90ba20b 100644 --- a/test/unit/modelsQuery/NotificationListQuery.spec.js +++ b/test/unit/modelsQuery/NotificationListQuery.spec.js @@ -9,7 +9,6 @@ describe('NotificationListQuery', () => { start: '2018-02-09T10:09:03.033Z', end: '2018-02-09T10:09:03.033Z', notification: 'string', - status: 'string', sortField: 'string', sortOrder: 'string', take: 1, From 8d3c8ae49b080ec2ed199908d3e62035fae763a7 Mon Sep 17 00:00:00 2001 From: itrambovetskiy Date: Thu, 1 Mar 2018 14:24:31 +0200 Subject: [PATCH 22/22] Slight code improvements --- src/ApiStrategy.js | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/ApiStrategy.js b/src/ApiStrategy.js index 85d2b55..4940406 100644 --- a/src/ApiStrategy.js +++ b/src/ApiStrategy.js @@ -51,10 +51,17 @@ class ApiStrategy extends EventEmitter { me.strategy = new (ApiStrategy.getType(mainServiceURL))({ mainServiceURL, authServiceURL, pluginServiceURL }); me.strategy.on(`message`, (message) => { - if (message.subscriptionId && message.action) { - me.emit(`message`, message[message.action.split(`/`)[0]]); - } else { - me.emit(`message`, message); + switch (me.strategy.type) { + case HTTP.TYPE: + me.emit(`message`, message); + break; + case WS.TYPE: + if (message.subscriptionId && message.action) { + me.emit(`message`, message[message.action.split(`/`)[0]]); + } else { + me.emit(`message`, message); + } + break; } }); }