diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..68bf01fa0 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,18 @@ +# editorconfig.org +root = true + +# Unix-style newlines with a newline ending every file +[*] +end_of_line = lf +charset = utf-8 +insert_final_newline = true + +[*.{json,yml,md,babelrc,eslintrc,remarkrc}] +indent_style = space +indent_size = 2 +trim_trailing_whitespace = true + +[*.{js}] +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 000000000..c01a14034 --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,12 @@ +{ + "extends": "tamia", + "parserOptions": { + "sourceType": "module" + }, + "plugins": ["prettier"], + "rules": { + "prettier/prettier": "error", + "no-shadow": 0, + "valid-jsdoc": 0 + } +} diff --git a/.gitignore b/.gitignore index 80a4c7bc5..23cfd3090 100644 --- a/.gitignore +++ b/.gitignore @@ -13,4 +13,5 @@ .project .metadata npm-debug.log +.eslintcache diff --git a/.jshintrc b/.jshintrc deleted file mode 100644 index 517729321..000000000 --- a/.jshintrc +++ /dev/null @@ -1,31 +0,0 @@ -{ - "curly": true, - "eqeqeq": true, - "immed": true, - "latedef": true, - "newcap": true, - "noarg": true, - "noempty": true, - "quotmark": "single", - "undef": true, - "unused": true, - "trailing": true, - "maxparams": 8, - "maxdepth": 4, - "camelcase": true, - "maxlen": 120, - "node": true, - "expr": true, - "unused": "vars", - "esversion": 6, - "globals": { - "describe":true, - "it": true, - "expect": true, - "before": true, - "after": true, - "beforeEach": true, - "afterEach": true, - "mock": true - } -} \ No newline at end of file diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 000000000..8238852e0 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,9 @@ +{ + "arrowParens": "always", + "bracketSpacing": true, + "singleQuote": true, + "parser": "flow", + "printWidth": 120, + "trailingComma": "none", + "tabWidth": 4 +} \ No newline at end of file diff --git a/CHANGES_NEXT_RELEASE b/CHANGES_NEXT_RELEASE index e69de29bb..400c995c7 100644 --- a/CHANGES_NEXT_RELEASE +++ b/CHANGES_NEXT_RELEASE @@ -0,0 +1,7 @@ +Update codebase to use ES6 +- Remove JSHint and jshint overrides +- Add esLint using standard tamia presets +- Replace var with let/const +- Fix or disable eslint errors +Add prettier code formatting +Add husky and lint-staged diff --git a/README.md b/README.md index 38d390c4a..ebe3a29f3 100644 --- a/README.md +++ b/README.md @@ -9,22 +9,19 @@ [![Coverage Status](https://coveralls.io/repos/github/telefonicaid/iotagent-node-lib/badge.svg?branch=master)](https://coveralls.io/github/telefonicaid/iotagent-node-lib?branch=master) ![Status](https://nexus.lab.fiware.org/static/badges/statuses/iot-node-lib.svg) -This project aims to provide a Node.js module to enable IoT Agent developers to -build custom agents for their devices that can easily connect to NGSI Context -Brokers (such as [Orion](https://github.com/telefonicaid/fiware-orion)). - -An IoT Agent is a component that lets groups of devices send their data to and -be managed from a FIWARE NGSI Context Broker using their own native protocols. -IoT Agents should also be able to deal with security aspects of the FIWARE -platform (authentication and authorization of the channel) and provide other -common services to the device programmer. - -This project is part of [FIWARE](https://www.fiware.org/). For more information -check the FIWARE Catalogue entry for the +This project aims to provide a Node.js module to enable IoT Agent developers to build custom agents for their devices +that can easily connect to NGSI Context Brokers (such as [Orion](https://github.com/telefonicaid/fiware-orion)). + +An IoT Agent is a component that lets groups of devices send their data to and be managed from a FIWARE NGSI Context +Broker using their own native protocols. IoT Agents should also be able to deal with security aspects of the FIWARE +platform (authentication and authorization of the channel) and provide other common services to the device programmer. + +This project is part of [FIWARE](https://www.fiware.org/). For more information check the FIWARE Catalogue entry for the [IoT Agents](https://github.com/Fiware/catalogue/tree/master/iot-agents). | :books: [Documentation](https://iotagent-node-lib.rtfd.io) | :mortar_board: [Academy](https://fiware-academy.readthedocs.io/en/latest/iot-agents/idas) | :dart: [Roadmap](https://github.com/telefonicaid/iotagent-node-lib/blob/master/docs/roadmap.md) | -|---|---|---| +| ---------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | + ## Index @@ -59,7 +56,6 @@ functionality provided by the IoT Agent node lin (e.g. for contecting to a conex its device communications using a common vocabulary regardless of the payload, syntax or transport protocol used by the device itself. - ## Install The **IoT Agent node library** is not a standalone product and should be added as a dependency to `package.json` of the @@ -78,43 +74,39 @@ In order to use the library within your own IoT Agent, you must first you requir const iotagentLib = require("iotagent-node-lib"); ``` -Information about how to configure the Library can be found at the corresponding -section of the +Information about how to configure the Library can be found at the corresponding section of the [Installation & Administration Guide](doc/installationguide.md). ## Usage -This library has no packaging or build processes. The [Getting Started](doc/getting-started.md) is a good place to start. -Usage of the library is explained in the [User & Programmers Manual](doc/usermanual.md). +This library has no packaging or build processes. The [Getting Started](doc/getting-started.md) is a good place to +start. Usage of the library is explained in the [User & Programmers Manual](doc/usermanual.md). -- Details of the architecture of an IoT Agent be found [here](doc/architecture.md). -- Further Advanced topics can be found [here](doc/advanced-topics.md). -- The following features are listed as [deprecated](doc/deprecated.md). +- Details of the architecture of an IoT Agent be found [here](doc/architecture.md). +- Further Advanced topics can be found [here](doc/advanced-topics.md). +- The following features are listed as [deprecated](doc/deprecated.md). ## API The **IoT Agent node library** offers a simple REST API which provides common functionality to access, provision and -decommission devices. -[API](doc/api.md). +decommission devices. [API](doc/api.md). ## Testing - Contributions to development can be found [here](doc/development.md) - additional contributions are welcome. ### Agent Console -A command-line client to experiment with the library is packed with it. The -command-line client can be started using the following command: +A command-line client to experiment with the library is packed with it. The command-line client can be started using the +following command: ```console bin/agentConsole.js ``` -The client offers an API similar to the one offered by the library: it can start -and stop an IoT agent, register and unregister devices, send measures mimicking -the device and receive updates of the device data. Take into account that, by -default, the console uses the same `config.js` file than the IoT Agent. +The client offers an API similar to the one offered by the library: it can start and stop an IoT agent, register and +unregister devices, send measures mimicking the device and receive updates of the device data. Take into account that, +by default, the console uses the same `config.js` file than the IoT Agent. The command-line client creates a console that offers the following options: @@ -172,24 +164,20 @@ listdevices #### Command-line testing -The library also offers a Context Broker and IoT Agent client that can be used -to: +The library also offers a Context Broker and IoT Agent client that can be used to: -- Simulate operations to the Context Broker used by the IoT Agent, triggering - Context Provider forwardings for lazy attributes and checking the - appropriate values for active ones. -- Simulate operations to the Device Provisioning API and Configuration API of - the IoT Agent. +- Simulate operations to the Context Broker used by the IoT Agent, triggering Context Provider forwardings for lazy + attributes and checking the appropriate values for active ones. +- Simulate operations to the Device Provisioning API and Configuration API of the IoT Agent. -The tester can be started with the following command, from the root folder of -the project: +The tester can be started with the following command, from the root folder of the project: ```console bin/iotAgentTester.js ``` -From the command-line, the `help` command can be used to show a description of -the currently supported features. These are the following: +From the command-line, the `help` command can be used to show a description of the currently supported features. These +are the following: ```text stressInit @@ -304,30 +292,26 @@ migrate subservices, use the "*" value. ``` -The agent session stores transient configuration data about the target Context -Broker and the target IoT Agent. This configuration is independent, and can be -checked with the `showConfigCb` and `showConfigIot` commands, respectively. -Their values can be changed with the `configCb` and `configIot` commands -respectively. The new configurations will be deleted upon startup. +The agent session stores transient configuration data about the target Context Broker and the target IoT Agent. This +configuration is independent, and can be checked with the `showConfigCb` and `showConfigIot` commands, respectively. +Their values can be changed with the `configCb` and `configIot` commands respectively. The new configurations will be +deleted upon startup. #### Creating specialized testers The command-line testing tools make use of the -[command-node Node.js library](https://github.com/telefonicaid/command-shell-lib) -for command-line utils. In order to help creating testing tools for IoTAgents of -specific protocols, all the commands of the library tester are offered as a -array that can be directly imported into other Command-Line tools, using the -following steps: +[command-node Node.js library](https://github.com/telefonicaid/command-shell-lib) for command-line utils. In order to +help creating testing tools for IoTAgents of specific protocols, all the commands of the library tester are offered as a +array that can be directly imported into other Command-Line tools, using the following steps: -- Require the `iotagent-node-lib` command-line module in your command-line - tool: +- Require the `iotagent-node-lib` command-line module in your command-line tool: ```javascript - var iotaCommands = require('iotagent-node-lib').commandLine; +var iotaCommands = require("iotagent-node-lib").commandLine; ``` -- Initialize the command-line utils (the initialization function takes two - arguments, that will be explained in detail below: +- Initialize the command-line utils (the initialization function takes two arguments, that will be explained in detail + below: ```javascript iotaCommands.init(configCb, configIot); @@ -342,56 +326,47 @@ commands = commands.concat(commands, iotaCommands.commands); - Execute the command-line interpreter as usual: ```javascript -clUtils.initialize(commandLine.commands, 'IoT Agent tester> '); +clUtils.initialize(commandLine.commands, "IoT Agent tester> "); ``` -The command-line module makes use of two configuration objects. Both can be -shown and edited in the command-line using the provided commands, but a default -value must be present. +The command-line module makes use of two configuration objects. Both can be shown and edited in the command-line using +the provided commands, but a default value must be present. -The Context Broker configuration object holds all the information about the -Context Broker where the IoT Agent to be tested is connected. It MUST contain -the following attributes: +The Context Broker configuration object holds all the information about the Context Broker where the IoT Agent to be +tested is connected. It MUST contain the following attributes: - **host**: host where the Context Broker instance is located. - **port**: port where the Context Broker instance is listening. - **service**: service that will be used in all the NGSI operations. - **subservice**: service that will be used in all the NGSI operations. -The IoT Agent configuration object holds information about the IoT Agent that is -being tested. It MUST contain the following attributes: +The IoT Agent configuration object holds information about the IoT Agent that is being tested. It MUST contain the +following attributes: - **host**: host where the IoT Agent instance is located. - **port**: port where the IoT Agent instance is listening. -- **service**: service that will be used to group devices and device - information. -- **subservice**: subservice that will be used to group devices and device - information. +- **service**: service that will be used to group devices and device information. +- **subservice**: subservice that will be used to group devices and device information. --- ## Licence -The IoT Agent Node Library is licensed under [Affero General Public License (GPL) -version 3](./LICENSE). +The IoT Agent Node Library is licensed under [Affero General Public License (GPL) version 3](./LICENSE). © 2019 Telefonica Investigación y Desarrollo, S.A.U - - ### Are there any legal issues with AGPL 3.0? Is it safe for me to use? -There is absolutely no problem in using a product licensed under AGPL 3.0. Issues with GPL -(or AGPL) licenses are mostly related with the fact that different people assign different -interpretations on the meaning of the term “derivate work” used in these licenses. Due to this, -some people believe that there is a risk in just _using_ software under GPL or AGPL licenses -(even without _modifying_ it). +There is absolutely no problem in using a product licensed under AGPL 3.0. Issues with GPL (or AGPL) licenses are mostly +related with the fact that different people assign different interpretations on the meaning of the term “derivate work” +used in these licenses. Due to this, some people believe that there is a risk in just _using_ software under GPL or AGPL +licenses (even without _modifying_ it). For the avoidance of doubt, the owners of this software licensed under an AGPL-3.0 license wish to make a clarifying public statement as follows: -> Please note that software derived as a result of modifying the source code of this -> software in order to fix a bug or incorporate enhancements is considered a derivative -> work of the product. Software that merely uses or aggregates (i.e. links to) an otherwise -> unmodified version of existing software is not considered a derivative work, and therefore -> it does not need to be released as under the same license, or even released as open source. +> Please note that software derived as a result of modifying the source code of this software in order to fix a bug or +> incorporate enhancements is considered a derivative work of the product. Software that merely uses or aggregates (i.e. +> links to) an otherwise unmodified version of existing software is not considered a derivative work, and therefore it +> does not need to be released as under the same license, or even released as open source. diff --git a/bin/agentConsole.js b/bin/agentConsole.js index 9ddfa4cab..dfe15ea8e 100755 --- a/bin/agentConsole.js +++ b/bin/agentConsole.js @@ -23,53 +23,58 @@ * please contact with::[contacto@tid.es] */ -var readline = require('readline'), - iotAgentLib = require('../lib/fiware-iotagent-lib'), - commandUtils = require('command-shell-lib'), - config = require('../config'), - logger = require('logops'), - async = require('async'), - separator = '\n\n\t'; - -var commands = { - 'start': { +/* eslint-disable no-unused-vars */ +/* eslint-disable no-console */ + +const readline = require('readline'); +const iotAgentLib = require('../lib/fiware-iotagent-lib'); +const commandUtils = require('command-shell-lib'); +let config = require('../config'); +const logger = require('logops'); +const async = require('async'); +const separator = '\n\n\t'; + +const commands = { + start: { parameters: [], description: '\tStart the IoT Agent', handler: startApp }, - 'stop': { + stop: { parameters: [], description: '\tStop the IoT Agent', handler: stopApp }, - 'register': { + register: { parameters: ['id', 'type'], - description: '\tRegister a new device in the IoT Agent. The attributes to register will be extracted from the\n' + + description: + '\tRegister a new device in the IoT Agent. The attributes to register will be extracted from the\n' + '\ttype configuration', handler: registerDevice }, - 'unregister': { + unregister: { parameters: ['id', 'type'], description: '\tUnregister the selected device', handler: unregisterDevice }, - 'showConfig': { + showConfig: { parameters: [], description: '\tShow the current configuration file', handler: showConfig }, - 'config': { + config: { parameters: ['newConfig'], description: '\tChange the configuration file to a new one', handler: changeConfig }, - 'updatevalue': { + updatevalue: { parameters: ['deviceId', 'deviceType', 'attributes'], - description: '\tUpdate a device value in the Context Broker. The attributes should be triads with the following\n' + + description: + '\tUpdate a device value in the Context Broker. The attributes should be triads with the following\n' + '\tformat: "name/type/value" sepparated by commas.', handler: updateDeviceValue }, - 'listdevices': { + listdevices: { parameters: [], description: '\tList all the devices that have been registered in this IoT Agent session\n', handler: listDevices @@ -79,9 +84,9 @@ var commands = { function handleError(message) { return function (error) { if (error) { - console.log('\n\033[31mERROR:\033[0m %s', error.message); + console.log('\n\\033[31mERROR:\\033[0m %s', error.message); } else { - console.log(message) + console.log(message); } commandUtils.prompt(); @@ -91,11 +96,11 @@ function handleError(message) { function listDevices() { iotAgentLib.listDevices(config.service, config.subservice, function (error, devices) { if (error) { - console.log('\n\033[31mERROR:\033[0m %s', error.message); + console.log('\n\\033[31mERROR:\\033[0m %s', error.message); } else { - var keys = Object.keys(devices); + const keys = Object.keys(devices); - for (var i = 0; i < keys.length; i++) { + for (let i = 0; i < keys.length; i++) { console.log('\n\n%s\n', JSON.stringify(devices[keys[i]], null, 4)); } @@ -105,16 +110,15 @@ function listDevices() { } function extractAttributes(attributeString, callback) { - var attributes = attributeString.split(','), - attributesResult = []; - - for (var i = 0; i < attributes.length; i++) { - var fields = attributes[i].split('/'), - attribute = { - name: fields[0], - type: fields[1] - }; + const attributes = attributeString.split(','); + const attributesResult = []; + for (let i = 0; i < attributes.length; i++) { + const fields = attributes[i].split('/'); + const attribute = { + name: fields[0], + type: fields[1] + }; if (fields[2]) { attribute.value = fields[2]; @@ -135,24 +139,32 @@ function changeConfig(command) { } function writeHandler(id, type, attributes, callback) { - console.log('\n\nFake WRITE handler for update in entity [%s] with type [%s]\n%s\n', - id, type, JSON.stringify(attributes, null, 4)); + console.log( + '\n\nFake WRITE handler for update in entity [%s] with type [%s]\n%s\n', + id, + type, + JSON.stringify(attributes, null, 4) + ); callback(null, { - id: id, - type: type, - attributes: attributes + id, + type, + attributes }); } function readHandler(id, type, attributes, callback) { - console.log('\n\nFake READ handler for update in entity [%s] with type [%s]\n%s\n' - , id, type, JSON.stringify(attributes, null, 4)); - - var sensorData = { - id: id, + console.log( + '\n\nFake READ handler for update in entity [%s] with type [%s]\n%s\n', + id, + type, + JSON.stringify(attributes, null, 4) + ); + + const sensorData = { + id, isPattern: false, - type: type, + type, attributes: [ { name: 'luminance', @@ -181,7 +193,7 @@ function exitAgent(command) { } function registerDevice(command) { - var device = { + const device = { id: command[0], type: command[1] }; @@ -196,17 +208,26 @@ function unregisterDevice(command) { } function updateDeviceValue(command) { - iotAgentLib.getDevice(command[0], function(error, device) { + iotAgentLib.getDevice(command[0], function (error, device) { if (device) { - extractAttributes(command[2], function(error, attributes) { - iotAgentLib.update(device.name, device.type, '', attributes, device, - handleError('Device value updated')); + extractAttributes(command[2], function (error, attributes) { + iotAgentLib.update( + device.name, + device.type, + '', + attributes, + device, + handleError('Device value updated') + ); }); } else { - async.waterfall([ - async.apply(extractAttributes, command[2]), - async.apply(iotAgentLib.update, command[0], command[1], '') - ], handleError('Device value updated')); + async.waterfall( + [ + async.apply(extractAttributes, command[2]), + async.apply(iotAgentLib.update, command[0], command[1], '') + ], + handleError('Device value updated') + ); } }); } @@ -215,20 +236,20 @@ function queryHandler(id, type, attributes, callback) { console.log('Handling query for [%s] of type [%s]:\n%s', JSON.stringify(attributes)); callback(null, { - type: type, + type, isPattern: false, - id: id, + id, attributes: [] }); } function updateHandler(id, type, attributes, callback) { - console.log("Update message received for device with id [%s] and type [%s]", id, type); + console.log('Update message received for device with id [%s] and type [%s]', id, type); callback(null, { - type: type, + type, isPattern: false, - id: id, + id, attributes: [] }); } diff --git a/bin/iotAgentTester.js b/bin/iotAgentTester.js index 73b9a2a2e..5eb1b4c82 100755 --- a/bin/iotAgentTester.js +++ b/bin/iotAgentTester.js @@ -22,24 +22,23 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; -var commandLine = require('../lib/command/commandLine'), - clUtils = require('command-shell-lib'), - configCb = { - host: 'localhost', - port: 1026, - service: 'tester', - subservice: '/test' - }, - configIot = { - host: 'localhost', - port: 4041, - name: 'default', - service: 'tester', - subservice: '/test' - }; +const commandLine = require('../lib/command/commandLine'); +const clUtils = require('command-shell-lib'); +const configCb = { + host: 'localhost', + port: 1026, + service: 'tester', + subservice: '/test' +}; +const configIot = { + host: 'localhost', + port: 4041, + name: 'default', + service: 'tester', + subservice: '/test' +}; commandLine.init(configCb, configIot); -clUtils.initialize(commandLine.commands, 'IoT Agent tester> '); \ No newline at end of file +clUtils.initialize(commandLine.commands, 'IoT Agent tester> '); diff --git a/config-blank.js b/config-blank.js index f57209bc6..4a76214ee 100644 --- a/config-blank.js +++ b/config-blank.js @@ -33,8 +33,7 @@ var config = { deviceRegistry: { type: 'memory' }, - types: { - }, + types: {}, service: 'tester', subservice: '/test', providerUrl: 'http://192.168.56.1:4041', diff --git a/config.js b/config.js index cb6c8d3b6..7cfde892d 100644 --- a/config.js +++ b/config.js @@ -44,7 +44,7 @@ var config = { type: 'memory' }, types: { - 'Light': { + Light: { url: '/', apikey: '', type: 'Light', diff --git a/doc/advanced-topics.md b/doc/advanced-topics.md index 4e98f3214..1d44bd120 100644 --- a/doc/advanced-topics.md +++ b/doc/advanced-topics.md @@ -138,7 +138,7 @@ The library provides some plugins out of the box, in the `dataPlugins` collectio use the `addQueryMiddleware` and `addUpdateMiddleware` functions with the selected plugin, as in the example: ```javascript -var iotaLib = require('iotagent-node-lib'); +var iotaLib = require("iotagent-node-lib"); iotaLib.addUpdateMiddleware(iotaLib.dataPlugins.compressTimestamp.update); iotaLib.addQueryMiddleware(iotaLib.dataPlugins.compressTimestamp.query); diff --git a/doc/api.md b/doc/api.md index 514bafb78..47b8f7578 100644 --- a/doc/api.md +++ b/doc/api.md @@ -75,23 +75,23 @@ information configured: The table below shows the information held in the service group provisioning resource. The table also contains the correspondence between the API resource fields and the same fields in the database model. -| Payload Field | DB Field | Definition | -| --------------------- | -------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `service` | `service` | Service of the devices of this type | -| `subservice` | `subservice` | Subservice of the devices of this type. | -| `resource` | `resource` | string representing the Southbound resource that will be used to assign a type to a device (e.g.: pathname in the southbound port). | -| `apikey` | `apikey` | API Key string. | -| `timestamp` | `timestamp` | Optional flagw whether to include the `TimeInstant`within each entity created, as well as a `TimeInstant` metadata to each attribute, with the current timestamp | -| `entity_type` | `entity_type` | name of the Entity `type` to assign to the group. | -| `trust` | `trust` | trust token to use for secured access to the Context Broker for this type of devices (optional; only needed for secured scenarios). | -| `cbHost` | `cbHost` | Context Broker connection information. This options can be used to override the global ones for specific types of devices. | -| `lazy` | `lazy` | list of common lazy attributes of the device. For each attribute, its `name` and `type` must be provided. | -| `commands` | `commands` | list of common commands attributes of the device. For each attribute, its `name` and `type` must be provided, additional `metadata` is optional. | -| `attributes` | `attributes` | list of common active attributes of the device. For each attribute, its `name` and `type` must be provided, additional `metadata` is optional. | -| `static_attributes` | `staticAttributes` | this attributes will be added to all the entities of this group 'as is', additional `metadata` is optional. | -| `internal_attributes` | `internalAttributes` | optional section with free format, to allow specific IoT Agents to store information along with the devices in the Device Registry. | -| `expressionLanguage` | `expresionLanguage` | optional boolean value, to set expression language used to compute expressions, possible values are: legacy or jexl. When not set or wrongly set, legacy is used as default value. | -| `explicitAttrs` | `explicitAttrs` | optional boolean value, to support selective ignore of measures so that IOTA doesn’t progress. If not specified default is false. | +| Payload Field | DB Field | Definition | +| --------------------- | -------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `service` | `service` | Service of the devices of this type | +| `subservice` | `subservice` | Subservice of the devices of this type. | +| `resource` | `resource` | string representing the Southbound resource that will be used to assign a type to a device (e.g.: pathname in the southbound port). | +| `apikey` | `apikey` | API Key string. | +| `timestamp` | `timestamp` | Optional flagw whether to include the `TimeInstant`within each entity created, as well as a `TimeInstant` metadata to each attribute, with the current timestamp | +| `entity_type` | `entity_type` | name of the Entity `type` to assign to the group. | +| `trust` | `trust` | trust token to use for secured access to the Context Broker for this type of devices (optional; only needed for secured scenarios). | +| `cbHost` | `cbHost` | Context Broker connection information. This options can be used to override the global ones for specific types of devices. | +| `lazy` | `lazy` | list of common lazy attributes of the device. For each attribute, its `name` and `type` must be provided. | +| `commands` | `commands` | list of common commands attributes of the device. For each attribute, its `name` and `type` must be provided, additional `metadata` is optional. | +| `attributes` | `attributes` | list of common active attributes of the device. For each attribute, its `name` and `type` must be provided, additional `metadata` is optional. | +| `static_attributes` | `staticAttributes` | this attributes will be added to all the entities of this group 'as is', additional `metadata` is optional. | +| `internal_attributes` | `internalAttributes` | optional section with free format, to allow specific IoT Agents to store information along with the devices in the Device Registry. | +| `expressionLanguage` | `expresionLanguage` | optional boolean value, to set expression language used to compute expressions, possible values are: legacy or jexl. When not set or wrongly set, legacy is used as default value. | +| `explicitAttrs` | `explicitAttrs` | optional boolean value, to support selective ignore of measures so that IOTA doesn’t progress. If not specified default is false. | ### Service Group Endpoint @@ -205,27 +205,27 @@ Note that there is a 1:1 correspondence between payload fields and DB fields (bu The table below shows the information held in the Device resource. The table also contains the correspondence between the API resource fields and the same fields in the database model. -| Payload Field | DB Field | Definition | Example of value | -| ------------------------- | -------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------- | -| `device_id` | `id` | Device ID that will be used to identify the device. | UO834IO | -| `service` | `service` | Name of the service the device belongs to (will be used in the fiware-service header). | smartGondor | -| `service_path` | `subservice` | Name of the subservice the device belongs to (used in the fiware-servicepath header). | /gardens | -| `entity_name` | `name` | Name of the entity representing the device in the Context Broker | ParkLamplight12 | -| `entity_type` | `type` | Type of the entity in the Context Broker | Lamplights | -| `timezone` | `timezone` | Time zone of the sensor if it has any | America/Santiago | -| `timestamp` | `timestamp` | Optional flag about whether or not to addthe TimeInstant attribute to the device entity created, as well as a TimeInstant metadata to each attribute, with the current timestamp | true | -| `apikey` | `apikey` | Optional Apikey key string to use instead of group apikey -| 9n4hb1vpwbjozzmw9f0flf9c2 | -| `endpoint` | `endpoint` | Endpoint where the device is going to receive commands, if any. | http://theDeviceUrl:1234/commands | -| `protocol` | `protocol` | Name of the device protocol, for its use with an IoT Manager. | IoTA-UL | -| `transport` | `transport` | Name of the device transport protocol, for the IoT Agents with multiple transport protocols. | MQTT | -| `attributes` | `active` | List of active attributes of the device | `[ { "name": "attr_name", "type": "Text" } ]` | -| `lazy` | `lazy` | List of lazy attributes of the device | `[ { "name": "attr_name", "type": "Text" } ]` | -| `commands` | `commands` | List of commands of the device | `[ { "name": "attr_name", "type": "Text" } ]` | -| `internal_attributes` | `internalAttributes` | List of internal attributes with free format for specific IoT Agent configuration | LWM2M mappings from object URIs to attributes | -| `static_attributes` | `staticAttributes` | List of static attributes to append to the entity. All the updateContext requests to the CB will have this set of attributes appended. | `[ { "name": "attr_name", "type": "Text" } ]` | -| `expressionLanguage` | `expresionLanguage` | optional boolean value, to set expression language used to compute expressions, possible values are: legacy or jexl. When not set or wrongly set, legacy is used as default value. -| `explicitAttrs` | `explicitAttrs` | Boolean value to support selective ignore of measures for device so that IOTA doesn’t progress. If not specified default is false. | `true/false` | +| Payload Field | DB Field | Definition | Example of value | +| ------------------------- | -------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------- | +| `device_id` | `id` | Device ID that will be used to identify the device. | UO834IO | +| `service` | `service` | Name of the service the device belongs to (will be used in the fiware-service header). | smartGondor | +| `service_path` | `subservice` | Name of the subservice the device belongs to (used in the fiware-servicepath header). | /gardens | +| `entity_name` | `name` | Name of the entity representing the device in the Context Broker | ParkLamplight12 | +| `entity_type` | `type` | Type of the entity in the Context Broker | Lamplights | +| `timezone` | `timezone` | Time zone of the sensor if it has any | America/Santiago | +| `timestamp` | `timestamp` | Optional flag about whether or not to addthe TimeInstant attribute to the device entity created, as well as a TimeInstant metadata to each attribute, with the current timestamp | true | +| `apikey` | `apikey` | Optional Apikey key string to use instead of group apikey | +| 9n4hb1vpwbjozzmw9f0flf9c2 | +| `endpoint` | `endpoint` | Endpoint where the device is going to receive commands, if any. | http://theDeviceUrl:1234/commands | +| `protocol` | `protocol` | Name of the device protocol, for its use with an IoT Manager. | IoTA-UL | +| `transport` | `transport` | Name of the device transport protocol, for the IoT Agents with multiple transport protocols. | MQTT | +| `attributes` | `active` | List of active attributes of the device | `[ { "name": "attr_name", "type": "Text" } ]` | +| `lazy` | `lazy` | List of lazy attributes of the device | `[ { "name": "attr_name", "type": "Text" } ]` | +| `commands` | `commands` | List of commands of the device | `[ { "name": "attr_name", "type": "Text" } ]` | +| `internal_attributes` | `internalAttributes` | List of internal attributes with free format for specific IoT Agent configuration | LWM2M mappings from object URIs to attributes | +| `static_attributes` | `staticAttributes` | List of static attributes to append to the entity. All the updateContext requests to the CB will have this set of attributes appended. | `[ { "name": "attr_name", "type": "Text" } ]` | +| `expressionLanguage` | `expresionLanguage` | optional boolean value, to set expression language used to compute expressions, possible values are: legacy or jexl. When not set or wrongly set, legacy is used as default value. | +| `explicitAttrs` | `explicitAttrs` | Boolean value to support selective ignore of measures for device so that IOTA doesn’t progress. If not specified default is false. | `true/false` | #### Attribute lists diff --git a/doc/architecture.md b/doc/architecture.md index db94266da..b975d153d 100644 --- a/doc/architecture.md +++ b/doc/architecture.md @@ -32,7 +32,7 @@ basis preprovisioning the devices). Device measures can have three different beh The following sequence diagram shows the different NGSI interactions an IoT Agent makes with the Context Broker, explained in the following subsections (using the example of a OMA Lightweight M2M device). -![General ](./img/ngsiInteractions.png 'NGSI Interactions') +![General ](./img/ngsiInteractions.png "NGSI Interactions") Be aware that the IoT Agents are only required to support NGSI10 operations `updateContext` and `queryContext` in their standard formats (currently in JSON format; XML deprecated) but will not answer to NGSI9 operations (or NGSI convenience @@ -207,7 +207,7 @@ the concrete IoT Agent implementations will be to map between the native device The following figure offers a graphical example of how a COAP IoT Agent work, ordered from the registration of the device to a command update to the device. -![General ](./img/iotAgentLib.png 'Architecture Overview') +![General ](./img/iotAgentLib.png "Architecture Overview") ### The `TimeInstant` element diff --git a/doc/development.md b/doc/development.md index b1db075c1..0afb3f6c2 100644 --- a/doc/development.md +++ b/doc/development.md @@ -41,9 +41,9 @@ npm test ### Coding guidelines -jshint +ESLint -Uses provided .jshintrc flag file. To check source code style, type +Uses the provided `.eslintrc.json` flag file. To check source code style, type ```bash npm run lint @@ -97,9 +97,36 @@ npm run lint:md ### Documentation Spell-checking -Checks the markdown documentation for spelling and grammar errors, dead links & etc. +Uses the provided `.textlintrc` flag file. To check the markdown documentation for spelling and grammar errors, dead links & etc. ```bash # Use git-bash on Windows npm run lint:text ``` + +### Clean + +Removes `node_modules` and `coverage` folders, and `package-lock.json` file so that a fresh copy of the project is +restored. + +```bash +# Use git-bash on Windows +npm run clean +``` + +### Prettify Code + +Runs the [prettier](https://prettier.io) code formatter to ensure consistent code style (whitespacing, parameter +placement and breakup of long lines etc.) within the codebase. + +```bash +# Use git-bash on Windows +npm run prettier +``` + +To ensure consistent Markdown formatting run the following: + +```bash +# Use git-bash on Windows +npm run prettier:text +``` diff --git a/doc/echo.js b/doc/echo.js index 5bafbc043..5d00742ac 100644 --- a/doc/echo.js +++ b/doc/echo.js @@ -22,7 +22,7 @@ function initEcho(callback) { echoServer.server.listen(echoServer.app.get('port'), echoServer.app.get('host'), callback); } -initEcho(function(error) { +initEcho(function (error) { if (error) { console.log('Could not initialize echo server: %s', error); } else { diff --git a/doc/expressionLanguage.md b/doc/expressionLanguage.md index 01ffe940c..9d0665f46 100644 --- a/doc/expressionLanguage.md +++ b/doc/expressionLanguage.md @@ -16,8 +16,8 @@ The IoTAgent Library provides an expression language for measurement transformation, that can be used to adapt the information coming from the South Bound APIs to the information reported to the Context Broker. Expressions in this -language can be configured for provisioned attributes as explained in the Device Provisioning API section in the -main README.md. +language can be configured for provisioned attributes as explained in the Device Provisioning API section in the main +README.md. ## Measurement transformation @@ -69,10 +69,10 @@ Expression Language (see definition [below](#language-description)). In order fo evaluated, all the expression patterns must be evaluatable (there must be a value in the measurement for all the variables of all the expression patterns). -Note that you need to include in the provision operation all the attributes required as inputs for the expressions. -In this example, they are `level`, `latitude` and `longitude`. Otherwise the device sending the measures will get -`{"name":"ATTRIBUTE_NOT_FOUND","message":"Some of the attributes does not exist"}` when it sends some of these -and the expression will not be calculated. +Note that you need to include in the provision operation all the attributes required as inputs for the expressions. In +this example, they are `level`, `latitude` and `longitude`. Otherwise the device sending the measures will get +`{"name":"ATTRIBUTE_NOT_FOUND","message":"Some of the attributes does not exist"}` when it sends some of these and the +expression will not be calculated. The exact same syntax works for Configuration and Device provisioning. @@ -316,11 +316,10 @@ two possible types of expressions: Integer (arithmetic operations) or Strings. ## JEXL Based Transformations -As an alternative, the IoTAgent Library supports as well [JEXL](https://github.com/TomFrost/jexl). -To use JEXL, you will need to either configure it as default -language using the `defaultExpressionLanguage` field to `jexl` -(see [configuration documentation](installationguide.md)) or configuring -the usage of JEXL as expression language for a given device: +As an alternative, the IoTAgent Library supports as well [JEXL](https://github.com/TomFrost/jexl). To use JEXL, you will +need to either configure it as default language using the `defaultExpressionLanguage` field to `jexl` (see +[configuration documentation](installationguide.md)) or configuring the usage of JEXL as expression language for a given +device: ``` { @@ -352,31 +351,27 @@ In the following we provide examples of using JEXL to apply transformations. ### Quick comparison to default language -* JEXL supports the following types: Boolean, String, Number, Object, Array. -* JEXL allows to navigate and [filter](https://github.com/TomFrost/jexl#collections) objects and arrays. -* JEXL supports if..then...else... via [ternary operator](https://github.com/TomFrost/jexl#ternary-operator). -* JEXL additionally supports the following operations: - Divide and floor `//`, Modulus `%`, Logical AND `&&` and - Logical OR `||`. Negation operator is `!` -* JEXL supports [comparisons](https://github.com/TomFrost/jexl#comparisons). +- JEXL supports the following types: Boolean, String, Number, Object, Array. +- JEXL allows to navigate and [filter](https://github.com/TomFrost/jexl#collections) objects and arrays. +- JEXL supports if..then...else... via [ternary operator](https://github.com/TomFrost/jexl#ternary-operator). +- JEXL additionally supports the following operations: Divide and floor `//`, Modulus `%`, Logical AND `&&` and + Logical OR `||`. Negation operator is `!` +- JEXL supports [comparisons](https://github.com/TomFrost/jexl#comparisons). - -For more details, check JEXL language details -[here](https://github.com/TomFrost/jexl#all-the-details). +For more details, check JEXL language details [here](https://github.com/TomFrost/jexl#all-the-details). ### Examples of expressions -The following table shows expressions and their expected outcomes taking into -account the following measures at southbound interface: - -* `value` with value 6 (number) -* `name` with value `"DevId629"` (string) -* `object` with value `{name: "John", surname: "Doe"}` (JSON object) -* `array` with value `[1, 3]` (JSON Array) +The following table shows expressions and their expected outcomes taking into account the following measures at +southbound interface: +- `value` with value 6 (number) +- `name` with value `"DevId629"` (string) +- `object` with value `{name: "John", surname: "Doe"}` (JSON object) +- `array` with value `[1, 3]` (JSON Array) | Expression | Expected outcome | -|:--------------------------- |:----------------------- | +| :-------------------------- | :---------------------- | | `5 * value` | `30` | | `(6 + value) * 3` | `36` | | `value / 12 + 1` | `1.5` | @@ -387,20 +382,19 @@ account the following measures at southbound interface: Support for `trim`, `length`, `substr` and `indexOf` transformations was added. -| Expression | Expected outcome | -|:--------------------------- |:----------------------- | -| " a "|trim | `a` | -| name|length | `8` | -| name|indexOf("e")| `1` | -| name|substring(0,name|indexOf("e")+1)| `"De"` | - -The following are some expressions not supported by the legacy expression -language: - -| Expression | Expected outcome | -|:----------------------------------- |:----------------------- | -| `value == 6? true : false` | `true` | -| value == 6 && name|indexOf("e")>0 | `true` | -| `array[1]+1` | `3` | -| `object.name` | `"John"` | -| `{type:"Point",coordinates: [value,value]}`| `{type:"Point",coordinates: [6,6]}` | +| Expression | Expected outcome | +| :----------------------------------------------------------- | :--------------- | +| " a "|trim | `a` | +| name|length | `8` | +| name|indexOf("e") | `1` | +| name|substring(0,name|indexOf("e")+1) | `"De"` | + +The following are some expressions not supported by the legacy expression language: + +| Expression | Expected outcome | +| :-------------------------------------------------- | :---------------------------------- | +| `value == 6? true : false` | `true` | +| value == 6 && name|indexOf("e")>0 | `true` | +| `array[1]+1` | `3` | +| `object.name` | `"John"` | +| `{type:"Point",coordinates: [value,value]}` | `{type:"Point",coordinates: [6,6]}` | diff --git a/doc/finalResult.js b/doc/finalResult.js index 4256d8384..592d68f30 100644 --- a/doc/finalResult.js +++ b/doc/finalResult.js @@ -32,14 +32,14 @@ function parseUl(data, device) { function manageULRequest(req, res, next) { var values; - iotAgentLib.getDevice(req.query.i, function(error, device) { + iotAgentLib.getDevice(req.query.i, function (error, device) { if (error) { res.status(404).send({ message: "Couldn't find the device: " + JSON.stringify(error) }); } else { values = parseUl(req.query.d, device); - iotAgentLib.update(device.name, device.type, '', values, device, function(error) { + iotAgentLib.update(device.name, device.type, '', values, device, function (error) { if (error) { res.status(500).send({ message: 'Error updating the device' @@ -99,7 +99,7 @@ function queryContextHandler(id, type, attributes, callback) { } }; - request(options, function(error, response, body) { + request(options, function (error, response, body) { if (error) { callback(error); } else { @@ -131,7 +131,7 @@ function updateContextHandler(id, type, attributes, callback) { } }; - request(options, function(error, response, body) { + request(options, function (error, response, body) { if (error) { callback(error); } else { @@ -157,7 +157,7 @@ function configurationHandler(configuration, callback) { callback(null, configuration); } -iotAgentLib.activate(config, function(error) { +iotAgentLib.activate(config, function (error) { if (error) { console.log('There was an error activating the IOTA'); process.exit(1); @@ -167,7 +167,7 @@ iotAgentLib.activate(config, function(error) { iotAgentLib.setConfigurationHandler(configurationHandler); iotAgentLib.setProvisioningHandler(provisioningHandler); - initSouthbound(function(error) { + initSouthbound(function (error) { if (error) { console.log('Could not initialize South bound API due to the following error: %s', error); } else { diff --git a/doc/getting-started.md b/doc/getting-started.md index c594d907f..236858216 100644 --- a/doc/getting-started.md +++ b/doc/getting-started.md @@ -10,23 +10,23 @@ custom settings may also be required dependent upon the actual IoT Agent used. ```javascript config = { - logLevel: 'DEBUG', + logLevel: "DEBUG", contextBroker: { - host: 'orion', - port: '1026' + host: "orion", + port: "1026", }, server: { port: 4041, - host: '0.0.0.0' + host: "0.0.0.0", }, deviceRegistry: { - type: 'memory' + type: "memory", }, - service: 'openiot', - subservice: '/', - providerUrl: 'http://iot-agent:4041', - deviceRegistrationDuration: 'P1M', - defaultType: 'Thing' + service: "openiot", + subservice: "/", + providerUrl: "http://iot-agent:4041", + deviceRegistrationDuration: "P1M", + defaultType: "Thing", }; ``` diff --git a/doc/howto.md b/doc/howto.md index ff7520146..28fdd82ec 100644 --- a/doc/howto.md +++ b/doc/howto.md @@ -75,12 +75,12 @@ folder of your project. Remember to change the Context Broker IP to your local C Now we can begin with the code of our IoT Agent. The very minimum code we need to start an IoT Agent is the following: ```javascript -var iotAgentLib = require('iotagent-node-lib'), - config = require('./config'); +var iotAgentLib = require("iotagent-node-lib"), + config = require("./config"); -iotAgentLib.activate(config, function(error) { +iotAgentLib.activate(config, function (error) { if (error) { - console.log('There was an error activating the IOTA'); + console.log("There was an error activating the IOTA"); process.exit(1); } }); @@ -112,10 +112,10 @@ In order to add the Express dependency to your project, add the following line t The require section would end up like this (the standard `http` module is also needed): ```javascript -var iotAgentLib = require('iotagent-node-lib'), - http = require('http'), - express = require('express'), - config = require('./config'); +var iotAgentLib = require("iotagent-node-lib"), + http = require("http"), + express = require("express"), + config = require("./config"); ``` And install the dependencies as usual with `npm install`. You will have to require both `express` and `http` in your @@ -129,16 +129,16 @@ function initSouthbound(callback) { southboundServer = { server: null, app: express(), - router: express.Router() + router: express.Router(), }; - southboundServer.app.set('port', 8080); - southboundServer.app.set('host', '0.0.0.0'); + southboundServer.app.set("port", 8080); + southboundServer.app.set("host", "0.0.0.0"); - southboundServer.router.get('/iot/d', manageULRequest); + southboundServer.router.get("/iot/d", manageULRequest); southboundServer.server = http.createServer(southboundServer.app); - southboundServer.app.use('/', southboundServer.router); - southboundServer.server.listen(southboundServer.app.get('port'), southboundServer.app.get('host'), callback); + southboundServer.app.use("/", southboundServer.router); + southboundServer.server.listen(southboundServer.app.get("port"), southboundServer.app.get("host"), callback); } ``` @@ -151,21 +151,21 @@ would be as follows: function manageULRequest(req, res, next) { var values; - iotAgentLib.retrieveDevice(req.query.i, req.query.k, function(error, device) { + iotAgentLib.retrieveDevice(req.query.i, req.query.k, function (error, device) { if (error) { res.status(404).send({ - message: "Couldn't find the device: " + JSON.stringify(error) + message: "Couldn't find the device: " + JSON.stringify(error), }); } else { values = parseUl(req.query.d, device); - iotAgentLib.update(device.name, device.type, '', values, device, function(error) { + iotAgentLib.update(device.name, device.type, "", values, device, function (error) { if (error) { res.status(500).send({ - message: 'Error updating the device' + message: "Error updating the device", }); } else { res.status(200).send({ - message: 'Device successfully updated' + message: "Device successfully updated", }); } }); @@ -190,17 +190,17 @@ function parseUl(data, device) { } function createAttribute(element) { - var pair = element.split('|'), + var pair = element.split("|"), attribute = { name: pair[0], value: pair[1], - type: findType(pair[0]) + type: findType(pair[0]), }; return attribute; } - return data.split(',').map(createAttribute); + return data.split(",").map(createAttribute); } ``` @@ -225,16 +225,16 @@ The last thing to do is to invoke the initialization function inside the IoT Age show the modifications in the `activate()` function: ```javascript -iotAgentLib.activate(config, function(error) { +iotAgentLib.activate(config, function (error) { if (error) { - console.log('There was an error activating the IOTA'); + console.log("There was an error activating the IOTA"); process.exit(1); } else { - initSouthbound(function(error) { + initSouthbound(function (error) { if (error) { - console.log('Could not initialize South bound API due to the following error: %s', error); + console.log("Could not initialize South bound API due to the following error: %s", error); } else { - console.log('Both APIs started successfully'); + console.log("Both APIs started successfully"); } }); } @@ -286,7 +286,7 @@ A HTTP request library will be needed in order to make those calls. To this exte used. In order to do so, add the following require statement to the initialization code: ```javascript -request = require('request'); +request = require("request"); ``` and add the `request` dependency to the `package.json` file: @@ -303,11 +303,11 @@ and add the `request` dependency to the `package.json` file: The require section should now look like this: ```javascript -var iotAgentLib = require('iotagent-node-lib'), - http = require('http'), - express = require('express'), - request = require('request'), - config = require('./config'); +var iotAgentLib = require("iotagent-node-lib"), + http = require("http"), + express = require("express"), + request = require("request"), + config = require("./config"); ``` ### Implementation @@ -321,14 +321,14 @@ for the context provisioning requests. At this point, we should provide two hand ```javascript function queryContextHandler(id, type, service, subservice, attributes, callback) { var options = { - url: 'http://127.0.0.1:9999/iot/d', - method: 'GET', + url: "http://127.0.0.1:9999/iot/d", + method: "GET", qs: { - q: attributes.join() - } + q: attributes.join(), + }, }; - request(options, function(error, response, body) { + request(options, function (error, response, body) { if (error) { callback(error); } else { @@ -350,21 +350,21 @@ attributes). Here is the code for the `createResponse()` function: ```javascript function createResponse(id, type, attributes, body) { - var values = body.split(','), + var values = body.split(","), responses = []; for (var i = 0; i < attributes.length; i++) { responses.push({ name: attributes[i], - type: 'string', - value: values[i] + type: "string", + value: values[i], }); } return { id: id, type: type, - attributes: responses + attributes: responses, }; } ``` @@ -374,21 +374,21 @@ function createResponse(id, type, attributes, body) { ```javascript function updateContextHandler(id, type, service, subservice, attributes, callback) { var options = { - url: 'http://127.0.0.1:9999/iot/d', - method: 'GET', + url: "http://127.0.0.1:9999/iot/d", + method: "GET", qs: { - d: createQueryFromAttributes(attributes) - } + d: createQueryFromAttributes(attributes), + }, }; - request(options, function(error, response, body) { + request(options, function (error, response, body) { if (error) { callback(error); } else { callback(null, { id: id, type: type, - attributes: attributes + attributes: attributes, }); } }); @@ -406,13 +406,13 @@ representation of the attributes to the UL type expected by the device: ```javascript function createQueryFromAttributes(attributes) { - var query = ''; + var query = ""; for (var i in attributes) { - query += attributes[i].name + '|' + attributes[i].value; + query += attributes[i].name + "|" + attributes[i].value; if (i != attributes.length - 1) { - query += ','; + query += ","; } } @@ -559,9 +559,9 @@ variable and afterward the value of the multiCore in the `config.js` file. The r (the standard `http` module is also needed): ```javascript -var iotAgent = require('../lib/iotagent-implementation'), - iotAgentLib = require('iotagent-node-lib'), - config = require('./config'); +var iotAgent = require("../lib/iotagent-implementation"), + iotAgentLib = require("iotagent-node-lib"), + config = require("./config"); ``` It is important to mention the purpose of the `iotAgent` variable. It is the proper implementation of the IoT Agent @@ -575,11 +575,11 @@ following code with a callback function to show details about any error during t about starting the IoTAgent: ```javascript -iotAgentLib.startServer(config, iotAgent, function(error) { +iotAgentLib.startServer(config, iotAgent, function (error) { if (error) { - console.log(context, 'Error starting IoT Agent: [%s] Exiting process', error); + console.log(context, "Error starting IoT Agent: [%s] Exiting process", error); } else { - console.log(context, 'IoT Agent started'); + console.log(context, "IoT Agent started"); } }); ``` @@ -606,7 +606,7 @@ handlers themselves. Here we can see the definition of the configuration handler ```javascript function configurationHandler(configuration, callback) { - console.log('\n\n* REGISTERING A NEW CONFIGURATION:\n%s\n\n', JSON.stringify(configuration, null, 4)); + console.log("\n\n* REGISTERING A NEW CONFIGURATION:\n%s\n\n", JSON.stringify(configuration, null, 4)); callback(null, configuration); } ``` @@ -623,8 +623,8 @@ feature, let's use the provisioning handler to change the value of the type of t ```javascript function provisioningHandler(device, callback) { - console.log('\n\n* REGISTERING A NEW DEVICE:\n%s\n\n', JSON.stringify(device, null, 4)); - device.type = 'CertifiedType'; + console.log("\n\n* REGISTERING A NEW DEVICE:\n%s\n\n", JSON.stringify(device, null, 4)); + device.type = "CertifiedType"; callback(null, device); } ``` diff --git a/doc/index.md b/doc/index.md index e9da09ac5..f32f7a6c1 100644 --- a/doc/index.md +++ b/doc/index.md @@ -51,5 +51,5 @@ IoT Agent In order to use the library within your own IoT Agent, you must first you require it before use: ```javascript -const iotagentLib = require('iotagent-node-lib'); +const iotagentLib = require("iotagent-node-lib"); ``` diff --git a/doc/northboundinteractions.md b/doc/northboundinteractions.md index 0817bf525..f0d9d6e20 100644 --- a/doc/northboundinteractions.md +++ b/doc/northboundinteractions.md @@ -261,7 +261,7 @@ Context Element, but with the request as a whole. ### Scenario 1: active attributes -![General ](./img/scenario1.png 'Scenario 1: active attributes') +![General ](./img/scenario1.png "Scenario 1: active attributes") In this scenario, the interaction is started by the device, that is going to actively send a piece of data to the platform. When the IoTAgent receives the data, it sends it to the Context Broker through a P1 request. The Context @@ -275,7 +275,7 @@ updating process, and can occur at any time (they are to completely different pr ### Scenario 2: lazy attributes -![General ](./img/scenario2.png 'Scenario 2: lazy attributes') +![General ](./img/scenario2.png "Scenario 2: lazy attributes") This scenario requires that the attributes that are going to be requested are marked as provided by the IoT Agent, through a registration process (NGSIv9). Examples of this registration process will be provided in the practical section @@ -301,7 +301,7 @@ queries (and thus P2 and R2 payloads). ### Scenario 3: commands -![General ](./img/scenario3.png 'Scenario 3: commands') +![General ](./img/scenario3.png "Scenario 3: commands") This scenario requires that the attributes that are going to be requested are marked as provided by the IoT Agent, through a registration process (NGSIv9). Examples of this registration process will be provided in the practical section diff --git a/doc/usermanual.md b/doc/usermanual.md index 7381a58f1..2c59d6a54 100644 --- a/doc/usermanual.md +++ b/doc/usermanual.md @@ -25,7 +25,7 @@ More values will be added in the future to the library. The applications using t Registry just by using the following function: ```javascript -iotagentLib.statsRegistry.add('statName', statIncrementalValue, callback); +iotagentLib.statsRegistry.add("statName", statIncrementalValue, callback); ``` The first time this function is invoked, it will add the new stat to the registry. Subsequent calls will add the value @@ -80,7 +80,7 @@ In order to use the library, add the following dependency to your package.json f In order to use this library, first you must require it: ```javascript -var iotagentLib = require('iotagent-node-lib'); +var iotagentLib = require("iotagent-node-lib"); ``` The library supports four groups of features, one for each direction of the communication: client-to-server and @@ -265,16 +265,16 @@ Once all the updates have taken place, the callback must be invoked with the upd ```javascript callback(null, { - type: 'TheType', + type: "TheType", isPattern: false, - id: 'EntityID', + id: "EntityID", attributes: [ { - name: 'lumniscence', - type: 'Lumens', - value: '432' - } - ] + name: "lumniscence", + type: "Lumens", + value: "432", + }, + ], }); ``` @@ -303,16 +303,16 @@ The callback must be invoked with the updated Context Element, using the informa ```javascript callback(null, { - type: 'TheType', + type: "TheType", isPattern: false, - id: 'EntityID', + id: "EntityID", attributes: [ { - name: 'lumniscence', - type: 'Lumens', - value: '432' - } - ] + name: "lumniscence", + type: "Lumens", + value: "432", + }, + ], }); ``` diff --git a/docs/roadmap.md b/docs/roadmap.md index fa7fd7b65..409e3b3a0 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,41 +1,50 @@ -# IoT Agent Node.js Library +# IoT Agent Node.js Library -This product is a FIWARE Generic Enabler. If you would like to learn about the overall Roadmap of FIWARE, please check "Roadmap" on the [FIWARE Catalogue](https://www.fiware.org/developers/catalogue/). +This product is a FIWARE Generic Enabler. If you would like to learn about the overall Roadmap of FIWARE, please check +"Roadmap" on the [FIWARE Catalogue](https://www.fiware.org/developers/catalogue/). ### Introduction -This section elaborates on proposed new features or tasks which are expected to be added to the product in the foreseeable future. There should be no assumption of a commitment to deliver these features on specific dates or in the order given. The development team will be doing their best to follow the proposed dates and priorities, but please bear in mind that plans to work on a given feature or task may be revised. All information is provided as general guidelines only, and this section may be revised to provide newer information at any time. +This section elaborates on proposed new features or tasks which are expected to be added to the product in the +foreseeable future. There should be no assumption of a commitment to deliver these features on specific dates or in the +order given. The development team will be doing their best to follow the proposed dates and priorities, but please bear +in mind that plans to work on a given feature or task may be revised. All information is provided as general guidelines +only, and this section may be revised to provide newer information at any time. Disclaimer: -* This section has been last updated in March 2020. Please take into account its - content could be obsolete. -* Note we develop this software in Agile way, so development plan is continuously - under review. Thus, this roadmap has to be understood as rough plan of features - to be done along time which is fully valid only at the time of writing it. This - roadmap has not be understood as a commitment on features and/or dates. -* Some of the roadmap items may be implemented by external community developers, - out of the scope of GE owners. Thus, the moment in which these features will be - finalized cannot be assured. - +- This section has been last updated in March 2020. Please take into account its content could be obsolete. +- Note we develop this software in Agile way, so development plan is continuously under review. Thus, this roadmap has + to be understood as rough plan of features to be done along time which is fully valid only at the time of writing + it. This roadmap has not be understood as a commitment on features and/or dates. +- Some of the roadmap items may be implemented by external community developers, out of the scope of GE owners. Thus, + the moment in which these features will be finalized cannot be assured. + ### Short term -The following list of features are planned to be addressed in the short term, and incorporated in a release of the product: +The following list of features are planned to be addressed in the short term, and incorporated in a release of the +product: -- Selectively ignore measure in the southbound interface (community) -- JEXL support in expressions (community) -- cgroup literal in configuration groups management API (community) -- Metadata processing improvements -- Add MongoDB authentication support +- Selectively ignore measure in the southbound interface (community) +- JEXL support in expressions (community) +- cgroup literal in configuration groups management API (community) +- Metadata processing improvements +- Add MongoDB authentication support ### Medium term -The following list of features are planned to be addressed in the medium term, typically within the subsequent release(s) generated in the next 9 months after the next planned release: -- Support for "delta" measures (i.e. "temperature *increased* in 5 degress" instead of "temperature *is* 25") -- Removal support for NGSIv1 (which currently is deprecated) +The following list of features are planned to be addressed in the medium term, typically within the subsequent +release(s) generated in the next 9 months after the next planned release: + +- Support for "delta" measures (i.e. "temperature _increased_ in 5 degress" instead of "temperature _is_ 25") +- Removal support for NGSIv1 (which currently is deprecated) ### Long term -The following list of features are proposals regarding the longer-term evolution of the product even though the development of these features has not yet been scheduled for a release in the near future. Please feel free to contact us if you wish to get involved in the implementation or influence the roadmap: -- Incremental introduccion of ECMAScript6 syntax (previous analysis of which sub-set of interesting aspect we want to take) -- Use the lightweight ingestion mechanism for connection oriented updates implemented in Context Broker +The following list of features are proposals regarding the longer-term evolution of the product even though the +development of these features has not yet been scheduled for a release in the near future. Please feel free to contact +us if you wish to get involved in the implementation or influence the roadmap: + +- Incremental introduccion of ECMAScript6 syntax (previous analysis of which sub-set of interesting aspect we want to + take) +- Use the lightweight ingestion mechanism for connection oriented updates implemented in Context Broker diff --git a/ghpages/javascripts/scale.fix.js b/ghpages/javascripts/scale.fix.js index 87a40ca71..39cdc7663 100644 --- a/ghpages/javascripts/scale.fix.js +++ b/ghpages/javascripts/scale.fix.js @@ -1,17 +1,17 @@ var metas = document.getElementsByTagName('meta'); var i; if (navigator.userAgent.match(/iPhone/i)) { - for (i=0; i 0) { - db.db().collection(collection).insertMany(docs, function(error, inserts) { - innerCb(error); - }); + db.db() + .collection(collection) + /* eslint-disable-next-line no-unused-vars */ + .insertMany(docs, function (error, inserts) { + innerCb(error); + }); } else { innerCb(); } @@ -120,7 +121,7 @@ function migrate(dbConfig, originDb, targetDb, service, subservice, callback) { } function getCollection(db, name, service, subservice, innerCb) { - var query = {}; + const query = {}; if (service) { query.service = service; @@ -134,38 +135,42 @@ function migrate(dbConfig, originDb, targetDb, service, subservice, callback) { } function closeDb(db, innerCb) { - db.close(function(error) { + /* eslint-disable-next-line no-unused-vars */ + db.close(function (error) { innerCb(); }); } function startMigration(dbResults, innerCb) { - var originDb = dbResults[0], - targetDb = dbResults[1]; - - async.waterfall([ - apply(getCollection, originDb, 'SERVICE', service, subservice), - generateCollectionTranslator(serviceTranslation), - apply(saveToTargetDb, targetDb, 'groups'), - apply(getCollection, originDb, 'DEVICE', service, subservice), - generateCollectionTranslator(deviceTranslation), - applyDefaultName, - applyProtocolTranslations, - apply(saveToTargetDb, targetDb, 'devices'), - apply(closeDb, originDb), - apply(closeDb, targetDb) - ], function(error) { - innerCb(error); - }); + const originDb = dbResults[0]; + const targetDb = dbResults[1]; + + async.waterfall( + [ + apply(getCollection, originDb, 'SERVICE', service, subservice), + generateCollectionTranslator(serviceTranslation), + apply(saveToTargetDb, targetDb, 'groups'), + apply(getCollection, originDb, 'DEVICE', service, subservice), + generateCollectionTranslator(deviceTranslation), + applyDefaultName, + applyProtocolTranslations, + apply(saveToTargetDb, targetDb, 'devices'), + apply(closeDb, originDb), + apply(closeDb, targetDb) + ], + function (error) { + innerCb(error); + } + ); } - async.waterfall([ - apply(async.series, [ - apply(connectToDb, dbConfig, originDb), - apply(connectToDb, dbConfig, targetDb) - ]), - startMigration - ], callback); + async.waterfall( + [ + apply(async.series, [apply(connectToDb, dbConfig, originDb), apply(connectToDb, dbConfig, targetDb)]), + startMigration + ], + callback + ); } exports.migrate = migrate; diff --git a/lib/commonConfig.js b/lib/commonConfig.js index f64a9f46a..18a5eeb58 100644 --- a/lib/commonConfig.js +++ b/lib/commonConfig.js @@ -25,37 +25,34 @@ * Modified by: Fernando López - FIWARE Foundation */ -'use strict'; - -var config = {}, - logger = require('logops'), - registry, - groupRegistry, - commandRegistry, - securityService; - -const fs = require('fs'); +let config = {}; +const logger = require('logops'); +let registry; +let groupRegistry; +let commandRegistry; +let securityService; + +const fs = require('fs'); const path = require('path'); -const SECRETS_DIR = process.env.SECRETS_DIR || '/run/secrets'; +const SECRETS_DIR = process.env.SECRETS_DIR || '/run/secrets'; const secrets = {}; if (fs.existsSync(SECRETS_DIR)) { - const files = fs.readdirSync(SECRETS_DIR); - files.forEach(function(file, index) { - const fullPath = path.join(SECRETS_DIR, file); - const key = file; - try { - const data = fs.readFileSync(fullPath, 'utf8').toString().trim(); - secrets[key] = data; - } catch (e) { - logger.error(e.message); - } - }); + const files = fs.readdirSync(SECRETS_DIR); + files.forEach(function (file) { + const fullPath = path.join(SECRETS_DIR, file); + const key = file; + try { + const data = fs.readFileSync(fullPath, 'utf8').toString().trim(); + secrets[key] = data; + } catch (e) { + logger.error(e.message); + } + }); } - function anyIsSet(variableSet) { - for (var i = 0; i < variableSet.length; i++) { + for (let i = 0; i < variableSet.length; i++) { if (process.env[variableSet[i]]) { return true; } @@ -69,16 +66,15 @@ function anyIsSet(variableSet) { */ function getSecretData(key) { const filepath = process.env[key + '_FILE']; - if (!!filepath) { + if (filepath) { process.env[key] = secrets[path.parse(filepath).base] || process.env[key]; } } /* -* Inform the user if security is correctly enabled. -*/ + * Inform the user if security is correctly enabled. + */ function logAuthState() { - const stars = '***********************************************'; if (config.authentication === undefined) { logger.warn( @@ -89,19 +85,13 @@ function logAuthState() { stars ); } else { - const authKeystone = !!config.authentication.user && - !!config.authentication.password; - const authKeyrock = !!config.authentication.clientSecret && - !!config.authentication.clientId; - + const authKeystone = !!config.authentication.user && !!config.authentication.password; + const authKeyrock = !!config.authentication.clientSecret && !!config.authentication.clientId; + if (authKeystone) { - logger.info( - 'INFO: IoT Agent=>Keystone Auth credentials have been configured' - ); + logger.info('INFO: IoT Agent=>Keystone Auth credentials have been configured'); } else if (authKeyrock) { - logger.info( - 'INFO: IoT Agent=>Keyrock Auth credentials have been configured' - ); + logger.info('INFO: IoT Agent=>Keyrock Auth credentials have been configured'); } else { logger.warn( stars + @@ -118,84 +108,84 @@ function logAuthState() { * Looks for environment variables that could override configuration values. */ function processEnvironmentVariables() { - var environmentVariables = [ - 'IOTA_CB_URL', - 'IOTA_CB_HOST', - 'IOTA_CB_PORT', - 'IOTA_CB_NGSI_VERSION', - 'IOTA_NORTH_HOST', - 'IOTA_NORTH_PORT', - 'IOTA_PROVIDER_URL', - 'IOTA_AUTH_ENABLED', - 'IOTA_AUTH_TYPE', - 'IOTA_AUTH_HEADER', - 'IOTA_AUTH_URL', - 'IOTA_AUTH_HOST', - 'IOTA_AUTH_PORT', - 'IOTA_AUTH_USER', - 'IOTA_AUTH_PASSWORD', - 'IOTA_AUTH_CLIENT_ID', - 'IOTA_AUTH_CLIENT_SECRET', - 'IOTA_AUTH_TOKEN_PATH', - 'IOTA_AUTH_PERMANENT_TOKEN', - 'IOTA_REGISTRY_TYPE', - 'IOTA_LOG_LEVEL', - 'IOTA_TIMESTAMP', - 'IOTA_IOTAM_HOST', - 'IOTA_IOTAM_PORT', - 'IOTA_IOTAM_PATH', - 'IOTA_IOTAM_PROTOCOL', - 'IOTA_IOTAM_DESCRIPTION', - 'IOTA_DEFAULT_RESOURCE', - 'IOTA_EXPLICIT_ATTRS', - 'IOTA_MONGO_HOST', - 'IOTA_MONGO_PORT', - 'IOTA_MONGO_DB', - 'IOTA_MONGO_REPLICASET', - 'IOTA_AUTOCAST', - 'IOTA_MONGO_PASSWORD', - 'IOTA_MONGO_AUTH_SOURCE', - 'IOTA_MONGO_RETRIES', - 'IOTA_MONGO_USER', - 'IOTA_MONGO_RETRY_TIME', - 'IOTA_SINGLE_MODE', - 'IOTA_APPEND_MODE', - 'IOTA_POLLING_EXPIRATION', - 'IOTA_POLLING_DAEMON_FREQ', - 'IOTA_MULTI_CORE', - 'IOTA_DEFAULT_EXPRESSION_LANGUAGE', - 'IOTA_RELAX_TEMPLATE_VALIDATION' - ], - iotamVariables = [ - 'IOTA_IOTAM_URL', - 'IOTA_IOTAM_HOST', - 'IOTA_IOTAM_PORT', - 'IOTA_IOTAM_PATH', - 'IOTA_IOTAM_PROTOCOL', - 'IOTA_IOTAM_DESCRIPTION', - 'IOTA_IOTAM_AGENTPATH' - ], - mongoVariables = [ - 'IOTA_MONGO_HOST', - 'IOTA_MONGO_PORT', - 'IOTA_MONGO_DB', - 'IOTA_MONGO_REPLICASET', - 'IOTA_MONGO_USER', - 'IOTA_MONGO_PASSWORD', - 'IOTA_MONGO_AUTH_SOURCE', - 'IOTA_MONGO_RETRIES', - 'IOTA_MONGO_RETRY_TIME', - 'IOTA_MONGO_SSL', - 'IOTA_MONGO_EXTRAARGS' - ], - protectedVariables = [ - 'IOTA_AUTH_USER', - 'IOTA_AUTH_PASSWORD', - 'IOTA_AUTH_CLIENT_ID', - 'IOTA_AUTH_CLIENT_SECRET', - 'IOTA_MONGO_USER', - 'IOTA_MONGO_PASSWORD' - ]; + const environmentVariables = [ + 'IOTA_CB_URL', + 'IOTA_CB_HOST', + 'IOTA_CB_PORT', + 'IOTA_CB_NGSI_VERSION', + 'IOTA_NORTH_HOST', + 'IOTA_NORTH_PORT', + 'IOTA_PROVIDER_URL', + 'IOTA_AUTH_ENABLED', + 'IOTA_AUTH_TYPE', + 'IOTA_AUTH_HEADER', + 'IOTA_AUTH_URL', + 'IOTA_AUTH_HOST', + 'IOTA_AUTH_PORT', + 'IOTA_AUTH_USER', + 'IOTA_AUTH_PASSWORD', + 'IOTA_AUTH_CLIENT_ID', + 'IOTA_AUTH_CLIENT_SECRET', + 'IOTA_AUTH_TOKEN_PATH', + 'IOTA_AUTH_PERMANENT_TOKEN', + 'IOTA_REGISTRY_TYPE', + 'IOTA_LOG_LEVEL', + 'IOTA_TIMESTAMP', + 'IOTA_IOTAM_HOST', + 'IOTA_IOTAM_PORT', + 'IOTA_IOTAM_PATH', + 'IOTA_IOTAM_PROTOCOL', + 'IOTA_IOTAM_DESCRIPTION', + 'IOTA_DEFAULT_RESOURCE', + 'IOTA_EXPLICIT_ATTRS', + 'IOTA_MONGO_HOST', + 'IOTA_MONGO_PORT', + 'IOTA_MONGO_DB', + 'IOTA_MONGO_REPLICASET', + 'IOTA_AUTOCAST', + 'IOTA_MONGO_PASSWORD', + 'IOTA_MONGO_AUTH_SOURCE', + 'IOTA_MONGO_RETRIES', + 'IOTA_MONGO_USER', + 'IOTA_MONGO_RETRY_TIME', + 'IOTA_SINGLE_MODE', + 'IOTA_APPEND_MODE', + 'IOTA_POLLING_EXPIRATION', + 'IOTA_POLLING_DAEMON_FREQ', + 'IOTA_MULTI_CORE', + 'IOTA_DEFAULT_EXPRESSION_LANGUAGE', + 'IOTA_RELAX_TEMPLATE_VALIDATION' + ]; + const iotamVariables = [ + 'IOTA_IOTAM_URL', + 'IOTA_IOTAM_HOST', + 'IOTA_IOTAM_PORT', + 'IOTA_IOTAM_PATH', + 'IOTA_IOTAM_PROTOCOL', + 'IOTA_IOTAM_DESCRIPTION', + 'IOTA_IOTAM_AGENTPATH' + ]; + const mongoVariables = [ + 'IOTA_MONGO_HOST', + 'IOTA_MONGO_PORT', + 'IOTA_MONGO_DB', + 'IOTA_MONGO_REPLICASET', + 'IOTA_MONGO_USER', + 'IOTA_MONGO_PASSWORD', + 'IOTA_MONGO_AUTH_SOURCE', + 'IOTA_MONGO_RETRIES', + 'IOTA_MONGO_RETRY_TIME', + 'IOTA_MONGO_SSL', + 'IOTA_MONGO_EXTRAARGS' + ]; + const protectedVariables = [ + 'IOTA_AUTH_USER', + 'IOTA_AUTH_PASSWORD', + 'IOTA_AUTH_CLIENT_ID', + 'IOTA_AUTH_CLIENT_SECRET', + 'IOTA_MONGO_USER', + 'IOTA_MONGO_PASSWORD' + ]; // Substitute Docker Secret Variables where set. protectedVariables.forEach((key) => { @@ -204,10 +194,12 @@ function processEnvironmentVariables() { environmentVariables.forEach((key) => { let value = process.env[key]; if (value) { - if (key.endsWith('USER') || - key.endsWith('PASSWORD') || - key.endsWith('CLIENT_ID') || - key.endsWith('CLIENT_SECRET')) { + if ( + key.endsWith('USER') || + key.endsWith('PASSWORD') || + key.endsWith('CLIENT_ID') || + key.endsWith('CLIENT_SECRET') + ) { value = '********'; } logger.info('Setting %s to environment value: %s', key, value); @@ -262,8 +254,7 @@ function processEnvironmentVariables() { // Authentication Parameters - General if (process.env.IOTA_AUTH_ENABLED) { config.authentication = {}; - config.authentication.enabled = - process.env.IOTA_AUTH_ENABLED === 'true'; + config.authentication.enabled = process.env.IOTA_AUTH_ENABLED === 'true'; } if (process.env.IOTA_AUTH_TYPE) { config.authentication.type = process.env.IOTA_AUTH_TYPE; @@ -293,16 +284,14 @@ function processEnvironmentVariables() { config.authentication.clientId = process.env.IOTA_AUTH_CLIENT_ID; } if (process.env.IOTA_AUTH_CLIENT_SECRET) { - config.authentication.clientSecret = - process.env.IOTA_AUTH_CLIENT_SECRET; + config.authentication.clientSecret = process.env.IOTA_AUTH_CLIENT_SECRET; } if (process.env.IOTA_AUTH_TOKEN_PATH) { config.authentication.tokenPath = process.env.IOTA_AUTH_TOKEN_PATH; } // Authentication Parameters - Keyrock only if (process.env.IOTA_AUTH_PERMANENT_TOKEN) { - config.authentication.permanentToken = - process.env.IOTA_AUTH_PERMANENT_TOKEN; + config.authentication.permanentToken = process.env.IOTA_AUTH_PERMANENT_TOKEN; } // Authentication Parameters - Keystone only if (process.env.IOTA_AUTH_USER) { @@ -413,27 +402,23 @@ function processEnvironmentVariables() { } if (process.env.IOTA_MONGO_SSL) { - config.mongodb.ssl = - process.env.IOTA_MONGO_SSL.toLowerCase() === 'true'; + config.mongodb.ssl = process.env.IOTA_MONGO_SSL.toLowerCase() === 'true'; } if (process.env.IOTA_MONGO_EXTRAARGS) { try { - var ea = JSON.parse(process.env.IOTA_MONGO_EXTRAARGS); - if ( - ea !== null && - typeof ea === 'object' && - ea.constructor === Object - ) { + const ea = JSON.parse(process.env.IOTA_MONGO_EXTRAARGS); + if (ea !== null && typeof ea === 'object' && ea.constructor === Object) { config.mongodb.extraArgs = ea; } - } catch (e) {} + } catch (e) { + // Do nothing + } } // Other configuration properties if (process.env.IOTA_SINGLE_MODE) { - config.singleConfigurationMode = - process.env.IOTA_SINGLE_MODE === 'true'; + config.singleConfigurationMode = process.env.IOTA_SINGLE_MODE === 'true'; } if (process.env.IOTA_APPEND_MODE) { @@ -459,8 +444,7 @@ function processEnvironmentVariables() { } if (process.env.IOTA_DEFAULT_EXPRESSION_LANGUAGE) { - config.defaultExpressionLanguage = - process.env.IOTA_DEFAULT_EXPRESSION_LANGUAGE; + config.defaultExpressionLanguage = process.env.IOTA_DEFAULT_EXPRESSION_LANGUAGE; } if (process.env.IOTA_RELAX_TEMPLATE_VALIDATION) { config.relaxTemplateValidation = process.env.IOTA_RELAX_TEMPLATE_VALIDATION === 'true'; @@ -514,11 +498,7 @@ function getCommandRegistry() { * @return {boolean} Result of the checking */ function checkNgsi2() { - if ( - config.contextBroker && - config.contextBroker.ngsiVersion && - config.contextBroker.ngsiVersion === 'v2' - ) { + if (config.contextBroker && config.contextBroker.ngsiVersion && config.contextBroker.ngsiVersion === 'v2') { return true; } @@ -533,7 +513,6 @@ function getSecurityService() { return securityService; } - exports.setConfig = setConfig; exports.getConfig = getConfig; exports.setRegistry = setRegistry; diff --git a/lib/constants.js b/lib/constants.js index cfeb4b35e..b3ca4e0cf 100644 --- a/lib/constants.js +++ b/lib/constants.js @@ -23,8 +23,6 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - module.exports = { TIMESTAMP_ATTRIBUTE: 'TimeInstant', TIMESTAMP_TYPE: 'ISO8601', diff --git a/lib/errors.js b/lib/errors.js index 96e5e286e..23eaf406c 100644 --- a/lib/errors.js +++ b/lib/errors.js @@ -22,162 +22,266 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ - -'use strict'; - -module.exports = { - RegistrationError: function(id, type) { +class RegistrationError { + constructor(id, type) { this.name = 'REGISTRATION_ERROR'; this.message = 'Error registering context provider for device: ' + id + ' of type: ' + type; - }, - UnregistrationError: function(id, type) { + } +} +class UnregistrationError { + constructor(id, type) { this.name = 'UNREGISTRATION_ERROR'; this.message = 'Error unregistering context provider for device: ' + id + ' of type: ' + type; - }, - EntityGenericError: function(id, type, details, code) { + } +} +class EntityGenericError { + constructor(id, type, details, code) { this.name = 'ENTITY_GENERIC_ERROR'; this.message = 'Error accesing entity data for device: ' + id + ' of type: ' + type; this.details = details || {}; this.code = code || 200; - }, - EntityNotFound: function(id) { + } +} +class EntityNotFound { + constructor(id) { this.name = 'ENTITY_NOT_FOUND'; this.message = 'The entity with the requested id [' + id + '] was not found.'; this.code = 404; - }, - RegistryNotAvailable: function() { + } +} +class RegistryNotAvailable { + constructor() { this.name = 'REGISTRY_NOT_AVAILABLE'; this.message = 'No device registry is available.'; - }, - InternalDbError: function(msg) { + } +} +class InternalDbError { + constructor(msg) { this.name = 'INTERNAL_DB_ERROR'; this.message = 'An internal DB Error happened: ' + msg; - }, - BadRequest: function(msg) { + } +} +class BadRequest { + constructor(msg) { this.name = 'BAD_REQUEST'; this.message = 'Request error connecting to the Context Broker: ' + msg; this.code = 400; - }, - UnsupportedContentType: function(type) { + } +} +class UnsupportedContentType { + constructor(type) { this.name = 'UNSUPPORTED_CONTENT_TYPE'; this.message = 'Unsuported content type in the context request: ' + type; this.code = 400; - }, - TypeNotFound: function(id, type) { + } +} +class TypeNotFound { + constructor(id, type) { this.name = 'TYPE_NOT_FOUND'; this.message = 'Type : ' + type + ' not found for device with id: ' + id; this.code = 500; - }, - MissingAttributes: function(msg) { + } +} +class MissingAttributes { + constructor(msg) { this.name = 'MISSING_ATTRIBUTES'; this.message = 'The request was not well formed:' + msg; - }, - DeviceNotFound: function(id) { + } +} +class DeviceNotFound { + constructor(id) { this.name = 'DEVICE_NOT_FOUND'; this.message = 'No device was found with id:' + id; this.code = 404; - }, - AttributeNotFound: function(){ + } +} + +class AttributeNotFound { + constructor() { this.name = 'ATTRIBUTE_NOT_FOUND'; this.message = 'Some of the attributes does not exist'; this.code = 404; - }, - DuplicateDeviceId: function(id) { + } +} + +class DuplicateDeviceId { + constructor(id) { this.name = 'DUPLICATE_DEVICE_ID'; this.message = 'A device with the same pair (Service, DeviceId) was found:' + id; this.code = 409; - }, - DuplicateGroup: function(res, key) { + } +} +class DuplicateGroup { + constructor(res, key) { this.name = 'DUPLICATE_GROUP'; this.message = 'A device configuration already exists for resource ' + res + ' and API Key ' + key; this.code = 409; - }, - SecurityInformationMissing: function(type) { + } +} +class SecurityInformationMissing { + constructor(type) { this.name = 'SECURITY_INFORMATION_MISSING'; this.message = 'Some security information was missing for device type:' + type; - }, - TokenRetrievalError: function(trust, msg) { + } +} +class TokenRetrievalError { + constructor(trust, msg) { this.name = 'TOKEN_RETRIEVAL_ERROR'; this.message = 'An error occurred trying to retrieve a token with trust [' + trust + ']: ' + msg; - }, - AccessForbidden: function(token, service, subservice) { + } +} +class AccessForbidden { + constructor(token, service, subservice) { this.name = 'ACCESS_FORBIDDEN'; - this.message = 'The access to the CB was rejected for service [' + - service + '] subservice [ ' + subservice + ' ] and token [' + token + ']'; - }, - AuthenticationError: function(trust) { + this.message = + 'The access to the CB was rejected for service [' + + service + + '] subservice [ ' + + subservice + + ' ] and token [' + + token + + ']'; + } +} +class AuthenticationError { + constructor(trust) { this.name = 'AUTHENTICATION_ERROR'; this.message = 'The trust configured for the device was rejected: [' + trust + ']'; - }, - BadConfiguration: function(msg) { + } +} +class BadConfiguration { + constructor(msg) { this.name = 'BAD_CONFIGURATION'; this.message = 'The application startup failed due to a bad configuration:' + msg; - }, - MissingHeaders: function(msg) { + } +} +class MissingHeaders { + constructor(msg) { this.name = 'MISSING_HEADERS'; this.message = 'Some headers were missing from the request: ' + msg; this.code = 400; - }, - MismatchedService: function(service, subservice) { + } +} +class MismatchedService { + /* eslint-disable-next-line no-unused-vars */ + constructor(service, subservice) { this.name = 'MISMATCHED_SERVICE'; - this.message = 'The declared service didn\'t match the stored one in the entity'; + + this.message = "The declared service didn't match the stored one in the entity"; this.code = 403; - }, - WrongSyntax: function(msg) { + } +} +class WrongSyntax { + constructor(msg) { this.name = 'WRONG_SYNTAX'; this.message = 'Wrong syntax in request: ' + msg; this.code = 400; - }, - CommandNotFound: function(name) { + } +} +class CommandNotFound { + constructor(name) { this.name = 'COMMAND_NOT_FOUND'; - this.message = 'Couldn\'t update the command because no command with the name [' + name + '] was found.'; + this.message = "Couldn't update the command because no command with the name [" + name + '] was found.'; this.code = 400; - }, - MissingConfigParams: function(missing) { + } +} +class MissingConfigParams { + constructor(missing) { this.name = 'MISSING_CONFIG_PARAMS'; this.message = 'The following mandatory configuration parameters were missing: ' + JSON.stringify(missing); this.code = 400; - }, - NotificationError: function(code) { + } +} +class NotificationError { + constructor(code) { this.name = 'NOTIFICATION_ERROR'; this.message = 'Incoming notification with non-200 status code: ' + code; this.code = 400; - }, - DeviceGroupNotFound: function(fields, values) { + } +} +class DeviceGroupNotFound { + constructor(fields, values) { this.name = 'DEVICE_GROUP_NOT_FOUND'; if (values && fields) { - this.message = 'Couldn\t find device group for fields: ' + JSON.stringify(fields) + - ' and values: ' + JSON.stringify(values); + this.message = + 'Couldn\t find device group for fields: ' + + JSON.stringify(fields) + + ' and values: ' + + JSON.stringify(values); } else if (fields) { this.message = 'Couldn\t find device group for fields: ' + JSON.stringify(fields); } else { - this.message = 'Couldn\t find device group'; + this.message = "Couldn't find device group"; } this.code = 404; - }, - GroupNotFound: function(service, subservice) { + } +} +class GroupNotFound { + constructor(service, subservice) { this.name = 'GROUP_NOT_FOUND'; this.message = 'Group not found for service [' + service + '] and subservice [' + subservice + ']'; this.code = 404; - }, - WrongExpressionType: function(type) { + } +} +class WrongExpressionType { + constructor(type) { this.name = 'WRONG_EXPRESSION_TYPE'; this.message = 'Invalid type evaluating expression [' + type + ']'; this.code = 400; - }, - InvalidExpression: function(expression) { + } +} +class InvalidExpression { + constructor(expression) { this.name = 'INVALID_EXPRESSION'; this.message = 'Invalid expression in evaluation [' + expression + ']'; this.code = 400; - }, - BadAnswer: function(statusCode, operation) { + } +} +class BadAnswer { + constructor(statusCode, operation) { this.name = 'BAD_ANSWER'; this.message = 'Invalid statusCode in operation [' + operation + ']'; this.code = 400; - }, - BadTimestamp: function(payload) { + } +} +class BadTimestamp { + constructor(payload) { this.name = 'BAD_TIMESTAMP'; this.message = 'Invalid ISO8601 timestamp [' + payload + ']'; this.code = 400; } +} + +module.exports = { + RegistrationError, + UnregistrationError, + EntityGenericError, + EntityNotFound, + RegistryNotAvailable, + InternalDbError, + BadRequest, + UnsupportedContentType, + TypeNotFound, + MissingAttributes, + AttributeNotFound, + DeviceNotFound, + DuplicateDeviceId, + DuplicateGroup, + SecurityInformationMissing, + TokenRetrievalError, + AccessForbidden, + AuthenticationError, + BadConfiguration, + MissingHeaders, + MismatchedService, + WrongSyntax, + CommandNotFound, + MissingConfigParams, + NotificationError, + DeviceGroupNotFound, + GroupNotFound, + WrongExpressionType, + InvalidExpression, + BadAnswer, + BadTimestamp }; diff --git a/lib/fiware-iotagent-lib.js b/lib/fiware-iotagent-lib.js index a53dd763f..d06cef072 100644 --- a/lib/fiware-iotagent-lib.js +++ b/lib/fiware-iotagent-lib.js @@ -21,41 +21,42 @@ * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; - -var async = require('async'), - apply = async.apply, - ngsi = require('./services/ngsi/ngsiService'), - intoTrans = require('./services/common/domain').intoTrans, - middlewares = require('./services/common/genericMiddleware'), - db = require('./model/dbConn'), - subscriptions = require('./services/ngsi/subscriptionService'), - statsRegistry = require('./services/stats/statsRegistry'), - domainUtils = require('./services/common/domain'), - deviceService = require('./services/devices/deviceService'), - groupConfig = require('./services/groups/groupService'), - commands = require('./services/commands/commandService'), - iotManager = require('./services/common/iotManagerService'), - contextServer = require('./services/northBound/northboundServer'), - errors = require('./errors'), - constants = require('./constants'), - logger = require('logops'), - config = require('./commonConfig'), - cluster = require('cluster'), - context = { - op: 'IoTAgentNGSI.Global' - }; +const async = require('async'); +const apply = async.apply; +const ngsi = require('./services/ngsi/ngsiService'); +const intoTrans = require('./services/common/domain').intoTrans; +const middlewares = require('./services/common/genericMiddleware'); +const db = require('./model/dbConn'); +const subscriptions = require('./services/ngsi/subscriptionService'); +const statsRegistry = require('./services/stats/statsRegistry'); +const domainUtils = require('./services/common/domain'); +const deviceService = require('./services/devices/deviceService'); +const groupConfig = require('./services/groups/groupService'); +const commands = require('./services/commands/commandService'); +const iotManager = require('./services/common/iotManagerService'); +const contextServer = require('./services/northBound/northboundServer'); +const errors = require('./errors'); +const constants = require('./constants'); +const logger = require('logops'); +const config = require('./commonConfig'); +const cluster = require('cluster'); +const context = { + op: 'IoTAgentNGSI.Global' +}; function activateStatLogs(newConfig, callback) { if (newConfig.stats && newConfig.stats.interval) { - async.series([ - apply(statsRegistry.globalLoad, { - deviceCreationRequests: 0, - deviceRemovalRequests: 0, - measureRequests: 0 - }), - apply(statsRegistry.addTimerAction, statsRegistry.logStats) - ], callback); + async.series( + [ + apply(statsRegistry.globalLoad, { + deviceCreationRequests: 0, + deviceRemovalRequests: 0, + measureRequests: 0 + }), + apply(statsRegistry.addTimerAction, statsRegistry.logStats) + ], + callback + ); } else { callback(); } @@ -79,10 +80,10 @@ function globalErrorHandler(err) { * @param {Function} callback The callback function. */ function doActivate(newConfig, callback) { - var registry, - groupRegistry, - commandRegistry, - securityService; + let registry; + let groupRegistry; + let commandRegistry; + let securityService; logger.format = logger.formatters.pipe; @@ -95,41 +96,42 @@ function doActivate(newConfig, callback) { newConfig = config.getConfig(); if (newConfig.contextBroker) { - if (! newConfig.contextBroker.url && newConfig.contextBroker.host && newConfig.contextBroker.port) { + if (!newConfig.contextBroker.url && newConfig.contextBroker.host && newConfig.contextBroker.port) { newConfig.contextBroker.url = 'http://' + newConfig.contextBroker.host + ':' + newConfig.contextBroker.port; - } else if (! newConfig.contextBroker.url && newConfig.contextBroker.host && !newConfig.contextBroker.port) { + } else if (!newConfig.contextBroker.url && newConfig.contextBroker.host && !newConfig.contextBroker.port) { newConfig.contextBroker.url = 'http://' + newConfig.contextBroker.host; } } if (newConfig.iotManager) { - if (! newConfig.iotManager.url && newConfig.iotManager.host && newConfig.iotManager.port) { + if (!newConfig.iotManager.url && newConfig.iotManager.host && newConfig.iotManager.port) { newConfig.iotManager.url = 'http://' + newConfig.iotManager.host + ':' + newConfig.iotManager.port; - } else if (! newConfig.iotManager.url && newConfig.iotManager.host && !newConfig.iotManager.port) { + } else if (!newConfig.iotManager.url && newConfig.iotManager.host && !newConfig.iotManager.port) { newConfig.iotManager.url = 'http://' + newConfig.iotManager.host; } } if (newConfig.authentication && newConfig.authentication.enabled) { - if (! newConfig.authentication.header) { + if (!newConfig.authentication.header) { newConfig.authentication.header = constants.AUTH_HEADER; } - if (! newConfig.authentication.url && newConfig.authentication.host && newConfig.authentication.port) { - newConfig.authentication.url = 'http://' + newConfig.authentication.host + ':' + - newConfig.authentication.port; - } else if (! newConfig.authentication.url && newConfig.authentication.host && !newConfig.authentication.port) { + if (!newConfig.authentication.url && newConfig.authentication.host && newConfig.authentication.port) { + newConfig.authentication.url = + 'http://' + newConfig.authentication.host + ':' + newConfig.authentication.port; + } else if (!newConfig.authentication.url && newConfig.authentication.host && !newConfig.authentication.port) { newConfig.authentication.url = 'http://' + newConfig.authentication.host; } } - if (newConfig.defaultExpressionLanguage && - (newConfig.defaultExpressionLanguage === 'legacy' || - newConfig.defaultExpressionLanguage ==='jexl')){ - logger.info(context, 'Using ' + newConfig.defaultExpressionLanguage + ' as default expression language'); + if ( + newConfig.defaultExpressionLanguage && + (newConfig.defaultExpressionLanguage === 'legacy' || newConfig.defaultExpressionLanguage === 'jexl') + ) { + logger.info(context, 'Using ' + newConfig.defaultExpressionLanguage + ' as default expression language'); } else { - logger.info(context, 'Default expression language not set, or invalid, using legacy configuration'); - newConfig.defaultExpressionLanguage = 'legacy'; + logger.info(context, 'Default expression language not set, or invalid, using legacy configuration'); + newConfig.defaultExpressionLanguage = 'legacy'; } config.setConfig(newConfig); //after chaging some configuration, we re apply the configuration @@ -137,8 +139,7 @@ function doActivate(newConfig, callback) { logger.info(context, 'Activating IOT Agent NGSI Library.'); if (newConfig.authentication && newConfig.authentication.enabled) { - if (newConfig.authentication.type && - newConfig.authentication.type === 'oauth2') { + if (newConfig.authentication.type && newConfig.authentication.type === 'oauth2') { logger.info(context, 'Using OAuth2 as authentication service'); securityService = require('./services/common/securityServiceOAuth2'); @@ -149,9 +150,7 @@ function doActivate(newConfig, callback) { } } - if (newConfig.deviceRegistry && - newConfig.deviceRegistry.type && - newConfig.deviceRegistry.type === 'mongodb') { + if (newConfig.deviceRegistry && newConfig.deviceRegistry.type && newConfig.deviceRegistry.type === 'mongodb') { logger.info(context, 'MongoDB Device registry selected for NGSI Library'); registry = require('./services/devices/deviceRegistryMongoDB'); @@ -165,14 +164,11 @@ function doActivate(newConfig, callback) { commandRegistry = require('./services/commands/commandRegistryMemory'); } - exports.clearAll = function(callback) { - async.series([ - registry.clear, - groupRegistry.clear, - commandRegistry.clear, - ngsi.resetMiddlewares, - contextServer.clear - ], callback); + exports.clearAll = function (callback) { + async.series( + [registry.clear, groupRegistry.clear, commandRegistry.clear, ngsi.resetMiddlewares, contextServer.clear], + callback + ); }; config.setSecurityService(securityService); @@ -182,18 +178,14 @@ function doActivate(newConfig, callback) { commands.start(); - async.series([ - db.configureDb, - apply(contextServer.start, newConfig), - apply(activateStatLogs, newConfig) - ], callback); + async.series([db.configureDb, apply(contextServer.start, newConfig), apply(activateStatLogs, newConfig)], callback); } function checkConfig(newConfig, callback) { - var mandatory = ['providerUrl', 'types'], - missing = []; + const mandatory = ['providerUrl', 'types']; + const missing = []; - for (var i in mandatory) { + for (const i in mandatory) { if (!newConfig[mandatory[i]]) { missing.push(mandatory[i]); } @@ -201,15 +193,15 @@ function checkConfig(newConfig, callback) { if (newConfig.authentication && newConfig.authentication.enabled) { if (newConfig.authentication.type && newConfig.authentication.type === 'oauth2') { - var mandatoryOauth = ['tokenPath', 'clientId', 'clientSecret']; - for (var j in mandatoryOauth) { + const mandatoryOauth = ['tokenPath', 'clientId', 'clientSecret']; + for (const j in mandatoryOauth) { if (!newConfig.authentication[mandatoryOauth[j]]) { missing.push('authentication.' + mandatoryOauth[j]); } } } else { - var mandatoryKeystone = ['user', 'password']; - for (var k in mandatoryKeystone) { + const mandatoryKeystone = ['user', 'password']; + for (const k in mandatoryKeystone) { if (!newConfig.authentication[mandatoryKeystone[k]]) { missing.push('authentication.' + mandatoryKeystone[k]); } @@ -225,11 +217,7 @@ function checkConfig(newConfig, callback) { } function activate(newConfig, callback) { - async.series([ - apply(checkConfig, newConfig), - apply(doActivate, newConfig), - iotManager.register - ], callback); + async.series([apply(checkConfig, newConfig), apply(doActivate, newConfig), iotManager.register], callback); } /** @@ -258,7 +246,7 @@ function startServer(newConfig, iotAgent, callback) { // get the proper context of the logger logger.getContext = function domainContext() { - var domainObj = require('domain').active || {}; + const domainObj = require('domain').active || {}; return { corr: domainObj.corr, @@ -277,11 +265,11 @@ function startServer(newConfig, iotAgent, callback) { if (cluster.isMaster) { // Code to run if we're in a master node process // Count the machine's CPUs - var cpuCount = require('os').cpus().length; + const cpuCount = require('os').cpus().length; logger.info(context, 'Master cluster setting up ' + cpuCount + ' workers...'); // Create a worker for each CPU in the machine - for (var i = 0; i < cpuCount; i += 1) { + for (let i = 0; i < cpuCount; i += 1) { cluster.fork(); } @@ -292,12 +280,11 @@ function startServer(newConfig, iotAgent, callback) { // If a worker died, automatically we create a new worker to replace it cluster.on('exit', function (worker, code, signal) { - var message = 'Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal; + const message = 'Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal; logger.warn(context, message); logger.warn(context, 'Starting a new worker...'); cluster.fork(); }); - } else { // We are in the worker, and they can share any TCP connection logger.info(context, 'Starting a new worker...'); @@ -310,7 +297,6 @@ function startServer(newConfig, iotAgent, callback) { } } - exports.activate = intoTrans(context, activate); exports.deactivate = intoTrans(context, deactivate); exports.register = deviceService.register; diff --git a/lib/model/Command.js b/lib/model/Command.js index 4169c89c2..3706b971a 100644 --- a/lib/model/Command.js +++ b/lib/model/Command.js @@ -20,12 +20,11 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; -var mongoose = require('mongoose'), - Schema = mongoose.Schema; +const mongoose = require('mongoose'); +const Schema = mongoose.Schema; -var Command = new Schema({ +const Command = new Schema({ deviceId: String, type: String, name: String, diff --git a/lib/model/Device.js b/lib/model/Device.js index 47f37ec78..0090023fe 100644 --- a/lib/model/Device.js +++ b/lib/model/Device.js @@ -20,12 +20,11 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; -var mongoose = require('mongoose'), - Schema = mongoose.Schema; +const mongoose = require('mongoose'); +const Schema = mongoose.Schema; -var Device = new Schema({ +const Device = new Schema({ id: String, type: String, name: String, diff --git a/lib/model/Group.js b/lib/model/Group.js index aa0760f1c..de94694b2 100644 --- a/lib/model/Group.js +++ b/lib/model/Group.js @@ -20,12 +20,11 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; -var mongoose = require('mongoose'), - Schema = mongoose.Schema; +const mongoose = require('mongoose'); +const Schema = mongoose.Schema; -var Group = new Schema({ +const Group = new Schema({ url: String, resource: String, apikey: String, diff --git a/lib/model/dbConn.js b/lib/model/dbConn.js index 78eda3bf9..c47c3c2d8 100644 --- a/lib/model/dbConn.js +++ b/lib/model/dbConn.js @@ -20,25 +20,24 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; /** * This module sets up the connection with the mongodb through mongoose. This connection will be used * in mongoose schemas to persist objects. */ -var mongoose = require('mongoose'), - config = require('../commonConfig'), - constants = require('../constants'), - alarms = require('../services/common/alarmManagement'), - logger = require('logops'), - async = require('async'), - errors = require('../errors'), - defaultDb, - DEFAULT_DB_NAME = 'iotagent', - context = { - op: 'IoTAgentNGSI.DbConn' - }; +const mongoose = require('mongoose'); +const config = require('../commonConfig'); +const constants = require('../constants'); +const alarms = require('../services/common/alarmManagement'); +const logger = require('logops'); +const async = require('async'); +const errors = require('../errors'); +let defaultDb; +const DEFAULT_DB_NAME = 'iotagent'; +const context = { + op: 'IoTAgentNGSI.DbConn' +}; function loadModels() { require('./Device').load(defaultDb); @@ -53,13 +52,11 @@ function loadModels() { */ function init(host, db, port, options, callback) { /*jshint camelcase:false, validthis:true */ - var hosts, - url, - retries = 0, - lastError, - maxRetries = (config.getConfig().mongodb && config.getConfig().mongodb.retries || - constants.DEFAULT_MONGODB_RETRIES); - + let url; + let retries = 0; + let lastError; + const maxRetries = + (config.getConfig().mongodb && config.getConfig().mongodb.retries) || constants.DEFAULT_MONGODB_RETRIES; function addPort(item) { return item + ':' + port; @@ -75,22 +72,23 @@ function init(host, db, port, options, callback) { return previous; } - hosts = host.split(',') - .map(addPort) - .reduce(commaConcat, ''); + const hosts = host.split(',').map(addPort).reduce(commaConcat, ''); url = 'mongodb://' + hosts + '/' + db; if (options.extraArgs) { if (options.extraArgs instanceof Object && Object.keys(options.extraArgs).length > 0) { url += '?'; - url += Object.entries(options.extraArgs).map(function([k, v]) { - return encodeURIComponent(k) + '=' + encodeURIComponent(v); - }).join('&'); + url += Object.entries(options.extraArgs) + .map(function ([k, v]) { + return encodeURIComponent(k) + '=' + encodeURIComponent(v); + }) + .join('&'); } delete options.extraArgs; } + /* eslint-disable-next-line no-unused-vars */ function createConnectionHandler(error, results) { if (defaultDb) { logger.info(context, 'Successfully connected to MongoDB.'); @@ -108,45 +106,46 @@ function init(host, db, port, options, callback) { } function connectionAttempt(url, options, callback) { - var candidateDb; - logger.info(context, 'Attempting to connect to MongoDB instance. Attempt %d', retries); options.useNewUrlParser = true; mongoose.set('useCreateIndex', true); - candidateDb = mongoose.createConnection(url, options, function(error, result) { + /* eslint-disable-next-line no-unused-vars */ + const candidateDb = mongoose.createConnection(url, options, function (error, result) { if (error) { logger.error(context, 'MONGODB-001: Error trying to connect to MongoDB: %s', error); lastError = error; } else { defaultDb = candidateDb; - defaultDb.on('error', function(error) { + defaultDb.on('error', function (error) { logger.error(context, 'Mongo Driver error: %j', error); alarms.raise(constants.MONGO_ALARM, error); }); - defaultDb.on('connecting', function(error) { + /* eslint-disable-next-line no-unused-vars */ + defaultDb.on('connecting', function (error) { logger.debug(context, 'Mongo Driver connecting'); }); - defaultDb.on('connected', function() { + + defaultDb.on('connected', function () { logger.debug(context, 'Mongo Driver connected'); }); - defaultDb.on('reconnected', function() { + defaultDb.on('reconnected', function () { logger.debug(context, 'Mongo Driver reconnected'); }); - defaultDb.on('disconnected', function() { + defaultDb.on('disconnected', function () { logger.debug(context, 'Mongo Driver disconnected'); }); - defaultDb.on('reconnectFailed', function() { + defaultDb.on('reconnectFailed', function () { logger.error(context, 'MONGODB-004: MongoDB connection was lost'); process.exit(1); }); - defaultDb.on('disconnecting', function() { + defaultDb.on('disconnecting', function () { logger.debug(context, 'Mongo Driver disconnecting'); }); - defaultDb.on('open', function() { + defaultDb.on('open', function () { logger.debug(context, 'Mongo Driver open'); }); - defaultDb.on('close', function() { + defaultDb.on('close', function () { logger.debug(context, 'Mongo Driver close'); }); } @@ -156,9 +155,10 @@ function init(host, db, port, options, callback) { } function tryCreateConnection(callback) { - var attempt = async.apply(connectionAttempt, url, options, callback), - seconds = (config.getConfig().mongodb && config.getConfig().mongodb.retryTime || - constants.DEFAULT_MONGODB_RETRY_TIME); + const attempt = async.apply(connectionAttempt, url, options, callback); + const seconds = + (config.getConfig().mongodb && config.getConfig().mongodb.retryTime) || + constants.DEFAULT_MONGODB_RETRY_TIME; retries++; @@ -177,17 +177,19 @@ function init(host, db, port, options, callback) { function configureDb(callback) { /*jshint camelcase:false, validthis:true */ - var currentConfig = config.getConfig(); + const currentConfig = config.getConfig(); - if ((currentConfig.deviceRegistry && currentConfig.deviceRegistry.type === 'mongodb') || - (currentConfig.stats && currentConfig.stats.persistence === true)) { + if ( + (currentConfig.deviceRegistry && currentConfig.deviceRegistry.type === 'mongodb') || + (currentConfig.stats && currentConfig.stats.persistence === true) + ) { if (!currentConfig.mongodb || !currentConfig.mongodb.host) { logger.fatal(context, 'MONGODB-003: No host found for MongoDB driver.'); callback(new errors.BadConfiguration('No host found for MongoDB driver')); } else { - var dbName = currentConfig.mongodb.db, - port = currentConfig.mongodb.port || 27017, - options = {}; + let dbName = currentConfig.mongodb.db; + const port = currentConfig.mongodb.port || 27017; + const options = {}; if (!currentConfig.mongodb.db) { dbName = DEFAULT_DB_NAME; diff --git a/lib/plugins/addEvent.js b/lib/plugins/addEvent.js index 9548e8994..6a3862648 100644 --- a/lib/plugins/addEvent.js +++ b/lib/plugins/addEvent.js @@ -1,4 +1,3 @@ - /* * Copyright 2016 Telefonica Investigación y Desarrollo, S.A.U * @@ -22,13 +21,11 @@ * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; - -var pluginUtils = require('./pluginUtils'), - config = require('../commonConfig'); +const pluginUtils = require('./pluginUtils'); +const config = require('../commonConfig'); function addEvents() { - return (new Date()).toISOString(); + return new Date().toISOString(); } exports.update = pluginUtils.createUpdateFilter(addEvents, config.getConfig().eventType || 'Event'); diff --git a/lib/plugins/attributeAlias.js b/lib/plugins/attributeAlias.js index 728c29cb4..c1b87409e 100644 --- a/lib/plugins/attributeAlias.js +++ b/lib/plugins/attributeAlias.js @@ -23,17 +23,17 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; +/* eslint-disable no-unused-vars */ -var config = require('../commonConfig'), - utils = require('./pluginUtils'), - /*jshint unused:false*/ - logger = require('logops'), - /*jshint unused:false*/ - context = { - op: 'IoTAgentNGSI.attributeAlias' - }, - ngsiService = require('../services/ngsi/ngsiService'); +const config = require('../commonConfig'); +const utils = require('./pluginUtils'); +/*jshint unused:false*/ +const logger = require('logops'); +/*jshint unused:false*/ +const context = { + op: 'IoTAgentNGSI.attributeAlias' +}; +const ngsiService = require('../services/ngsi/ngsiService'); function extractSingleMapping(previous, current) { /* jshint camelcase: false */ @@ -51,7 +51,7 @@ function extractSingleMapping(previous, current) { * @return {{direct: {}, inverse: {}}} Object containing the direct and reverse name mappings. */ function extractAllMappings(typeInformation) { - var mappings = { direct: {}, inverse: {}, types: {}, metadata: {}}; + let mappings = { direct: {}, inverse: {}, types: {}, metadata: {} }; if (typeInformation.active) { mappings = typeInformation.active.reduce(extractSingleMapping, mappings); @@ -95,9 +95,9 @@ function applyAlias(mappings) { * @param {Object} typeInformation Provisioning information about the device represented by the entity. */ function updateAttribute(entity, typeInformation, callback) { - var mappings = extractAllMappings(typeInformation); + const mappings = extractAllMappings(typeInformation); if (config.checkNgsi2()) { - var attsArray = utils.extractAttributesArrayFromNgsi2Entity(entity); + let attsArray = utils.extractAttributesArrayFromNgsi2Entity(entity); attsArray = attsArray.map(applyAlias(mappings)); entity = utils.createNgsi2Entity(entity.id, entity.type, attsArray, true); ngsiService.castJsonNativeAttributes(entity); diff --git a/lib/plugins/bidirectionalData.js b/lib/plugins/bidirectionalData.js index 9ff44faad..67b3c469b 100644 --- a/lib/plugins/bidirectionalData.js +++ b/lib/plugins/bidirectionalData.js @@ -23,19 +23,17 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var async = require('async'), - apply = async.apply, - _ = require('underscore'), - parser = require('./expressionParser'), - logger = require('logops'), - subscriptions = require('../services/ngsi/subscriptionService'), - deviceService = require('../services/devices/deviceService'), - context = { - op: 'IoTAgentNGSI.BidirectionalPlugin' - }, - config = require('../commonConfig'); +const async = require('async'); +const apply = async.apply; +const _ = require('underscore'); +const parser = require('./expressionParser'); +const logger = require('logops'); +const subscriptions = require('../services/ngsi/subscriptionService'); +const deviceService = require('../services/devices/deviceService'); +const context = { + op: 'IoTAgentNGSI.BidirectionalPlugin' +}; +const config = require('../commonConfig'); /** * Extract a list of all the bidirectional attributes (those containing reverse expressions) from a device object. @@ -45,7 +43,7 @@ var async = require('async'), * @param {Object} group Configuration Group data object. */ function extractBidirectionalAttributes(device, group, callback) { - var attributeList; + let attributeList; function isBidirectional(item) { return item.reverse; @@ -73,16 +71,15 @@ function extractBidirectionalAttributes(device, group, callback) { * @return {Array} List of variables in all the collection of reverse expressions. */ function extractVariables(item) { - var variables; + let variables; function extractFromExpression(value) { if (value.expression) { - return value.expression.match(/@[a-zA-Z]+/g).map(function(item) { + return value.expression.match(/@[a-zA-Z]+/g).map(function (item) { return item.substr(1); }); - } else { - return []; } + return []; } if (item.reverse) { @@ -101,9 +98,8 @@ function extractVariables(item) { * @param {Array} attributeList List of active attributes for subscription. */ function sendSubscriptions(device, attributeList, callback) { - function sendSingleSubscriptionNgsi1(item, innerCb) { - var variables = extractVariables(item); + const variables = extractVariables(item); subscriptions.subscribe(device, [item.name], variables, function handleSubscription(error, subId) { if (error) { @@ -118,7 +114,7 @@ function sendSubscriptions(device, attributeList, callback) { } function sendSingleSubscriptionNgsi2(item, innerCb) { - var variables = extractVariables(item); + const variables = extractVariables(item); subscriptions.subscribe(device, [item.name], variables, function handleSubscription(error, subId) { if (error) { @@ -176,20 +172,20 @@ function handleGroupProvision(newGroup, callback) { * @param {Array} values List of reported attributes (with their name, type and value). */ function getReverseTransformations(list, values, callback) { - var availableData = _.pluck(values, 'name'), - transformations = []; + const availableData = _.pluck(values, 'name'); + let transformations = []; function getVariable(expression) { - return expression.match(/@[a-zA-Z]+/g).map(function(item) { + return expression.match(/@[a-zA-Z]+/g).map(function (item) { return item.substr(1); }); } if (list && list.length > 0) { - for (var i = 0; i < list.length; i++) { + for (let i = 0; i < list.length; i++) { if (list[i].reverse && list[i].reverse.length > 0) { - var expressions = _.pluck(list[i].reverse, 'expression'), - variables = _.uniq(_.flatten(expressions.map(getVariable))); + const expressions = _.pluck(list[i].reverse, 'expression'); + const variables = _.uniq(_.flatten(expressions.map(getVariable))); if (_.difference(variables, availableData).length === 0) { transformations = transformations.concat(list[i].reverse); @@ -210,21 +206,21 @@ function getReverseTransformations(list, values, callback) { * @param {Array} transformations List of transformations to apply (with their name, type and expression). */ function processTransformations(values, transformations, callback) { - /*jshint camelcase:false */ + let cleanedExpression; + const ctx = parser.extractContext(values); + let resultTransformations = []; - var cleanedExpression, - ctx = parser.extractContext(values), - resultTransformations = []; - - for (var j = 0; j < 2; j++) { + for (let j = 0; j < 2; j++) { if (transformations[j]) { resultTransformations = resultTransformations.concat(transformations[j]); } } - for (var i = 0; i < resultTransformations.length; i++) { - cleanedExpression = resultTransformations[i].expression - .substr(2, resultTransformations[i].expression.length - 3); + for (let i = 0; i < resultTransformations.length; i++) { + cleanedExpression = resultTransformations[i].expression.substr( + 2, + resultTransformations[i].expression.length - 3 + ); values.push({ name: resultTransformations[i].object_id, @@ -243,21 +239,21 @@ function processTransformations(values, transformations, callback) { * @param {Object} device Device data object. */ function handleDeviceProvision(device, callback) { - deviceService.findConfigurationGroup(device, function(error, group) { + deviceService.findConfigurationGroup(device, function (error, group) { if (error) { callback(error); } else { - async.waterfall([ - apply(extractBidirectionalAttributes, device, group), - apply(sendSubscriptions, device) - ], function(error, subscriptionMaps) { - if (error) { - callback(error); - } else { - device = updateDeviceWithSubscriptionIds(subscriptionMaps, device); - callback(null, device); + async.waterfall( + [apply(extractBidirectionalAttributes, device, group), apply(sendSubscriptions, device)], + function (error, subscriptionMaps) { + if (error) { + callback(error); + } else { + device = updateDeviceWithSubscriptionIds(subscriptionMaps, device); + callback(null, device); + } } - }); + ); } }); } @@ -270,22 +266,25 @@ function handleDeviceProvision(device, callback) { * @param {Array} values List of notified values. */ function handleNotification(device, values, callback) { - deviceService.findConfigurationGroup(device, function(error, group) { - var deviceAttributes = device.active || [], - groupAttributes = group && group.attributes || []; + deviceService.findConfigurationGroup(device, function (error, group) { + const deviceAttributes = device.active || []; + const groupAttributes = (group && group.attributes) || []; if (deviceAttributes.length > 0 || groupAttributes.length > 0) { logger.debug(context, 'Processing active attributes notification'); - async.waterfall([ - apply(async.series, [ - apply(getReverseTransformations, deviceAttributes, values), - apply(getReverseTransformations, groupAttributes, values) - ]), - apply(processTransformations, values) - ], function(error, results) { - callback(error, device, results); - }); + async.waterfall( + [ + apply(async.series, [ + apply(getReverseTransformations, deviceAttributes, values), + apply(getReverseTransformations, groupAttributes, values) + ]), + apply(processTransformations, values) + ], + function (error, results) { + callback(error, device, results); + } + ); } else { callback(null, device, values); } @@ -295,4 +294,3 @@ function handleNotification(device, values, callback) { exports.deviceProvision = handleDeviceProvision; exports.groupProvision = handleGroupProvision; exports.notification = handleNotification; - diff --git a/lib/plugins/compressTimestamp.js b/lib/plugins/compressTimestamp.js index 206c022ad..8fdf510eb 100644 --- a/lib/plugins/compressTimestamp.js +++ b/lib/plugins/compressTimestamp.js @@ -1,4 +1,3 @@ - /* * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U * @@ -24,10 +23,8 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var pluginUtils = require('./pluginUtils'), - constants = require('../constants'); +const pluginUtils = require('./pluginUtils'); +const constants = require('../constants'); /** * Takes a string representation of a date in ISO8601 basic calendar format and transforms it into @@ -37,14 +34,12 @@ var pluginUtils = require('./pluginUtils'), * @return {String} Date in extended format. */ function fromBasicToExtended(date) { - var split = date.match(/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})/); + const split = date.match(/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})/); if (split) { - return '+00' + split[1] + '-' + split[2] + '-' + split[3] + 'T' + - split[4] + ':' + split[5] + ':' + split[6]; - } else { - return null; + return '+00' + split[1] + '-' + split[2] + '-' + split[3] + 'T' + split[4] + ':' + split[5] + ':' + split[6]; } + return null; } /** @@ -55,13 +50,12 @@ function fromBasicToExtended(date) { * @return {String} Date in basic format. */ function fromExtendedToBasic(date) { - var split = date.match(/\+00(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/); + const split = date.match(/\+00(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/); if (split) { return split[1] + split[2] + split[3] + 'T' + split[4] + split[5] + split[6]; - } else { - return null; } + return null; } exports.update = pluginUtils.createUpdateFilter(fromBasicToExtended, constants.TIMESTAMP_TYPE); diff --git a/lib/plugins/expressionParser.js b/lib/plugins/expressionParser.js index c509f154c..3a9dcd34f 100644 --- a/lib/plugins/expressionParser.js +++ b/lib/plugins/expressionParser.js @@ -23,72 +23,74 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var Parser = require('jison').Parser, - errors = require('../errors'), - config = require('../commonConfig'), - _ = require('underscore'), - grammar = { - lex: { - rules: [ - ['\\s+', '/* skip whitespace */'], - ['@[a-zA-Z0-9]+\\b', 'return "VARIABLE";'], - ['[0-9]+(?:\\.[0-9]+)?\\b', 'return "NUMBER";'], - ['\\*', 'return "*";'], - ['\\/', 'return "/";'], - ['-', 'return "-";'], - ['\\+', 'return "+";'], - ['\\^', 'return "^";'], - ['\\(', 'return "(";'], - ['\\)', 'return ")";'], - [',', 'return ",";'], - ['#', 'return "#";'], - ['indexOf', 'return "INDEX";'], - ['length', 'return "LENGTH";'], - ['substr', 'return "SUBSTR";'], - ['trim', 'return "TRIM";'], - ['"[a-zA-Z0-9\\s,]+"', 'return "STRING";'], - ['\'[a-zA-Z0-9\\s,]+\'', 'return "STRING";'], - ['$', 'return "EOF";'] - ] - }, - - operators: [ - ['left', '#', '+', '-'], - ['left', '*', '/'], - ['left', '^'], - ['left', 'UMINUS'] - ], - - bnf: { - expressions: [['e EOF', 'return $1;']], - - e: [ - ['e + e', '$$ = Number($1) + Number($3);'], - ['e - e', '$$ = $1 - $3;'], - ['e * e', '$$ = $1 * $3;'], - ['e / e', '$$ = $1 / $3;'], - ['e ^ e', '$$ = Math.pow($1, $3);'], - ['e # e', '$$ = String($1) + String($3);'], - ['- e', '$$ = -$2;', {'prec': 'UMINUS'}], - ['INDEX ( e , e )', '$$ = String($3).indexOf($5)'], - ['SUBSTR ( e , e , e )', '$$ = String($3).substr($5, $7)'], - ['LENGTH ( e )', '$$ = String($3).length'], - ['TRIM ( e )', '$$ = String($3).trim()'], - ['( e )', '$$ = $2;'], - ['NUMBER', '$$ = Number(yytext);'], - ['VARIABLE', '$$ = yy[yytext.substr(1)];'], - ['STRING', '$$ = yytext.substr(1, yytext.length -2);'], - ['E', '$$ = Math.E;'], - ['PI', '$$ = Math.PI;']] - } +/* eslint-disable consistent-return */ + +const Parser = require('jison').Parser; +const errors = require('../errors'); +const config = require('../commonConfig'); +const _ = require('underscore'); +const grammar = { + lex: { + rules: [ + ['\\s+', '/* skip whitespace */'], + ['@[a-zA-Z0-9]+\\b', 'return "VARIABLE";'], + ['[0-9]+(?:\\.[0-9]+)?\\b', 'return "NUMBER";'], + ['\\*', 'return "*";'], + ['\\/', 'return "/";'], + ['-', 'return "-";'], + ['\\+', 'return "+";'], + ['\\^', 'return "^";'], + ['\\(', 'return "(";'], + ['\\)', 'return ")";'], + [',', 'return ",";'], + ['#', 'return "#";'], + ['indexOf', 'return "INDEX";'], + ['length', 'return "LENGTH";'], + ['substr', 'return "SUBSTR";'], + ['trim', 'return "TRIM";'], + ['"[a-zA-Z0-9\\s,]+"', 'return "STRING";'], + + ["'[a-zA-Z0-9\\s,]+'", 'return "STRING";'], + ['$', 'return "EOF";'] + ] }, - parser = new Parser(grammar); + + operators: [ + ['left', '#', '+', '-'], + ['left', '*', '/'], + ['left', '^'], + ['left', 'UMINUS'] + ], + + bnf: { + expressions: [['e EOF', 'return $1;']], + + e: [ + ['e + e', '$$ = Number($1) + Number($3);'], + ['e - e', '$$ = $1 - $3;'], + ['e * e', '$$ = $1 * $3;'], + ['e / e', '$$ = $1 / $3;'], + ['e ^ e', '$$ = Math.pow($1, $3);'], + ['e # e', '$$ = String($1) + String($3);'], + ['- e', '$$ = -$2;', { prec: 'UMINUS' }], + ['INDEX ( e , e )', '$$ = String($3).indexOf($5)'], + ['SUBSTR ( e , e , e )', '$$ = String($3).substr($5, $7)'], + ['LENGTH ( e )', '$$ = String($3).length'], + ['TRIM ( e )', '$$ = String($3).trim()'], + ['( e )', '$$ = $2;'], + ['NUMBER', '$$ = Number(yytext);'], + ['VARIABLE', '$$ = yy[yytext.substr(1)];'], + ['STRING', '$$ = yytext.substr(1, yytext.length -2);'], + ['E', '$$ = Math.E;'], + ['PI', '$$ = Math.PI;'] + ] + } +}; +const parser = new Parser(grammar); function parse(expression, context, type, callback) { - var result, - error; + let result; + let error; if (type !== 'String' && type !== 'Number') { error = new errors.WrongExpressionType(type); @@ -107,9 +109,8 @@ function parse(expression, context, type, callback) { if (callback) { return callback(error); - } else { - throw error; } + throw error; } if (callback) { @@ -121,23 +122,21 @@ function parse(expression, context, type, callback) { } function extractContext(attributeList) { - var context = {}; + const context = {}; - for (var i = 0; i < attributeList.length; i++) { + for (let i = 0; i < attributeList.length; i++) { context[attributeList[i].name] = attributeList[i].value; } return context; } - function processExpression(context) { - return function(expression) { - var result, - cleanedExpression = expression.substr(2, expression.length - 3); + return function (expression) { + const cleanedExpression = expression.substr(2, expression.length - 3); // Note that parse() function allows both String way processing and Number way processing // (have a look to expression-test.js). However, here we only use one of the possibilities, i.e. String - result = parse(cleanedExpression, context, 'String'); + const result = parse(cleanedExpression, context, 'String'); return { original: expression, @@ -146,12 +145,13 @@ function processExpression(context) { }; } +/* eslint-disable-next-line no-unused-vars */ function applyExpression(expression, context, typeInformation) { - var expressionList = expression.match(/\$\{.*?\}/g) || [], - substitutions = expressionList.map(processExpression(context)), - expressionResult = expression; + const expressionList = expression.match(/\$\{.*?\}/g) || []; + const substitutions = expressionList.map(processExpression(context)); + let expressionResult = expression; - for (var i = 0; i < substitutions.length; i++) { + for (let i = 0; i < substitutions.length; i++) { expressionResult = expressionResult.replace(substitutions[i].original, substitutions[i].value); } @@ -159,8 +159,7 @@ function applyExpression(expression, context, typeInformation) { } function expressionApplier(context, typeInformation) { - return function(attribute) { - + return function (attribute) { /** * Determines if a value is of type float * @@ -171,12 +170,11 @@ function expressionApplier(context, typeInformation) { return !isNaN(value) && value.toString().indexOf('.') !== -1; } - var newAttribute = { + const newAttribute = { name: attribute.name, type: attribute.type }; - /*jshint camelcase: false */ if (config.checkNgsi2() && attribute.object_id) { newAttribute.object_id = attribute.object_id; } @@ -185,14 +183,11 @@ function expressionApplier(context, typeInformation) { if (attribute.type === 'Number' && isFloat(newAttribute.value)) { newAttribute.value = Number.parseFloat(newAttribute.value); - } - else if (attribute.type === 'Number' && Number.parseInt(newAttribute.value)) { + } else if (attribute.type === 'Number' && Number.parseInt(newAttribute.value)) { newAttribute.value = Number.parseInt(newAttribute.value); - } - else if (attribute.type === 'Boolean') { - newAttribute.value = (newAttribute.value === 'true' || newAttribute.value === '1'); - } - else if (attribute.type === 'None') { + } else if (attribute.type === 'Boolean') { + newAttribute.value = newAttribute.value === 'true' || newAttribute.value === '1'; + } else if (attribute.type === 'None') { newAttribute.value = null; } @@ -201,17 +196,17 @@ function expressionApplier(context, typeInformation) { } function contextAvailable(expression, context) { - var variables = expression.match(/@[a-zA-Z0-9]+/g).map(function(item) { - return item.substr(1); - }), - keys = Object.keys(context); + const variables = expression.match(/@[a-zA-Z0-9]+/g).map(function (item) { + return item.substr(1); + }); + const keys = Object.keys(context); return _.difference(variables, keys).length === 0; } function processExpressionAttributes(typeInformation, list, context) { return list - .filter(function(item) { + .filter(function (item) { return item.expression && contextAvailable(item.expression, context); }) .map(expressionApplier(context, typeInformation)); diff --git a/lib/plugins/expressionPlugin.js b/lib/plugins/expressionPlugin.js index f4224886e..d85342d05 100644 --- a/lib/plugins/expressionPlugin.js +++ b/lib/plugins/expressionPlugin.js @@ -1,4 +1,3 @@ - /* * Copyright 2016 Telefonica Investigación y Desarrollo, S.A.U * @@ -25,29 +24,29 @@ * Modified by: Federico M. Facca - Martel Innovate */ -'use strict'; +/* eslint-disable no-unused-vars */ -var _ = require('underscore'), - legacyParser = require('./expressionParser'), - jexlParser = require('./jexlParser'), - config = require('../commonConfig'), - /*jshint unused:false*/ - logger = require('logops'), - /*jshint unused:false*/ - context = { - op: 'IoTAgentNGSI.expressionPlugin' - }, - utils = require('./pluginUtils'); +const _ = require('underscore'); +const legacyParser = require('./expressionParser'); +const jexlParser = require('./jexlParser'); +const config = require('../commonConfig'); +/*jshint unused:false*/ +const logger = require('logops'); +/*jshint unused:false*/ +const context = { + op: 'IoTAgentNGSI.expressionPlugin' +}; +const utils = require('./pluginUtils'); function mergeAttributes(attrList1, attrList2) { - var finalCollection = _.clone(attrList1), - additionalItems = [], - found; + const finalCollection = _.clone(attrList1); + const additionalItems = []; + let found; - for (var i = 0; i < attrList2.length; i++) { + for (let i = 0; i < attrList2.length; i++) { found = false; - for (var j = 0; j < finalCollection.length; j++) { + for (let j = 0; j < finalCollection.length; j++) { if (finalCollection[j].name === attrList2[i].name) { finalCollection[j].value = attrList2[i].value; found = true; @@ -62,31 +61,33 @@ function mergeAttributes(attrList1, attrList2) { return finalCollection.concat(additionalItems); } - function update(entity, typeInformation, callback) { - - function checkJexl(typeInformation){ - if (config.getConfig().defaultExpressionLanguage === 'jexl' && + function checkJexl(typeInformation) { + if ( + config.getConfig().defaultExpressionLanguage === 'jexl' && + typeInformation.expressionLanguage && + typeInformation.expressionLanguage !== 'legacy' + ) { + return true; + } else if (config.getConfig().defaultExpressionLanguage === 'jexl' && !typeInformation.expressionLanguage) { + return true; + } else if ( + config.getConfig().defaultExpressionLanguage === 'legacy' && typeInformation.expressionLanguage && - typeInformation.expressionLanguage !== 'legacy') { - return true; - } else if (config.getConfig().defaultExpressionLanguage === 'jexl' && - !typeInformation.expressionLanguage) { - return true; - } else if (config.getConfig().defaultExpressionLanguage === 'legacy' && - typeInformation.expressionLanguage && typeInformation.expressionLanguage === 'jexl') { - return true; + typeInformation.expressionLanguage === 'jexl' + ) { + return true; } return false; } function processEntityUpdateNgsi1(entity) { - var parser = legacyParser; - if (checkJexl(typeInformation)){ - parser = jexlParser; + let parser = legacyParser; + if (checkJexl(typeInformation)) { + parser = jexlParser; } - var expressionAttributes = [], - ctx = parser.extractContext(entity.attributes); + let expressionAttributes = []; + const ctx = parser.extractContext(entity.attributes); if (typeInformation.active) { expressionAttributes = parser.processExpressionAttributes(typeInformation, typeInformation.active, ctx); @@ -98,12 +99,12 @@ function update(entity, typeInformation, callback) { } function processEntityUpdateNgsi2(attributes) { - var parser = legacyParser; - if (checkJexl(typeInformation)){ - parser = jexlParser; + let parser = legacyParser; + if (checkJexl(typeInformation)) { + parser = jexlParser; } - var expressionAttributes = [], - ctx = parser.extractContext(attributes); + let expressionAttributes = []; + const ctx = parser.extractContext(attributes); if (typeInformation.active) { expressionAttributes = parser.processExpressionAttributes(typeInformation, typeInformation.active, ctx); @@ -115,7 +116,7 @@ function update(entity, typeInformation, callback) { try { if (config.checkNgsi2()) { - var attsArray = utils.extractAttributesArrayFromNgsi2Entity(entity); + let attsArray = utils.extractAttributesArrayFromNgsi2Entity(entity); attsArray = processEntityUpdateNgsi2(attsArray); entity = utils.createNgsi2Entity(entity.id, entity.type, attsArray, true); } else { diff --git a/lib/plugins/jexlParser.js b/lib/plugins/jexlParser.js index 334b33248..61de1036d 100644 --- a/lib/plugins/jexlParser.js +++ b/lib/plugins/jexlParser.js @@ -23,16 +23,17 @@ * Developed by: Federico M. Facca - Martel Innovate */ -'use strict'; +/* eslint-disable consistent-return */ +/* eslint-disable no-self-assign */ +/* eslint-disable no-unused-vars */ const jexl = require('jexl'); -var errors = require('../errors'), - logger = require('logops'), - config = require('../commonConfig'), - logContext = { - op: 'IoTAgentNGSI.JEXL' - }; - +const errors = require('../errors'); +const logger = require('logops'); +const config = require('../commonConfig'); +const logContext = { + op: 'IoTAgentNGSI.JEXL' +}; jexl.addTransform('indexOf', (val, char) => String(val).indexOf(char)); jexl.addTransform('length', (val) => String(val).length); @@ -40,20 +41,19 @@ jexl.addTransform('trim', (val) => String(val).trim()); jexl.addTransform('substr', (val, int1, int2) => String(val).substr(int1, int2)); function parse(expression, context, callback) { - var result, - error; + let result; + let error; try { - - result = jexl.evalSync (expression, context); + result = jexl.evalSync(expression, context); logger.debug(logContext, 'parse expression result "[%j]" ', result); } catch (e) { - error = new errors.InvalidExpression(expression); - if (callback) { - callback(error); - } else { - throw error; - } + error = new errors.InvalidExpression(expression); + if (callback) { + callback(error); + } else { + throw error; + } } if (callback) { @@ -64,29 +64,30 @@ function parse(expression, context, callback) { } function extractContext(attributeList) { - var context = {}; - var value; - - for (var i = 0; i < attributeList.length; i++) { - if (Number.parseFloat(attributeList[i].value) && - !Number.isInteger(Number.parseFloat(attributeList[i].value))) { - value = Number.parseFloat(attributeList[i].value); - } else if (Number.parseInt(attributeList[i].value) && - Number.isInteger(Number.parseFloat(attributeList[i].value))) { - value = Number.parseInt(attributeList[i].value); + const context = {}; + let value; + + for (let i = 0; i < attributeList.length; i++) { + if (Number.parseFloat(attributeList[i].value) && !Number.isInteger(Number.parseFloat(attributeList[i].value))) { + value = Number.parseFloat(attributeList[i].value); + } else if ( + Number.parseInt(attributeList[i].value) && + Number.isInteger(Number.parseFloat(attributeList[i].value)) + ) { + value = Number.parseInt(attributeList[i].value); } else if (String(attributeList[i].value) === 'true') { - value = true; + value = true; } else if (String(attributeList[i].value) === 'false') { - value = false; + value = false; } else { - value = attributeList[i].value; + value = attributeList[i].value; } - if(attributeList[i].name) { - context[attributeList[i].name] = value; + if (attributeList[i].name) { + context[attributeList[i].name] = value; } /*jshint camelcase: false */ - if(attributeList[i].object_id) { - context[attributeList[i].object_id] = value; + if (attributeList[i].object_id) { + context[attributeList[i].object_id] = value; } /*jshint camelcase: true */ } @@ -95,15 +96,13 @@ function extractContext(attributeList) { } function applyExpression(expression, context, typeInformation) { - var result; - result = jexl.evalSync (expression, context); + const result = jexl.evalSync(expression, context); logger.debug(logContext, 'applyExpression result "[%j]" ', result); return result; } function expressionApplier(context, typeInformation) { - return function(attribute) { - + return function (attribute) { /** * Determines if a value is of type float * @@ -114,7 +113,7 @@ function expressionApplier(context, typeInformation) { return !isNaN(value) && value.toString().indexOf('.') !== -1; } - var newAttribute = { + const newAttribute = { name: attribute.name, type: attribute.type }; @@ -128,22 +127,19 @@ function expressionApplier(context, typeInformation) { if (attribute.type === 'Number' && isFloat(newAttribute.value)) { newAttribute.value = Number.parseFloat(newAttribute.value); - } - else if (attribute.type === 'Number' && Number.parseInt(newAttribute.value)) { + } else if (attribute.type === 'Number' && Number.parseInt(newAttribute.value)) { newAttribute.value = Number.parseInt(newAttribute.value); - } - else if (attribute.type === 'Boolean') { - newAttribute.value = (newAttribute.value === 'true' || newAttribute.value === '1'); - } - else if (attribute.type === 'None') { + } else if (attribute.type === 'Boolean') { + newAttribute.value = newAttribute.value === 'true' || newAttribute.value === '1'; + } else if (attribute.type === 'None') { newAttribute.value = null; - } - else if (attribute.type === 'Text' || attribute.type === 'String') { + } else if (attribute.type === 'Text' || attribute.type === 'String') { newAttribute.value = String(newAttribute.value); - } - else if (attribute.type.toLowerCase().includes('structuredvalue') || - attribute.type.toLowerCase().startsWith('geo') || - attribute.type.toLowerCase().includes('json') ) { + } else if ( + attribute.type.toLowerCase().includes('structuredvalue') || + attribute.type.toLowerCase().startsWith('geo') || + attribute.type.toLowerCase().includes('json') + ) { newAttribute.value = newAttribute.value; } else { newAttribute.value = String(newAttribute.value); @@ -153,42 +149,47 @@ function expressionApplier(context, typeInformation) { } function isTransform(identifier) { - return jexl.getTransform(identifier) === ( null || undefined) ? false : true; + return jexl.getTransform(identifier) !== (null || undefined); } function contextAvailable(expression, context) { - var error; - try{ - var lexer = jexl._getLexer(); - var identifiers = lexer.tokenize(expression).filter(function(token) { - return token.type === 'identifier'; - }); - var keys = Object.keys(context); - var validContext = true; - identifiers.some(function(element) { - if (!keys.includes(element.value) && !isTransform(element.value)) { - validContext = false; - logger.warn(logContext, 'For expression "[%s]" context does not have element %s' , expression, element.value); - } - // FIXME: Workaround to allow keys of JSON geopoints - if (element.value === 'type' || element.value === 'coordinates') { - validContext = true; - } - return validContext === false; - }); - if(validContext) { - jexl.evalSync (expression, context); + let error; + try { + const lexer = jexl._getLexer(); + const identifiers = lexer.tokenize(expression).filter(function (token) { + return token.type === 'identifier'; + }); + const keys = Object.keys(context); + let validContext = true; + identifiers.some(function (element) { + if (!keys.includes(element.value) && !isTransform(element.value)) { + validContext = false; + logger.warn( + logContext, + 'For expression "[%s]" context does not have element %s', + expression, + element.value + ); + } + // FIXME: Workaround to allow keys of JSON geopoints + if (element.value === 'type' || element.value === 'coordinates') { + validContext = true; + } + return validContext === false; + }); + if (validContext) { + jexl.evalSync(expression, context); + } + return validContext; + } catch (e) { + error = new errors.InvalidExpression(expression); + throw error; } - return validContext; - } catch (e) { - error = new errors.InvalidExpression(expression); - throw error; - } } function processExpressionAttributes(typeInformation, list, context) { return list - .filter(function(item) { + .filter(function (item) { return item.expression && contextAvailable(item.expression, context); }) .map(expressionApplier(context, typeInformation)); diff --git a/lib/plugins/multiEntity.js b/lib/plugins/multiEntity.js index 8a2be784c..c2850e9c5 100644 --- a/lib/plugins/multiEntity.js +++ b/lib/plugins/multiEntity.js @@ -23,23 +23,22 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -/* jshint camelcase: false */ - -var _ = require('underscore'), - constants = require('../constants'), - parser = require('./expressionParser'), - config = require('../commonConfig'), - /*jshint unused:false*/ - logger = require('logops'), - /*jshint unused:false*/ - context = { - op: 'IoTAgentNGSI.MultiEntityPlugin' - }, - utils = require('./pluginUtils'), - aliasPlugin = require('./attributeAlias'); - +/* eslint-disable no-prototype-builtins */ +/* eslint-disable array-callback-return */ + +const _ = require('underscore'); +const constants = require('../constants'); +const parser = require('./expressionParser'); +const config = require('../commonConfig'); +/* eslint-disable-next-line no-unused-vars */ +const logger = require('logops'); +/* eslint-disable-next-line no-unused-vars */ +const context = { + op: 'IoTAgentNGSI.MultiEntityPlugin' +}; +const utils = require('./pluginUtils'); +/* eslint-disable-next-line no-unused-vars */ +const aliasPlugin = require('./attributeAlias'); function hasEntityName(item) { return item.entity_name; @@ -53,7 +52,7 @@ function hasEntityName(item) { * @return {Array} List of all the attrbiutes without multientity flag. */ function filterOutMultientitiesNgsi1(originalAttrs, meAttributes) { - return originalAttrs.filter(function(item) { + return originalAttrs.filter(function (item) { return !_.contains(meAttributes, item.name); }); } @@ -66,8 +65,8 @@ function filterOutMultientitiesNgsi1(originalAttrs, meAttributes) { * @return {Array} List of all the attrbiutes without multientity flag. */ function filterOutMultientitiesNgsi2(originalAttrs, meAttributes) { - var result = {}; - for (var att in originalAttrs) { + const result = {}; + for (const att in originalAttrs) { if (originalAttrs.hasOwnProperty(att)) { if (!_.contains(meAttributes, att)) { result[att] = originalAttrs[att]; @@ -90,14 +89,13 @@ function filterOutMultientitiesNgsi2(originalAttrs, meAttributes) { * @return {Array} List of the new Context Entities */ function generateNewCEsNgsi1(entity, newEntities, entityTypes, typeInformation, multiEntityAttributes) { - var result = [], - newEntityAttributes, - newEntityAttributeNames, - entityName, - ctx; + const result = []; + let newEntityAttributes; + let newEntityAttributeNames; + let entityName; function filterByEntityName(entityName) { - return function(item) { + return function (item) { return item.entity_name === entityName; }; } @@ -106,9 +104,9 @@ function generateNewCEsNgsi1(entity, newEntities, entityTypes, typeInformation, return _.contains(newEntityAttributeNames, item.name); } - ctx = parser.extractContext(entity.contextElements[0].attributes); + const ctx = parser.extractContext(entity.contextElements[0].attributes); - for (var i = 0; i < newEntities.length; i++) { + for (let i = 0; i < newEntities.length; i++) { newEntityAttributeNames = _.pluck(multiEntityAttributes.filter(filterByEntityName(newEntities[i])), 'name'); newEntityAttributes = entity.contextElements[0].attributes.filter(filterByAttributeNames); @@ -127,7 +125,6 @@ function generateNewCEsNgsi1(entity, newEntities, entityTypes, typeInformation, return result; } - /** * Generate new Context Elements for each new Entity, with the attributes of the original entity matching its * entity_name. It considers Ngsiv2. @@ -140,39 +137,35 @@ function generateNewCEsNgsi1(entity, newEntities, entityTypes, typeInformation, * @return {Array} List of the new Context Entities */ function generateNewCEsNgsi2(entity, newEntities, entityTypes, typeInformation, multiEntityAttributes) { - - var result = [], - newEntityAttributes, - newEntityAttributeNames, - newEntityAttributeObjectIds, - entityName, - ctx; + const result = []; + let newEntityAttributes; + let newEntityAttributeNames; + let newEntityAttributeObjectIds; + let entityName; function filterByEntityName(entityName) { - return function(item) { + return function (item) { return item.entity_name === entityName; }; } function filterByAttributeObjectIds() { - var result = {}; - for (var att in entity) { + const result = {}; + for (const att in entity) { if (entity.hasOwnProperty(att)) { if (_.contains(newEntityAttributeNames, att)) { - if (entity[att].object_id && _.contains(newEntityAttributeObjectIds, entity[att].object_id )){ + if (entity[att].object_id && _.contains(newEntityAttributeObjectIds, entity[att].object_id)) { result[att] = entity[att]; delete entity[att].object_id; - } else { - // Check matches in rest of multientity attributes with same name (#635) - // jshint maxdepth:7 - if (entity[att].multi) { - for (var j in entity[att].multi) { - if (entity[att].multi[j].object_id && - _.contains(newEntityAttributeObjectIds, entity[att].multi[j].object_id)) { - result[att] = entity[att].multi[j]; - delete entity[att].multi[j].object_id; - break; // stop in first ocurrence (#635) - } + } else if (entity[att].multi) { + for (const j in entity[att].multi) { + if ( + entity[att].multi[j].object_id && + _.contains(newEntityAttributeObjectIds, entity[att].multi[j].object_id) + ) { + result[att] = entity[att].multi[j]; + delete entity[att].multi[j].object_id; + break; // stop in first ocurrence (#635) } } } @@ -182,13 +175,15 @@ function generateNewCEsNgsi2(entity, newEntities, entityTypes, typeInformation, return result; } - var attsArray = utils.extractAttributesArrayFromNgsi2Entity(entity); - ctx = parser.extractContext(attsArray); + const attsArray = utils.extractAttributesArrayFromNgsi2Entity(entity); + const ctx = parser.extractContext(attsArray); - for (var i = 0; i < newEntities.length; i++) { + for (let i = 0; i < newEntities.length; i++) { newEntityAttributeNames = _.pluck(multiEntityAttributes.filter(filterByEntityName(newEntities[i])), 'name'); - newEntityAttributeObjectIds = _.pluck(multiEntityAttributes.filter( - filterByEntityName(newEntities[i])), 'object_id'); + newEntityAttributeObjectIds = _.pluck( + multiEntityAttributes.filter(filterByEntityName(newEntities[i])), + 'object_id' + ); newEntityAttributes = filterByAttributeObjectIds(); entityName = parser.applyExpression(newEntities[i], ctx, typeInformation); @@ -202,9 +197,9 @@ function generateNewCEsNgsi2(entity, newEntities, entityTypes, typeInformation, } function extractTypes(attributeList, defaultType) { - var typeMap = {}; + const typeMap = {}; - for (var i = 0; i < attributeList.length; i++) { + for (let i = 0; i < attributeList.length; i++) { typeMap[attributeList[i].entity_name] = attributeList[i].entity_type || defaultType; } @@ -224,14 +219,15 @@ function extractTypes(attributeList, defaultType) { * */ function propagateTimestamp(entity, entities) { - var ts = entity[constants.TIMESTAMP_ATTRIBUTE]; + const ts = entity[constants.TIMESTAMP_ATTRIBUTE]; if (!ts) { return; } - entities.map(function(en) { + entities.map(function (en) { + let att; // Set timestamp metadata in attributes (except TimeInstant attribute itself) - for (var att in en && att !== constants.TIMESTAMP_ATTRIBUTE) { + for (att in en && att !== constants.TIMESTAMP_ATTRIBUTE) { if (en.hasOwnProperty(att) && att !== 'id' && att !== 'type') { if (!en[att].metadata) { en[att].metadata = {}; @@ -246,16 +242,15 @@ function propagateTimestamp(entity, entities) { function updateAttributeNgsi1(entity, typeInformation, callback) { if (typeInformation.active) { - var multiEntityAttributes = typeInformation.active.filter(hasEntityName), - newEntities = _.pluck(multiEntityAttributes, 'entity_name'), - attributesList = _.pluck(multiEntityAttributes, 'name'), - entityTypes = extractTypes(multiEntityAttributes, entity.contextElements[0].type), - resultAttributes; - - resultAttributes = filterOutMultientitiesNgsi1(entity.contextElements[0].attributes, attributesList); + const multiEntityAttributes = typeInformation.active.filter(hasEntityName); + const newEntities = _.pluck(multiEntityAttributes, 'entity_name'); + const attributesList = _.pluck(multiEntityAttributes, 'name'); + const entityTypes = extractTypes(multiEntityAttributes, entity.contextElements[0].type); + const resultAttributes = filterOutMultientitiesNgsi1(entity.contextElements[0].attributes, attributesList); entity.contextElements = entity.contextElements.concat( - generateNewCEsNgsi1(entity, newEntities, entityTypes, typeInformation, multiEntityAttributes)); + generateNewCEsNgsi1(entity, newEntities, entityTypes, typeInformation, multiEntityAttributes) + ); entity.contextElements[0].attributes = resultAttributes; } @@ -264,20 +259,24 @@ function updateAttributeNgsi1(entity, typeInformation, callback) { } function updateAttributeNgsi2(entity, typeInformation, callback) { - var entities = []; + let entities = []; entities.push(entity); if (typeInformation.active) { - - var multiEntityAttributes = typeInformation.active.filter(hasEntityName), - newEntities = _.pluck(multiEntityAttributes, 'entity_name'), - attributesList = _.pluck(multiEntityAttributes, 'name'), - entityTypes = extractTypes(multiEntityAttributes, typeInformation.type), - resultAttributes; + const multiEntityAttributes = typeInformation.active.filter(hasEntityName); + const newEntities = _.pluck(multiEntityAttributes, 'entity_name'); + const attributesList = _.pluck(multiEntityAttributes, 'name'); + const entityTypes = extractTypes(multiEntityAttributes, typeInformation.type); + let resultAttributes; if (multiEntityAttributes.length > 0) { resultAttributes = filterOutMultientitiesNgsi2(entity, attributesList); - var newCes = generateNewCEsNgsi2(entity, newEntities, entityTypes, typeInformation, - multiEntityAttributes); + const newCes = generateNewCEsNgsi2( + entity, + newEntities, + entityTypes, + typeInformation, + multiEntityAttributes + ); entities = entities.concat(newCes); entities[0] = resultAttributes; propagateTimestamp(entity, entities); diff --git a/lib/plugins/pluginUtils.js b/lib/plugins/pluginUtils.js index 6901d079d..7f8381556 100644 --- a/lib/plugins/pluginUtils.js +++ b/lib/plugins/pluginUtils.js @@ -23,9 +23,7 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var config = require('../commonConfig'); +const config = require('../commonConfig'); /** * Creates an array of attributes from an entity @@ -33,15 +31,16 @@ var config = require('../commonConfig'); * @return {Object} Array of attributes extracted from the entity */ function extractAttributesArrayFromNgsi2Entity(entity) { - var attsArray = []; - for (var i in entity) { + const attsArray = []; + for (const i in entity) { + /* eslint-disable-next-line no-prototype-builtins */ if (entity.hasOwnProperty(i)) { if (i !== 'id' && i !== 'type') { - var att = Object.assign({}, entity[i]); + const att = Object.assign({}, entity[i]); if (att.multi) { // jshint maxdepth:5 - for (var j in att.multi) { - var matt = Object.assign({}, entity[i].multi[j]); + for (const j in att.multi) { + const matt = Object.assign({}, entity[i].multi[j]); matt.name = i; attsArray.push(matt); } @@ -66,10 +65,10 @@ function extractAttributesArrayFromNgsi2Entity(entity) { * @return {Object} A NGSIv2 entity */ function createNgsi2Entity(id, type, attsArray, withObjectId) { - var entity = {}; + const entity = {}; entity.id = id; entity.type = type; - for (var i = 0; i < attsArray.length; i++) { + for (let i = 0; i < attsArray.length; i++) { /*jshint camelcase: false */ if (entity[attsArray[i].name] && withObjectId && attsArray[i].object_id) { // Check if multiple measures with multientity attributes with same name(#635) @@ -77,20 +76,20 @@ function createNgsi2Entity(id, type, attsArray, withObjectId) { entity[attsArray[i].name].multi = []; } entity[attsArray[i].name].multi.push({ - 'type' : attsArray[i].type, - 'value' : attsArray[i].value, + type: attsArray[i].type, + value: attsArray[i].value, /*jshint camelcase: false */ - 'object_id' : attsArray[i].object_id, - 'metadata' : attsArray[i].metadata + object_id: attsArray[i].object_id, + metadata: attsArray[i].metadata }); } else { entity[attsArray[i].name] = { - 'type' : attsArray[i].type, - 'value' : attsArray[i].value, - 'metadata' : attsArray[i].metadata + type: attsArray[i].type, + value: attsArray[i].value, + metadata: attsArray[i].metadata }; if (withObjectId && attsArray[i].object_id) { - entity[attsArray[i].name].object_id = attsArray[i].object_id; + entity[attsArray[i].name].object_id = attsArray[i].object_id; } } } @@ -99,30 +98,27 @@ function createNgsi2Entity(id, type, attsArray, withObjectId) { } function createProcessAttribute(fn, attributeType) { - return function(attribute) { - + return function (attribute) { if (attribute.type && attribute.type === attributeType) { attribute.value = fn(attribute.value); } if (config.checkNgsi2()) { - // This code is backwards compatible to process metadata in the older NGSIv1-style (array) - // as well as supporting the newer NGSIv2-style (object). The redundant Array Check can be + // This code is backwards compatible to process metadata in the older NGSIv1-style (array) + // as well as supporting the newer NGSIv2-style (object). The redundant Array Check can be // therefore be removed if/when NGSIv1 support is removed from the library. - if (Array.isArray (attribute.metadata)){ + if (Array.isArray(attribute.metadata)) { attribute.metadata = attribute.metadata.map(createProcessAttribute(fn, attributeType)); } else if (attribute.metadata) { - Object.keys(attribute.metadata).forEach(function(key) { - var entry = attribute.metadata[key]; - if(entry.type === 'DateTime'){ + Object.keys(attribute.metadata).forEach(function (key) { + const entry = attribute.metadata[key]; + if (entry.type === 'DateTime') { entry.value = fn(entry.value); } }); } - } else { - if (attribute.metadatas) { - attribute.metadatas = attribute.metadatas.map(createProcessAttribute(fn, attributeType)); - } + } else if (attribute.metadatas) { + attribute.metadatas = attribute.metadatas.map(createProcessAttribute(fn, attributeType)); } return attribute; @@ -140,16 +136,14 @@ function createProcessAttribute(fn, attributeType) { function createUpdateFilter(fn, attributeType) { return function update(entity, typeInformation, callback) { - function processEntityUpdateNgsi1(entity) { - entity.attributes = entity.attributes.map( - createProcessAttribute(fn, attributeType)); + entity.attributes = entity.attributes.map(createProcessAttribute(fn, attributeType)); return entity; } function processEntityUpdateNgsi2(entity) { - var attsArray = extractAttributesArrayFromNgsi2Entity(entity); + let attsArray = extractAttributesArrayFromNgsi2Entity(entity); attsArray = attsArray.map(createProcessAttribute(fn, attributeType)); entity = createNgsi2Entity(entity.id, entity.type, attsArray, true); return entity; @@ -177,13 +171,14 @@ function createQueryFilter(fn, attributeType) { return function query(entity, typeInformation, callback) { function processEntityQueryNgsi1(entity) { entity.contextElement.attributes = entity.contextElement.attributes.map( - createProcessAttribute(fn, attributeType)); + createProcessAttribute(fn, attributeType) + ); return entity; } function processEntityQueryNgsi2(entity) { - var attsArray = extractAttributesArrayFromNgsi2Entity(entity); + let attsArray = extractAttributesArrayFromNgsi2Entity(entity); attsArray = attsArray.map(createProcessAttribute(fn, attributeType)); entity = createNgsi2Entity(entity.id, entity.type, attsArray); return entity; diff --git a/lib/plugins/timestampProcessPlugin.js b/lib/plugins/timestampProcessPlugin.js index 83c21eb13..4ce004cf2 100644 --- a/lib/plugins/timestampProcessPlugin.js +++ b/lib/plugins/timestampProcessPlugin.js @@ -23,16 +23,16 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; +/* eslint-disable no-prototype-builtins */ -var errors = require('../errors'), - constants = require('../constants'), - logger = require('logops'), - context = { - op: 'IoTAgentNGSI.TimestampProcessPlugin' - }, - config = require('../commonConfig'), - utils = require('./pluginUtils'); +const errors = require('../errors'); +const constants = require('../constants'); +const logger = require('logops'); +const context = { + op: 'IoTAgentNGSI.TimestampProcessPlugin' +}; +const config = require('../commonConfig'); +const utils = require('./pluginUtils'); /** * Looks for Thinking Thing modules and parses them, updating the entity (NGSIv2) with the transformed value. @@ -40,12 +40,11 @@ var errors = require('../errors'), * @param {Object} entity NGSI Entity as it would have been sent before the plugin. */ function updatePluginNgsi2(entity, entityType, callback) { - var timestamp; + let timestamp; function insertMetadata(element) { - if (element.name !== constants.TIMESTAMP_ATTRIBUTE) { - var metadata = element.metadata || {}; + const metadata = element.metadata || {}; metadata[constants.TIMESTAMP_ATTRIBUTE] = { type: constants.TIMESTAMP_TYPE_NGSI2, value: timestamp.value @@ -57,7 +56,7 @@ function updatePluginNgsi2(entity, entityType, callback) { } function updateSingleEntity(entity) { - var attsArray = utils.extractAttributesArrayFromNgsi2Entity(entity); + let attsArray = utils.extractAttributesArrayFromNgsi2Entity(entity); if (entity && entity[constants.TIMESTAMP_ATTRIBUTE]) { if (entity.hasOwnProperty(constants.TIMESTAMP_ATTRIBUTE)) { @@ -77,14 +76,12 @@ function updatePluginNgsi2(entity, entityType, callback) { } if (entity instanceof Array) { - var results = entity.map(updateSingleEntity); + const results = entity.map(updateSingleEntity); callback(null, results, entityType); } else { - var newEntity = updateSingleEntity(entity); + const newEntity = updateSingleEntity(entity); callback(null, newEntity, entityType); } - - } /** @@ -93,22 +90,24 @@ function updatePluginNgsi2(entity, entityType, callback) { * @param {Object} entity NGSI Entity as it would have been sent before the plugin. */ function updatePluginNgsi1(entity, entityType, callback) { - var timestamp; + let timestamp; function insertMetadata(element) { if (element.name !== constants.TIMESTAMP_ATTRIBUTE) { - element.metadatas = [{ - name: constants.TIMESTAMP_ATTRIBUTE, - type: constants.TIMESTAMP_TYPE, - value: timestamp.value - }]; + element.metadatas = [ + { + name: constants.TIMESTAMP_ATTRIBUTE, + type: constants.TIMESTAMP_TYPE, + value: timestamp.value + } + ]; } return element; } if (entity.contextElements && entity.contextElements[0] && entity.contextElements[0].attributes) { - for (var i in entity.contextElements[0].attributes) { + for (const i in entity.contextElements[0].attributes) { if (entity.contextElements[0].attributes[i].name === constants.TIMESTAMP_ATTRIBUTE) { timestamp = entity.contextElements[0].attributes[i]; } @@ -123,7 +122,6 @@ function updatePluginNgsi1(entity, entityType, callback) { logger.error(context, 'Bad payload received while processing timestamps'); callback(new errors.WrongSyntax(entity)); } - } /** diff --git a/lib/services/commands/commandRegistryMemory.js b/lib/services/commands/commandRegistryMemory.js index b6d0d0ea6..b1948d044 100644 --- a/lib/services/commands/commandRegistryMemory.js +++ b/lib/services/commands/commandRegistryMemory.js @@ -20,43 +20,45 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; - -var registeredCommands = {}, - async = require('async'), - apply = async.apply, - logger = require('logops'), - intoTrans = require('../common/domain').intoTrans, - errors = require('../../errors'), - _ = require('underscore'), - context = { - op: 'IoTAgentNGSI.InMemoryCommandRegister' - }, - commandIds = 1; + +let registeredCommands = {}; +const async = require('async'); +const apply = async.apply; +const logger = require('logops'); +const intoTrans = require('../common/domain').intoTrans; +const errors = require('../../errors'); +const _ = require('underscore'); +const context = { + op: 'IoTAgentNGSI.InMemoryCommandRegister' +}; +let commandIds = 1; function findCommand(service, subservice, deviceId, name) { - var keys = Object.keys(registeredCommands).filter(function filterByCriteria(item) { - return registeredCommands[item].service === service && - registeredCommands[item].subservice === subservice && - registeredCommands[item].deviceId === deviceId, - registeredCommands[item].name === name; + const keys = Object.keys(registeredCommands).filter(function filterByCriteria(item) { + return ( + registeredCommands[item].service === service && + registeredCommands[item].subservice === subservice && + registeredCommands[item].deviceId === deviceId, + registeredCommands[item].name === name + ); }); if (keys.length === 1) { return registeredCommands[keys[0]]; - } else { - return null; } + return null; } function exists(service, subservice, deviceId, name) { - var keys = _.keys(registeredCommands); + const keys = _.keys(registeredCommands); - for (var i in keys) { - if (registeredCommands[keys[i]].service === service && + for (const i in keys) { + if ( + registeredCommands[keys[i]].service === service && registeredCommands[keys[i]].subservice === subservice && registeredCommands[keys[i]].name === name && - registeredCommands[keys[i]].deviceId === deviceId) { + registeredCommands[keys[i]].deviceId === deviceId + ) { return true; } } @@ -65,7 +67,7 @@ function exists(service, subservice, deviceId, name) { } function updateCommand(service, subservice, deviceId, command, callback) { - var foundCommand = findCommand(service, subservice, deviceId, command.name); + const foundCommand = findCommand(service, subservice, deviceId, command.name); if (foundCommand) { foundCommand.type = command.type; @@ -81,7 +83,7 @@ function addCommand(service, subservice, deviceId, command, callback) { if (exists(service, subservice, deviceId, command.name)) { updateCommand(service, subservice, deviceId, command, callback); } else { - var storeCommand = _.clone(command); + const storeCommand = _.clone(command); storeCommand._id = commandIds++; @@ -91,8 +93,14 @@ function addCommand(service, subservice, deviceId, command, callback) { registeredCommands[storeCommand._id].subservice = subservice; registeredCommands[storeCommand._id].deviceId = deviceId; - logger.debug(context, 'Storing device command [%s] for service [%s], subservice [%s] and deviceId [%s]', - command.name, storeCommand.service, storeCommand.subservice, deviceId); + logger.debug( + context, + 'Storing device command [%s] for service [%s], subservice [%s] and deviceId [%s]', + command.name, + storeCommand.service, + storeCommand.subservice, + deviceId + ); callback(null); } @@ -100,9 +108,11 @@ function addCommand(service, subservice, deviceId, command, callback) { function getFilteredCommands(service, subservice, deviceId) { return Object.keys(registeredCommands).filter(function filterByCriteria(item) { - return registeredCommands[item].service === service && + return ( + registeredCommands[item].service === service && registeredCommands[item].subservice === subservice && - registeredCommands[item].deviceId === deviceId; + registeredCommands[item].deviceId === deviceId + ); }); } @@ -114,10 +124,10 @@ function getFilteredCommands(service, subservice, deviceId) { * @param {Number} deviceId Id of the target device for the commands. */ function listCommands(service, subservice, deviceId, callback) { - var result = [], - filteredCommands = getFilteredCommands(service, subservice, deviceId); + const result = []; + const filteredCommands = getFilteredCommands(service, subservice, deviceId); - for (var i in filteredCommands) { + for (const i in filteredCommands) { result.push(registeredCommands[filteredCommands[i]]); } @@ -128,7 +138,7 @@ function listCommands(service, subservice, deviceId, callback) { } function remove(service, subservice, deviceId, name, callback) { - var foundCommand = findCommand(service, subservice, deviceId, name); + const foundCommand = findCommand(service, subservice, deviceId, name); if (foundCommand) { delete registeredCommands[foundCommand._id]; @@ -151,19 +161,22 @@ function getExpiredCommands(creationDate) { } function removeFromDate(creationDate, callback) { - var expiredCommands = getExpiredCommands(creationDate), - removalOrders = []; - - for (var i in expiredCommands) { - removalOrders.push(apply(remove, - registeredCommands[expiredCommands[i]].service, - registeredCommands[expiredCommands[i]].subservice, - registeredCommands[expiredCommands[i]].deviceId, - registeredCommands[expiredCommands[i]].name - )); + const expiredCommands = getExpiredCommands(creationDate); + const removalOrders = []; + + for (const i in expiredCommands) { + removalOrders.push( + apply( + remove, + registeredCommands[expiredCommands[i]].service, + registeredCommands[expiredCommands[i]].subservice, + registeredCommands[expiredCommands[i]].deviceId, + registeredCommands[expiredCommands[i]].name + ) + ); } - async.series(removalOrders, function(error) { + async.series(removalOrders, function (error) { if (error) { callback(error); } else { diff --git a/lib/services/commands/commandRegistryMongoDB.js b/lib/services/commands/commandRegistryMongoDB.js index 4d7d4b339..31efedc3a 100644 --- a/lib/services/commands/commandRegistryMongoDB.js +++ b/lib/services/commands/commandRegistryMongoDB.js @@ -20,32 +20,30 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; - -var logger = require('logops'), - dbService = require('../../model/dbConn'), - intoTrans = require('../common/domain').intoTrans, - errors = require('../../errors'), - Command = require('../../model/Command'), - async = require('async'), - context = { - op: 'IoTAgentNGSI.MongoDBCommandRegister' - }; + +const logger = require('logops'); +const dbService = require('../../model/dbConn'); +const intoTrans = require('../common/domain').intoTrans; +const errors = require('../../errors'); +const Command = require('../../model/Command'); +const async = require('async'); +const context = { + op: 'IoTAgentNGSI.MongoDBCommandRegister' +}; function findCommand(service, subservice, deviceId, name, callback) { - var query, - queryObj = { - service: service, - subservice: subservice, - deviceId: deviceId, - name: name - }; + const queryObj = { + service, + subservice, + deviceId, + name + }; logger.debug(context, 'Looking for command [%s] for device [%s]', name, deviceId); - query = Command.model.findOne(queryObj); + const query = Command.model.findOne(queryObj); - query.select({__v: 0}); + query.select({ __v: 0 }); query.exec(function handleGet(error, data) { if (error) { @@ -62,13 +60,13 @@ function findCommand(service, subservice, deviceId, name, callback) { } function updateCommand(service, subservice, deviceId, command, callback) { - findCommand(service, subservice, deviceId, command.name, function(error, commandDAO) { + findCommand(service, subservice, deviceId, command.name, function (error, commandDAO) { if (error) { callback(error); } else { commandDAO.value = command.value; - commandDAO.save(function(error) { + commandDAO.save(function (error) { callback(error, commandDAO.toObject()); }); } @@ -76,14 +74,11 @@ function updateCommand(service, subservice, deviceId, command, callback) { } function createCommand(service, subservice, deviceId, command, callback) { - var commandObj = new Command.model(), - attributeList = [ - 'name', - 'type', - 'value' - ]; - - for (var i = 0; i < attributeList.length; i++) { + /* eslint-disable-next-line new-cap */ + const commandObj = new Command.model(); + const attributeList = ['name', 'type', 'value']; + + for (let i = 0; i < attributeList.length; i++) { commandObj[attributeList[i]] = command[attributeList[i]]; } @@ -105,7 +100,7 @@ function createCommand(service, subservice, deviceId, command, callback) { } function addCommand(service, subservice, deviceId, command, callback) { - findCommand(service, subservice, deviceId, command.name, function(error) { + findCommand(service, subservice, deviceId, command.name, function (error) { if (error && error.name === 'COMMAND_NOT_FOUND') { createCommand(service, subservice, deviceId, command, callback); } else if (!error) { @@ -117,8 +112,7 @@ function addCommand(service, subservice, deviceId, command, callback) { } function listCommands(service, subservice, deviceId, callback) { - var condition = {}, - query; + const condition = {}; function toObjectFn(obj) { return obj.toObject(); @@ -128,12 +122,12 @@ function listCommands(service, subservice, deviceId, callback) { condition.subservice = subservice; condition.deviceId = deviceId; - query = Command.model.find(condition).sort(); + const query = Command.model.find(condition).sort(); - async.series([ - query.exec.bind(query), - Command.model.countDocuments.bind(Command.model, condition) - ], function(error, results) { + async.series([query.exec.bind(query), Command.model.countDocuments.bind(Command.model, condition)], function ( + error, + results + ) { callback(error, { count: results[1], commands: results[0].map(toObjectFn) @@ -142,14 +136,20 @@ function listCommands(service, subservice, deviceId, callback) { } function remove(service, subservice, deviceId, name, callback) { - logger.debug(context, 'Removing command for service [%s] subservice [%s] and DeviceID [%s] with name [%s]', - service, subservice, deviceId, name); - - findCommand(service, subservice, deviceId, name, function(error, command) { + logger.debug( + context, + 'Removing command for service [%s] subservice [%s] and DeviceID [%s] with name [%s]', + service, + subservice, + deviceId, + name + ); + + findCommand(service, subservice, deviceId, name, function (error, command) { if (error) { callback(error); } else { - Command.model.deleteOne({ _id: command._id }, function(error, commandResult) { + Command.model.deleteOne({ _id: command._id }, function (error, commandResult) { if (error) { logger.debug(context, 'Internal MongoDB Error getting command: %s', error); @@ -169,9 +169,9 @@ function remove(service, subservice, deviceId, name, callback) { } function listToObject(commandList) { - var result = []; + const result = []; - for (var i = 0; i < commandList.length; i++) { + for (let i = 0; i < commandList.length; i++) { result.push(commandList[i].toObject()); } @@ -179,19 +179,22 @@ function listToObject(commandList) { } function removeFromDate(creationDate, callback) { - var query = { creationDate: { $lt: creationDate } }; + const query = { creationDate: { $lt: creationDate } }; if (Command.model) { - Command.model.find(query).exec(function(error, commandList) { + Command.model.find(query).exec(function (error, commandList) { if (!error && commandList && commandList.length > 0) { - Command.model.deleteOne(query, function(error) { + Command.model.deleteOne(query, function (error) { if (error) { logger.debug(context, 'Internal MongoDB Error removing expired commands: %s', error); callback(new errors.InternalDbError(error)); } else { - logger.debug(context, 'Expired commands successfully removed from MongoDB for date [%s]', - creationDate); + logger.debug( + context, + 'Expired commands successfully removed from MongoDB for date [%s]', + creationDate + ); callback(null, listToObject(commandList)); } diff --git a/lib/services/commands/commandService.js b/lib/services/commands/commandService.js index 990079791..a1acc6d9a 100644 --- a/lib/services/commands/commandService.js +++ b/lib/services/commands/commandService.js @@ -21,20 +21,18 @@ * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; - -var intoTrans = require('../common/domain').intoTrans, - logger = require('logops'), - async = require('async'), - apply = async.apply, - config = require('../../commonConfig'), - constants = require('../../constants'), - ngsiService = require('../ngsi/ngsiService'), - deviceService = require('../devices/deviceService'), - daemonId, - context = { - op: 'IoTAgentNGSI.CommandService' - }; +const intoTrans = require('../common/domain').intoTrans; +const logger = require('logops'); +const async = require('async'); +const apply = async.apply; +const config = require('../../commonConfig'); +const constants = require('../../constants'); +const ngsiService = require('../ngsi/ngsiService'); +const deviceService = require('../devices/deviceService'); +let daemonId; +const context = { + op: 'IoTAgentNGSI.CommandService' +}; function listCommands(service, subservice, deviceId, callback) { logger.debug(context, 'Listing all commands for device [%s]', deviceId); @@ -64,26 +62,21 @@ function markAsExpired(command) { logger.debug('Marking command as expired: %j', command); function getGroup(device, callback) { - deviceService.findConfigurationGroup(device, function(error, group) { + deviceService.findConfigurationGroup(device, function (error, group) { callback(error, device, group); }); } function calculateTypeInformation(device, group, callback) { deviceService.mergeDeviceWithConfiguration( - [ - 'lazy', - 'active', - 'staticAttributes', - 'commands', - 'subscriptions' - ], + ['lazy', 'active', 'staticAttributes', 'commands', 'subscriptions'], [null, null, [], [], [], [], []], device, group, - function(error, typeInformation) { + function (error, typeInformation) { callback(error, device, group, typeInformation); - }); + } + ); } function updateExpiredCommand(device, group, typeInformation, callback) { @@ -95,28 +88,32 @@ function markAsExpired(command) { constants.COMMAND_EXPIRED_MESSAGE, constants.COMMAND_STATUS_ERROR, typeInformation, - callback); + callback + ); } - async.waterfall([ - apply(deviceService.getDevice, command.deviceId, command.service, command.subservice), - getGroup, - calculateTypeInformation, - updateExpiredCommand - ], function(error) { - if (error) { - logger.error(context, 'Error updating polling command to expire: %j', error); - } else { - logger.debug(context, 'Command successfully expired'); + async.waterfall( + [ + apply(deviceService.getDevice, command.deviceId, command.service, command.subservice), + getGroup, + calculateTypeInformation, + updateExpiredCommand + ], + function (error) { + if (error) { + logger.error(context, 'Error updating polling command to expire: %j', error); + } else { + logger.debug(context, 'Command successfully expired'); + } } - }); + ); } function expirationDaemon() { if (config.getConfig().pollingExpiration) { - config.getCommandRegistry().removeFromDate( - Date.now() - config.getConfig().pollingExpiration, - function(error, results) { + config + .getCommandRegistry() + .removeFromDate(Date.now() - config.getConfig().pollingExpiration, function (error, results) { logger.debug(context, 'Executed expiration daemon'); if (error) { diff --git a/lib/services/common/alarmManagement.js b/lib/services/common/alarmManagement.js index 622fb3b1d..fa6e18beb 100644 --- a/lib/services/common/alarmManagement.js +++ b/lib/services/common/alarmManagement.js @@ -20,13 +20,12 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; -var alarmRepository = {}, - logger = require('logops'), - context = { - op: 'IoTAgentNGSI.Alarms' - }; +let alarmRepository = {}; +const logger = require('logops'); +const context = { + op: 'IoTAgentNGSI.Alarms' +}; /** * Raises a new alarm with the provided data, if the alarm was not already risen. @@ -38,7 +37,7 @@ function raise(alarmName, description) { if (!alarmRepository[alarmName]) { alarmRepository[alarmName] = { name: alarmName, - description: description + description }; logger.error(context, 'Raising [%s]: %j', alarmName, description); @@ -92,9 +91,10 @@ function clean(callback) { */ function intercept(alarmName, targetFn) { function interceptCallback(callback) { - return function() { - var originalArguments = Array.prototype.slice.call(arguments), - error = originalArguments.slice(0, 1); + return function () { + /* eslint-disable-next-line prefer-rest-params */ + const originalArguments = Array.prototype.slice.call(arguments); + const error = originalArguments.slice(0, 1); if (error && error.length !== 0 && error[0]) { raise(alarmName, error[0]); @@ -106,9 +106,10 @@ function intercept(alarmName, targetFn) { }; } - return function() { - var originalArguments = Array.prototype.slice.call(arguments), - callback = originalArguments.splice(-1); + return function () { + /* eslint-disable-next-line prefer-rest-params */ + const originalArguments = Array.prototype.slice.call(arguments); + const callback = originalArguments.splice(-1); originalArguments.push(interceptCallback(callback[0])); diff --git a/lib/services/common/domain.js b/lib/services/common/domain.js index 774ee0d8b..464c5b699 100644 --- a/lib/services/common/domain.js +++ b/lib/services/common/domain.js @@ -21,28 +21,25 @@ * please contact with::[iot_support@tid.es] */ -'use strict'; - -var domain = require('domain'), - constants = require('../../constants'), - uuid = require('uuid'), - logger = require('logops'), - context = { - op: 'IoTAgentNGSI.DomainControl' - }; +const domain = require('domain'); +const constants = require('../../constants'); +const uuid = require('uuid'); +const logger = require('logops'); +const context = { + op: 'IoTAgentNGSI.DomainControl' +}; -var CORRELATOR_HEADER = 'Fiware-Correlator'; +const CORRELATOR_HEADER = 'Fiware-Correlator'; function getDomainTransaction() { if (domain.active && domain.active.trans) { return domain.active.trans; - } else { - return uuid.v4(); } + return uuid.v4(); } function cleanDomain(domainToClean) { - var responseTime = Date.now() - domainToClean.start; + const responseTime = Date.now() - domainToClean.start; logger.debug(context, 'response-time: ' + responseTime); domainToClean.removeAllListeners('error'); delete domainToClean.trans; @@ -65,7 +62,7 @@ function generateDomainErrorHandler(domainToHandle) { * It also generates a unique request id that can be used to track requests in logs. */ function requestDomain(req, res, next) { - var reqDomain = domain.create(); + const reqDomain = domain.create(); reqDomain.path = req.path; reqDomain.op = req.url; reqDomain.start = Date.now(); @@ -93,8 +90,9 @@ function requestDomain(req, res, next) { } function requestHandler() { - var corr = req.get(CORRELATOR_HEADER); + const corr = req.get(CORRELATOR_HEADER); + /* eslint-disable-next-line no-multi-assign */ reqDomain.trans = req.requestId = getDomainTransaction(); if (corr) { reqDomain.corr = corr; @@ -121,7 +119,7 @@ function requestDomain(req, res, next) { * @return {Object} Return value of the callback function, if any. */ function ensureSouthboundTransaction(context, callback) { - var reqDomain; + let reqDomain; if (!callback && typeof context === 'function') { callback = context; @@ -165,8 +163,9 @@ function ensureSouthboundTransaction(context, callback) { * @return {Function} New function executing the old one with the context. */ function intoTransaction(context, fn) { - return function() { - var originalArguments = arguments; + return function () { + /* eslint-disable-next-line prefer-rest-params */ + const originalArguments = arguments; function expandedFunction() { return fn.apply(fn, originalArguments); @@ -212,26 +211,26 @@ function fillService(context, data) { * It also generates a unique request id that can be used to track requests in logs. */ -function regenerateTransid(data){ - var reqDomain = domain.create(); +function regenerateTransid(data) { + const reqDomain = domain.create(); reqDomain.path = data; reqDomain.op = data; reqDomain.start = Date.now(); - + function requestHandler() { - var corr = false; - reqDomain.trans = getDomainTransaction(); + const corr = false; + reqDomain.trans = getDomainTransaction(); if (corr) { reqDomain.corr = corr; } else { reqDomain.corr = reqDomain.trans; } } - + reqDomain.on('error', generateDomainErrorHandler(reqDomain)); reqDomain.enter(); reqDomain.run(requestHandler); - } +} exports.ensureSouthboundDomain = ensureSouthboundTransaction; exports.finishSouthBoundTransaction = finishSouthboundTransaction; diff --git a/lib/services/common/genericMiddleware.js b/lib/services/common/genericMiddleware.js index 0b79198a3..3c61d46f1 100644 --- a/lib/services/common/genericMiddleware.js +++ b/lib/services/common/genericMiddleware.js @@ -21,15 +21,13 @@ * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; - -var logger = require('logops'), - revalidator = require('revalidator'), - errors = require('../../errors'), - iotaInformation, - context = { - op: 'IoTAgentNGSI.GenericMiddlewares' - }; +const logger = require('logops'); +const revalidator = require('revalidator'); +const errors = require('../../errors'); +let iotaInformation; +const context = { + op: 'IoTAgentNGSI.GenericMiddlewares' +}; /** * Express middleware for handling errors in the IoTAs. It extracts the code information to return from the error itself @@ -37,8 +35,10 @@ var logger = require('logops'), * * @param {Object} error Error object with all the information. */ + +/* eslint-disable-next-line no-unused-vars */ function handleError(error, req, res, next) { - var code = 500; + let code = 500; logger.debug(context, 'Error [%s] handling request: %s', error.name, error.message); @@ -68,8 +68,10 @@ function traceRequest(req, res, next) { /** * Changes the log level to the one specified in the request. */ + +/* eslint-disable-next-line no-unused-vars */ function changeLogLevel(req, res, next) { - var levels = ['INFO', 'ERROR', 'FATAL', 'DEBUG', 'WARNING']; + const levels = ['INFO', 'ERROR', 'FATAL', 'DEBUG', 'WARNING']; if (!req.query.level) { res.status(400).json({ @@ -88,6 +90,8 @@ function changeLogLevel(req, res, next) { /** * Return the current log level. */ + +/* eslint-disable-next-line no-unused-vars */ function getLogLevel(req, res, next) { res.status(200).json({ level: logger.getLevel() @@ -114,7 +118,7 @@ function ensureType(req, res, next) { function validateJson(template) { return function validate(req, res, next) { if (req.is('json')) { - var errorList = revalidator.validate(req.body, template); + const errorList = revalidator.validate(req.body, template); if (errorList.valid) { next(); @@ -131,6 +135,8 @@ function validateJson(template) { /** * Middleware that returns all the IoTA information stored in the module. */ + +/* eslint-disable-next-line no-unused-vars */ function retrieveVersion(req, res, next) { res.status(200).json(iotaInformation); } diff --git a/lib/services/common/iotManagerService.js b/lib/services/common/iotManagerService.js index a18578a4a..ad61a6108 100644 --- a/lib/services/common/iotManagerService.js +++ b/lib/services/common/iotManagerService.js @@ -23,26 +23,23 @@ * Modified by: Federico M. Facca - Martel Innovate */ -'use strict'; - -var request = require('request'), - async = require('async'), - errors = require('../../errors'), - constants = require('../../constants'), - config = require('../../commonConfig'), - intoTrans = require('../common/domain').intoTrans, - alarms = require('../common/alarmManagement'), - logger = require('logops'), - context = { - op: 'IoTAgentNGSI.IOTAMService' - }; +const request = require('request'); +const async = require('async'); +const errors = require('../../errors'); +const constants = require('../../constants'); +const config = require('../../commonConfig'); +const intoTrans = require('../common/domain').intoTrans; +const alarms = require('../common/alarmManagement'); +const logger = require('logops'); +const context = { + op: 'IoTAgentNGSI.IOTAMService' +}; /** * Sends the registration to the IoT Agent Manager if it is configured in the config file. */ function register(callback) { function adaptServiceInformation(service) { - /* jshint camelcase: false */ return { apikey: service.apikey, token: service.trust, @@ -64,7 +61,7 @@ function register(callback) { } function getServices(callback) { - config.getGroupRegistry().list(null, null, null, function(error, results) { + config.getGroupRegistry().list(null, null, null, function (error, results) { if (error) { callback(error); } else { @@ -74,20 +71,20 @@ function register(callback) { } function sendRegistration(services, callback) { - var resource = constants.DEFAULT_RESOURCE; + let resource = constants.DEFAULT_RESOURCE; // Use an Undefined check since defaultResource override could be blank. - if (config.getConfig().defaultResource !== undefined){ + if (config.getConfig().defaultResource !== undefined) { resource = config.getConfig().defaultResource; } - var options = { + const options = { url: config.getConfig().iotManager.url + config.getConfig().iotManager.path, method: 'POST', json: { protocol: config.getConfig().iotManager.protocol, description: config.getConfig().iotManager.description, iotagent: config.getConfig().providerUrl + (config.getConfig().iotManager.agentPath || ''), - resource: resource, - services: services + resource, + services } }; @@ -100,8 +97,11 @@ function register(callback) { if (result.statusCode !== 200 && result.statusCode !== 201) { alarms.raise(constants.IOTAM_ALARM, 'Wrong status code connecting with the IoTAM'); - logger.error(context, 'IOTAM-001: Error updating information in the IOTAM. Status Code [%d]', - result.statusCode); + logger.error( + context, + 'IOTAM-001: Error updating information in the IOTAM. Status Code [%d]', + result.statusCode + ); } else { alarms.release(constants.IOTAM_ALARM); } @@ -110,14 +110,14 @@ function register(callback) { } function checkConfiguration(callback) { - var attributes = ['protocol', 'description'], - missing = []; + const attributes = ['protocol', 'description']; + const missing = []; if (!config.getConfig().providerUrl) { missing.push('providerUrl'); } - for (var i in attributes) { + for (const i in attributes) { if (!config.getConfig().iotManager[attributes[i]]) { missing.push(attributes[i]); } @@ -131,22 +131,20 @@ function register(callback) { } if (config.getConfig().iotManager) { - async.waterfall([ - checkConfiguration, - getServices, - sendRegistration, - handleRegistration - ], function registerHandler(error) { - if (error) { - logger.error(context, 'Error connecting to IoT Manager: %j', error); - - alarms.raise(constants.IOTAM_ALARM, 'Unknown error connecting with the IoTAM'); - - callback(error); - } else { - callback(); + async.waterfall( + [checkConfiguration, getServices, sendRegistration, handleRegistration], + function registerHandler(error) { + if (error) { + logger.error(context, 'Error connecting to IoT Manager: %j', error); + + alarms.raise(constants.IOTAM_ALARM, 'Unknown error connecting with the IoTAM'); + + callback(error); + } else { + callback(); + } } - }); + ); } else { callback(); } diff --git a/lib/services/common/securityServiceKeystone.js b/lib/services/common/securityServiceKeystone.js index c48a2e942..dded788c2 100644 --- a/lib/services/common/securityServiceKeystone.js +++ b/lib/services/common/securityServiceKeystone.js @@ -1,4 +1,3 @@ - /* * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U * @@ -22,17 +21,14 @@ * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; - -var request = require('request'), - errors = require('../../errors'), - config = require('../../commonConfig'), - intoTrans = require('../common/domain').intoTrans, - logger = require('logops'), - context = { - op: 'IoTAgentNGSI.SecurityService' - }; - +const request = require('request'); +const errors = require('../../errors'); +const config = require('../../commonConfig'); +const intoTrans = require('../common/domain').intoTrans; +const logger = require('logops'); +const context = { + op: 'IoTAgentNGSI.SecurityService' +}; /** * Send a request to the Authorization Server to retrieve a token using the given trust. @@ -40,16 +36,13 @@ var request = require('request'), * @param {String} trust Trust generated in Keystone to act on behalf of a user. */ function auth(trust, callback) { - var options = { - url: config.getConfig().authentication.url + - '/v3/auth/tokens', + const options = { + url: config.getConfig().authentication.url + '/v3/auth/tokens', method: 'POST', json: { auth: { identity: { - methods: [ - 'password' - ], + methods: ['password'], password: { user: { domain: { @@ -71,6 +64,7 @@ function auth(trust, callback) { logger.debug(context, 'Authentication with Keystone using trust [%s]', trust); + /* eslint-disable-next-line no-unused-vars */ request(options, function handleResponse(error, response, body) { if (error) { logger.error(context, 'KEYSTONE-001: Error retrieving token from Keystone: %s', error); @@ -83,8 +77,13 @@ function auth(trust, callback) { callback(new errors.AuthenticationError(trust)); } else { logger.error(context, 'KEYSTONE-002: Unexpected status code: %d', response.statusCode); - callback(new errors.TokenRetrievalError( - trust, 'Unexpected status code retrieving token: %d', response.statusCode)); + callback( + new errors.TokenRetrievalError( + trust, + 'Unexpected status code retrieving token: %d', + response.statusCode + ) + ); } }); } @@ -96,7 +95,6 @@ function auth(trust, callback) { */ function getToken(trust, response, callback) { - logger.debug(context, 'Retrieving token from the KEYSTONE response'); if (response.headers['x-subject-token']) { @@ -105,8 +103,7 @@ function getToken(trust, response, callback) { callback(null, response.headers['x-subject-token']); } else { logger.error(context, 'KEYSTONE-003: Token missing in the response headers', response.headers); - callback(new errors.TokenRetrievalError( - trust, 'Unexpected response format', response.headers)); + callback(new errors.TokenRetrievalError(trust, 'Unexpected response format', response.headers)); } } diff --git a/lib/services/common/securityServiceOAuth2.js b/lib/services/common/securityServiceOAuth2.js index 3a3bcafdf..31c548cc9 100644 --- a/lib/services/common/securityServiceOAuth2.js +++ b/lib/services/common/securityServiceOAuth2.js @@ -1,4 +1,3 @@ - /* * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U * @@ -25,47 +24,45 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var request = require('request'), - queryString = require('query-string'), - errors = require('../../errors'), - config = require('../../commonConfig'), - intoTrans = require('../common/domain').intoTrans, - logger = require('logops'), - context = { - op: 'IoTAgentNGSI.SecurityService' - }; +/* eslint-disable consistent-return */ +const request = require('request'); +const queryString = require('query-string'); +const errors = require('../../errors'); +const config = require('../../commonConfig'); +const intoTrans = require('../common/domain').intoTrans; +const logger = require('logops'); +const context = { + op: 'IoTAgentNGSI.SecurityService' +}; /** * Send a request to the Authorization Server. * * @param {String} trust refresh_token for the OAuth2 provider to act on behalf of a user. */ -/* jshint camelcase: false */ -function auth(trust, callback) { +function auth(trust, callback) { if (config.getConfig().authentication.permanentToken) { return callback(null, trust); } - var form = { - grant_type: 'refresh_token', - client_id: config.getConfig().authentication.clientId, - client_secret: config.getConfig().authentication.clientSecret, - refresh_token: trust + const form = { + grant_type: 'refresh_token', + client_id: config.getConfig().authentication.clientId, + client_secret: config.getConfig().authentication.clientSecret, + refresh_token: trust }; - var formData = queryString.stringify(form); - var url = config.getConfig().authentication.url + config.getConfig().authentication.tokenPath; + const formData = queryString.stringify(form); + const url = config.getConfig().authentication.url + config.getConfig().authentication.tokenPath; - var options = { - url: url, + const options = { + url, method: 'POST', headers: { - 'Content-Length': formData.length, - 'Content-Type': 'application/x-www-form-urlencoded' + 'Content-Length': formData.length, + 'Content-Type': 'application/x-www-form-urlencoded' }, body: formData }; @@ -78,25 +75,35 @@ function auth(trust, callback) { callback(new errors.TokenRetrievalError(trust, error)); } else if (response.statusCode === 201 || response.statusCode === 200 /* Keyrock response */) { logger.debug(context, 'Authentication with trust [%s] was succesful', trust); - logger.debug(context, - 'Received the following response from the OAuth2 provider:\n\n%s\n\n', JSON.stringify(body, null, 4)); + logger.debug( + context, + 'Received the following response from the OAuth2 provider:\n\n%s\n\n', + JSON.stringify(body, null, 4) + ); callback(null, response); - } else if (response.statusCode === 401 || (response.statusCode === 400 && - JSON.parse(response.body).error_description === 'Invalid refresh token')) { + } else if ( + response.statusCode === 401 || + (response.statusCode === 400 && JSON.parse(response.body).error_description === 'Invalid refresh token') + ) { logger.error(context, 'Authentication rejected: %s', trust); callback(new errors.AuthenticationError(trust)); - } else if (response.statusCode === 400 && - JSON.parse(response.body).error === 'invalid_client') { //Keyrock response + } else if (response.statusCode === 400 && JSON.parse(response.body).error === 'invalid_client') { + //Keyrock response logger.error(context, 'Authentication rejected: %s', trust); callback(new errors.AuthenticationError(trust)); - } else if (response.statusCode === 400 && - JSON.parse(response.body).error === 'invalid_grant') { //Keyrock response + } else if (response.statusCode === 400 && JSON.parse(response.body).error === 'invalid_grant') { + //Keyrock response logger.error(context, 'Authentication rejected: %s', trust); callback(new errors.AuthenticationError(trust)); } else { logger.error(context, 'OAUTH2-002: Unexpected status code: %d', response.statusCode); - callback(new errors.TokenRetrievalError( - trust, 'Unexpected status code retrieving token: %d', response.statusCode)); + callback( + new errors.TokenRetrievalError( + trust, + 'Unexpected status code retrieving token: %d', + response.statusCode + ) + ); } }); } @@ -106,16 +113,15 @@ function auth(trust, callback) { * @param {String} trust refresh_token for the OAuth2 provider to act on behalf of a user. * @param {String} response The authentication response */ -/* jshint camelcase: false */ -function getToken(trust, response, callback) { +function getToken(trust, response, callback) { logger.debug(context, 'Retrieving token from the OAuth2 response'); if (config.getConfig().authentication.permanentToken) { return callback(null, 'Bearer ' + trust); } - var body = JSON.parse(response.body); + const body = JSON.parse(response.body); if (body.access_token) { logger.debug(context, 'Token found [%s] for trust [%s]', body.access_token, trust); @@ -123,8 +129,7 @@ function getToken(trust, response, callback) { callback(null, 'Bearer ' + body.access_token); } else { logger.error(context, 'OAUTH2-003: Token missing in the response body', body); - callback(new errors.TokenRetrievalError( - trust, 'Unexpected response format', body)); + callback(new errors.TokenRetrievalError(trust, 'Unexpected response format', body)); } } diff --git a/lib/services/devices/deviceRegistryMemory.js b/lib/services/devices/deviceRegistryMemory.js index ea78091e2..90c456045 100644 --- a/lib/services/devices/deviceRegistryMemory.js +++ b/lib/services/devices/deviceRegistryMemory.js @@ -21,18 +21,20 @@ * please contact with::daniel.moranjimenez@telefonica.com */ -var registeredDevices = {}, - logger = require('logops'), - errors = require('../../errors'), - _ = require('underscore'), - context = { - op: 'IoTAgentNGSI.InMemoryDeviceRegister' - }; +/* eslint-disable no-prototype-builtins */ + +let registeredDevices = {}; +const logger = require('logops'); +const errors = require('../../errors'); +const _ = require('underscore'); +const context = { + op: 'IoTAgentNGSI.InMemoryDeviceRegister' +}; function deepClone(device) { - var initialClone = _.clone(device); + const initialClone = _.clone(device); - for (var i in device) { + for (const i in device) { if (device.hasOwnProperty(i) && Array.isArray(device[i])) { initialClone[i] = device[i].map(_.clone); } @@ -70,9 +72,9 @@ function storeDevice(newDevice, callback) { * @param {String} subservice Subservice inside the service for the removed device. */ function removeDevice(id, service, subservice, callback) { - var services = Object.keys(registeredDevices); + const services = Object.keys(registeredDevices); - for (var i = 0; i < services.length; i++) { + for (let i = 0; i < services.length; i++) { if (registeredDevices[services[i]][id]) { logger.debug(context, 'Removing device with id [%s] from service [%s].', id, services[i]); delete registeredDevices[services[i]][id]; @@ -94,13 +96,11 @@ function getDevicesByService(service, subservice) { return Object.keys(registeredDevices[service]).filter(function filterByService(item) { if (subservice) { return registeredDevices[service][item].subservice === subservice; - } else { - return true; } + return true; }); - } else { - return []; } + return []; } /** @@ -112,16 +112,16 @@ function getDevicesByService(service, subservice) { * @param {Number} offset Number of entries to skip for pagination. */ function listDevices(type, service, subservice, limit, offset, callback) { - var result = [], - skipped = 0, - deviceList = getDevicesByService(service, subservice); - - var countNumber = deviceList.length; - for (var i in deviceList) { + const result = []; + let skipped = 0; + const deviceList = getDevicesByService(service, subservice); + + let countNumber = deviceList.length; + for (const i in deviceList) { if (registeredDevices[service].hasOwnProperty(deviceList[i])) { if (offset && skipped < parseInt(offset, 10)) { skipped++; - } else if (type && registeredDevices[service][deviceList[i]].type === type){ + } else if (type && registeredDevices[service][deviceList[i]].type === type) { result.push(registeredDevices[service][deviceList[i]]); } else if (type) { countNumber--; @@ -150,10 +150,10 @@ function getDevice(id, service, subservice, callback) { } function getByName(name, service, subservice, callback) { - var devices = _.values(registeredDevices[service]), - device; + const devices = _.values(registeredDevices[service]); + let device; - for (var i = 0; i < devices.length; i++) { + for (let i = 0; i < devices.length; i++) { if (devices[i].name === name) { device = devices[i]; } @@ -178,8 +178,8 @@ function clear(callback) { } function getDevicesByAttribute(name, value, service, subservice, callback) { - var devices, - resultDevices = []; + let devices; + const resultDevices = []; if (service) { devices = _.values(registeredDevices[service]); @@ -187,7 +187,7 @@ function getDevicesByAttribute(name, value, service, subservice, callback) { devices = _.flatten(_.values(registeredDevices).map(_.values)); } - for (var i = 0; i < devices.length; i++) { + for (let i = 0; i < devices.length; i++) { if (devices[i][name] === value) { resultDevices.push(devices[i]); } diff --git a/lib/services/devices/deviceRegistryMongoDB.js b/lib/services/devices/deviceRegistryMongoDB.js index d94e8c73e..9cd812dcd 100644 --- a/lib/services/devices/deviceRegistryMongoDB.js +++ b/lib/services/devices/deviceRegistryMongoDB.js @@ -21,18 +21,18 @@ * please contact with::daniel.moranjimenez@telefonica.com */ -var logger = require('logops'), - dbService = require('../../model/dbConn'), - config = require('../../commonConfig'), - fillService = require('./../common/domain').fillService, - alarmsInt = require('../common/alarmManagement').intercept, - errors = require('../../errors'), - constants = require('../../constants'), - Device = require('../../model/Device'), - async = require('async'), - context = { - op: 'IoTAgentNGSI.MongoDBDeviceRegister' - }; +const logger = require('logops'); +const dbService = require('../../model/dbConn'); +const config = require('../../commonConfig'); +const fillService = require('./../common/domain').fillService; +const alarmsInt = require('../common/alarmManagement').intercept; +const errors = require('../../errors'); +const constants = require('../../constants'); +const Device = require('../../model/Device'); +const async = require('async'); +let context = { + op: 'IoTAgentNGSI.MongoDBDeviceRegister' +}; /** * Generates a handler for the save device operations. The handler will take the customary error and the saved device @@ -58,17 +58,38 @@ function saveDeviceHandler(callback) { * @param {Object} newDevice Device object to be stored */ function storeDevice(newDevice, callback) { - var deviceObj = new Device.model(), - attributeList = ['id', 'type', 'name', 'service', 'subservice', 'lazy', 'commands', 'staticAttributes', - 'active', 'registrationId', 'internalId', 'internalAttributes', 'resource', 'apikey', 'protocol', - 'endpoint', 'transport', 'polling', 'timestamp', 'autoprovision', 'explicitAttrs', 'expressionLanguage']; - - for (var i = 0; i < attributeList.length; i++) { + const deviceObj = new Device.model(); // eslint-disable-line new-cap + const attributeList = [ + 'id', + 'type', + 'name', + 'service', + 'subservice', + 'lazy', + 'commands', + 'staticAttributes', + 'active', + 'registrationId', + 'internalId', + 'internalAttributes', + 'resource', + 'apikey', + 'protocol', + 'endpoint', + 'transport', + 'polling', + 'timestamp', + 'autoprovision', + 'explicitAttrs', + 'expressionLanguage' + ]; + + for (let i = 0; i < attributeList.length; i++) { deviceObj[attributeList[i]] = newDevice[attributeList[i]]; } // Ensure protocol is in newDevice - if ( !newDevice.protocol && config.getConfig().iotManager && config.getConfig().iotManager.protocol) { + if (!newDevice.protocol && config.getConfig().iotManager && config.getConfig().iotManager.protocol) { deviceObj.protocol = config.getConfig().iotManager.protocol; } @@ -99,15 +120,15 @@ function storeDevice(newDevice, callback) { * @param {String} subservice Subservice inside the service for the removed device. */ function removeDevice(id, service, subservice, callback) { - var condition = { - id: id, - service: service, - subservice: subservice + const condition = { + id, + service, + subservice }; logger.debug(context, 'Removing device with id [%s]', id); - Device.model.deleteOne(condition, function(error) { + Device.model.deleteOne(condition, function (error) { if (error) { logger.debug(context, 'Internal MongoDB Error getting device: %s', error); @@ -130,8 +151,7 @@ function removeDevice(id, service, subservice, callback) { * @param {Number} offset Number of entries to skip for pagination. */ function listDevices(type, service, subservice, limit, offset, callback) { - var condition = {}, - query; + const condition = {}; if (type) { condition.type = type; @@ -145,7 +165,7 @@ function listDevices(type, service, subservice, limit, offset, callback) { condition.subservice = subservice; } - query = Device.model.find(condition).sort(); + const query = Device.model.find(condition).sort(); if (limit) { query.limit(parseInt(limit, 10)); @@ -155,10 +175,10 @@ function listDevices(type, service, subservice, limit, offset, callback) { query.skip(parseInt(offset, 10)); } - async.series([ - query.exec.bind(query), - Device.model.countDocuments.bind(Device.model, condition) - ], function(error, results) { + async.series([query.exec.bind(query), Device.model.countDocuments.bind(Device.model, condition)], function ( + error, + results + ) { callback(error, { count: results[1], devices: results[0] @@ -174,17 +194,16 @@ function listDevices(type, service, subservice, limit, offset, callback) { * @param {String} subservice Division inside the service (optional). */ function getDeviceById(id, service, subservice, callback) { - var query, - queryParams = { - id: id, - service: service, - subservice: subservice - }; + const queryParams = { + id, + service, + subservice + }; context = fillService(context, queryParams); logger.debug(context, 'Looking for device with id [%s].', id); - query = Device.model.findOne(queryParams); - query.select({__v: 0}); + const query = Device.model.findOne(queryParams); + query.select({ __v: 0 }); query.exec(function handleGet(error, data) { if (error) { @@ -211,8 +230,7 @@ function getDeviceById(id, service, subservice, callback) { * @param {String} subservice Division inside the service. */ function getDevice(id, service, subservice, callback) { - - getDeviceById(id, service, subservice, function(error, data) { + getDeviceById(id, service, subservice, function (error, data) { if (error) { callback(error); } else { @@ -222,17 +240,16 @@ function getDevice(id, service, subservice, callback) { } function getByName(name, service, servicepath, callback) { - var query; - context = fillService(context, { service: service, subservice: servicepath}); + context = fillService(context, { service, subservice: servicepath }); logger.debug(context, 'Looking for device with name [%s].', name); - query = Device.model.findOne({ - name: name, - service: service, + const query = Device.model.findOne({ + name, + service, subservice: servicepath }); - query.select({__v: 0}); + query.select({ __v: 0 }); query.exec(function handleGet(error, data) { if (error) { @@ -256,7 +273,7 @@ function getByName(name, service, servicepath, callback) { * @param {Object} device Device object with the new values to write. */ function update(device, callback) { - getDeviceById(device.id, device.service, device.subservice, function(error, data) { + getDeviceById(device.id, device.service, device.subservice, function (error, data) { if (error) { callback(error); } else { @@ -285,14 +302,12 @@ function clear(callback) { function itemToObject(i) { if (i.toObject) { return i.toObject(); - } else { - return i; } + return i; } function getDevicesByAttribute(name, value, service, subservice, callback) { - var query, - filter = {}; + const filter = {}; if (service) { filter.service = service; @@ -306,8 +321,8 @@ function getDevicesByAttribute(name, value, service, subservice, callback) { context = fillService(context, filter); logger.debug(context, 'Looking for device with filter [%j].', filter); - query = Device.model.find(filter); - query.select({__v: 0}); + const query = Device.model.find(filter); + query.select({ __v: 0 }); query.exec(function handleGet(error, devices) { if (error) { diff --git a/lib/services/devices/deviceService.js b/lib/services/devices/deviceService.js index dcda986e4..5d906722b 100644 --- a/lib/services/devices/deviceService.js +++ b/lib/services/devices/deviceService.js @@ -24,30 +24,33 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var request = require('request'), - async = require('async'), - apply = async.apply, - uuid = require('uuid'), - constants = require('../../constants'), - domain = require('domain'), - intoTrans = require('../common/domain').intoTrans, - alarms = require('../common/alarmManagement'), - groupService = require('../groups/groupService'), - ngsiService = require('../ngsi/ngsiService'), - errors = require('../../errors'), - logger = require('logops'), - config = require('../../commonConfig'), - ngsiParser = require('./../ngsi/ngsiParser'), - registrationUtils = require('./registrationUtils'), - subscriptions = require('../ngsi/subscriptionService'), - _ = require('underscore'), - utils = require('../northBound/restUtils'), - moment = require('moment'), - context = { - op: 'IoTAgentNGSI.DeviceService' - }; +/* eslint-disable no-prototype-builtins */ +/* eslint-disable prefer-spread */ +/* eslint-disable prefer-rest-params */ +/* eslint-disable consistent-return */ + +const request = require('request'); +const async = require('async'); +const apply = async.apply; +const uuid = require('uuid'); +const constants = require('../../constants'); +const domain = require('domain'); +const intoTrans = require('../common/domain').intoTrans; +const alarms = require('../common/alarmManagement'); +const groupService = require('../groups/groupService'); +const ngsiService = require('../ngsi/ngsiService'); +const errors = require('../../errors'); +const logger = require('logops'); +const config = require('../../commonConfig'); +const ngsiParser = require('./../ngsi/ngsiParser'); +const registrationUtils = require('./registrationUtils'); +const subscriptions = require('../ngsi/subscriptionService'); +const _ = require('underscore'); +const utils = require('../northBound/restUtils'); +const moment = require('moment'); +const context = { + op: 'IoTAgentNGSI.DeviceService' +}; /** * Process the response from a Register Context request for a device, extracting the 'registrationId' and creating the @@ -57,7 +60,7 @@ var request = require('request'), * */ function processContextRegistration(deviceData, body, callback) { - var newDevice = _.clone(deviceData); + const newDevice = _.clone(deviceData); if (body) { newDevice.registrationId = body.registrationId; @@ -78,14 +81,17 @@ function processContextRegistration(deviceData, body, callback) { function createInitialEntityHandlerNgsi1(deviceData, newDevice, callback) { return function handleInitialEntityResponse(error, response, body) { if (error) { - logger.error(context, - 'ORION-001: Connection error creating inital entity in the Context Broker: %s', error); + logger.error( + context, + 'ORION-001: Connection error creating inital entity in the Context Broker: %s', + error + ); alarms.raise(constants.ORION_ALARM, error); callback(error); } else if (response && body && response.statusCode === 200) { - var errorField = ngsiParser.getErrorField(body); + const errorField = ngsiParser.getErrorField(body); if (errorField) { logger.error(context, 'Update error connecting to the Context Broker: %j', errorField); @@ -96,12 +102,14 @@ function createInitialEntityHandlerNgsi1(deviceData, newDevice, callback) { callback(null, newDevice); } } else { - var errorObj; - - logger.error(context, - 'Protocol error connecting to the Context Broker [%d]: %s', response.statusCode, body); + logger.error( + context, + 'Protocol error connecting to the Context Broker [%d]: %s', + response.statusCode, + body + ); - errorObj = new errors.EntityGenericError(deviceData.id, deviceData.type, body); + const errorObj = new errors.EntityGenericError(deviceData.id, deviceData.type, body); callback(errorObj); } @@ -120,8 +128,11 @@ function createInitialEntityHandlerNgsi1(deviceData, newDevice, callback) { function createInitialEntityHandlerNgsi2(deviceData, newDevice, callback) { return function handleInitialEntityResponse(error, response, body) { if (error) { - logger.error(context, - 'ORION-001: Connection error creating inital entity in the Context Broker: %s', error); + logger.error( + context, + 'ORION-001: Connection error creating inital entity in the Context Broker: %s', + error + ); alarms.raise(constants.ORION_ALARM, error); @@ -131,12 +142,14 @@ function createInitialEntityHandlerNgsi2(deviceData, newDevice, callback) { logger.debug(context, 'Initial entity created successfully.'); callback(null, newDevice); } else { - var errorObj; - - logger.error(context, - 'Protocol error connecting to the Context Broker [%d]: %s', response.statusCode, body); + logger.error( + context, + 'Protocol error connecting to the Context Broker [%d]: %s', + response.statusCode, + body + ); - errorObj = new errors.EntityGenericError(deviceData.id, deviceData.type, body); + const errorObj = new errors.EntityGenericError(deviceData.id, deviceData.type, body); callback(errorObj); } @@ -154,8 +167,11 @@ function createInitialEntityHandlerNgsi2(deviceData, newDevice, callback) { function updateEntityHandlerNgsi2(deviceData, updatedDevice, callback) { return function handleEntityResponse(error, response, body) { if (error) { - logger.error(context, - 'ORION-001: Connection error creating inital entity in the Context Broker: %s', error); + logger.error( + context, + 'ORION-001: Connection error creating inital entity in the Context Broker: %s', + error + ); alarms.raise(constants.ORION_ALARM, error); @@ -165,12 +181,14 @@ function updateEntityHandlerNgsi2(deviceData, updatedDevice, callback) { logger.debug(context, 'Entity updated successfully.'); callback(null, updatedDevice); } else { - var errorObj; + logger.error( + context, + 'Protocol error connecting to the Context Broker [%d]: %s', + response.statusCode, + body + ); - logger.error(context, - 'Protocol error connecting to the Context Broker [%d]: %s', response.statusCode, body); - - errorObj = new errors.EntityGenericError(deviceData.id, deviceData.type, body); + const errorObj = new errors.EntityGenericError(deviceData.id, deviceData.type, body); callback(errorObj); } @@ -195,7 +213,7 @@ function getInitialValueForType(type) { * @param {Object} json2 JSON object to be merged. */ function jsonConcat(json1, json2) { - for (var key in json2) { + for (const key in json2) { if (json2.hasOwnProperty(key)) { json1[key] = json2[key]; } @@ -210,11 +228,10 @@ function jsonConcat(json1, json2) { * @return {Object} List of device's attributes formatted in NGSIv2. */ function formatAttributesNgsi2(originalVector, staticAtts) { - var attributeList = {}; + const attributeList = {}; if (originalVector && originalVector.length) { - for (var i = 0; i < originalVector.length; i++) { - + for (let i = 0; i < originalVector.length; i++) { // (#628) check if attribute has entity_name: // In that case attribute should not be appear in current entity /*jshint camelcase: false */ @@ -229,7 +246,7 @@ function formatAttributesNgsi2(originalVector, staticAtts) { } else { attributeList[originalVector[i].name].value = getInitialValueForType(originalVector[i].type); } - if (originalVector[i].metadata ){ + if (originalVector[i].metadata) { attributeList[originalVector[i].name].metadata = originalVector[i].metadata; } } @@ -246,10 +263,10 @@ function formatAttributesNgsi2(originalVector, staticAtts) { * @return {Object} List of device's commands formatted in NGSIv2. */ function formatCommandsNgsi2(originalVector) { - var attributeList = {}; + const attributeList = {}; if (originalVector && originalVector.length) { - for (var i = 0; i < originalVector.length; i++) { + for (let i = 0; i < originalVector.length; i++) { attributeList[originalVector[i].name + constants.COMMAND_STATUS_SUFIX] = { type: constants.COMMAND_STATUS, value: 'UNKNOWN' @@ -271,43 +288,46 @@ function formatCommandsNgsi2(originalVector) { * @param {String} deviceData Device data. */ function executeWithSecurity(requestOptions, deviceData, callback) { - logger.debug(context, 'executeWithSecurity'); - config.getGroupRegistry().getType(deviceData.type, function(error, deviceGroup) { - var typeInformation; - if (error) { - logger.debug(context, 'error %j in get group device', error); - } + logger.debug(context, 'executeWithSecurity'); + config.getGroupRegistry().getType(deviceData.type, function (error, deviceGroup) { + let typeInformation; + if (error) { + logger.debug(context, 'error %j in get group device', error); + } - if (deviceGroup) { - typeInformation = deviceGroup; - } else { - typeInformation = config.getConfig().types[deviceData.type]; - } + if (deviceGroup) { + typeInformation = deviceGroup; + } else { + typeInformation = config.getConfig().types[deviceData.type]; + } - if (config.getConfig().authentication && config.getConfig().authentication.enabled) { - var security = config.getSecurityService(); - if (typeInformation && typeInformation.trust) { - async.waterfall([ + if (config.getConfig().authentication && config.getConfig().authentication.enabled) { + const security = config.getSecurityService(); + if (typeInformation && typeInformation.trust) { + async.waterfall( + [ apply(security.auth, typeInformation.trust), apply(ngsiService.updateTrust, deviceGroup, null, typeInformation.trust), apply(security.getToken, typeInformation.trust) - ], function(error, token) { + ], + function (error, token) { if (error) { callback(new errors.SecurityInformationMissing(typeInformation.type)); - } - else { + } else { requestOptions.headers[config.getConfig().authentication.header] = token; request(requestOptions, callback); } - }); - } else { - callback(new errors.SecurityInformationMissing( - typeInformation ? typeInformation.type : deviceData.type)); - } + } + ); } else { - request(requestOptions, callback); + callback( + new errors.SecurityInformationMissing(typeInformation ? typeInformation.type : deviceData.type) + ); } - }); + } else { + request(requestOptions, callback); + } + }); } /** @@ -318,7 +338,7 @@ function executeWithSecurity(requestOptions, deviceData, callback) { * @param {Object} newDevice Device object that will be stored in the database. */ function createInitialEntityNgsi2(deviceData, newDevice, callback) { - var options = { + const options = { url: config.getConfig().contextBroker.url + '/v2/entities?options=upsert', method: 'POST', json: { @@ -343,10 +363,13 @@ function createInitialEntityNgsi2(deviceData, newDevice, callback) { jsonConcat(options.json, formatCommandsNgsi2(deviceData.commands)); logger.debug(context, 'deviceData: %j', deviceData); - if ( (('timestamp' in deviceData && deviceData.timestamp !== undefined) ? - deviceData.timestamp : config.getConfig().timestamp) && - ! utils.isTimestampedNgsi2(options.json)) { - logger.debug(context, 'config.timestamp %s %s', deviceData.timestamp, config.getConfig().timestamp); + if ( + ('timestamp' in deviceData && deviceData.timestamp !== undefined + ? deviceData.timestamp + : config.getConfig().timestamp) && + !utils.isTimestampedNgsi2(options.json) + ) { + logger.debug(context, 'config.timestamp %s %s', deviceData.timestamp, config.getConfig().timestamp); options.json[constants.TIMESTAMP_ATTRIBUTE] = { type: constants.TIMESTAMP_TYPE_NGSI2, value: moment() @@ -366,38 +389,38 @@ function createInitialEntityNgsi2(deviceData, newDevice, callback) { * @param {Object} newDevice Device object that will be stored in the database. */ function createInitialEntityNgsi1(deviceData, newDevice, callback) { - var cbHost = config.getConfig().contextBroker.url; + let cbHost = config.getConfig().contextBroker.url; if (deviceData.cbHost && deviceData.cbHost.indexOf('://') !== -1) { cbHost = deviceData.cbHost; } else if (deviceData.cbHost && deviceData.cbHost.indexOf('://') === -1) { cbHost = 'http://' + deviceData.cbHost; } - var options = { - url: cbHost + '/v1/updateContext', - method: 'POST', - json: { - contextElements: [ - { - type: deviceData.type, - isPattern: 'false', - id: String(deviceData.name), - attributes: [] - } - ], - updateAction: 'APPEND' - }, - headers: { - 'fiware-service': deviceData.service, - 'fiware-servicepath': deviceData.subservice, - 'fiware-correlator': (domain.active && domain.active.corr) || uuid.v4() - } - }; + const options = { + url: cbHost + '/v1/updateContext', + method: 'POST', + json: { + contextElements: [ + { + type: deviceData.type, + isPattern: 'false', + id: String(deviceData.name), + attributes: [] + } + ], + updateAction: 'APPEND' + }, + headers: { + 'fiware-service': deviceData.service, + 'fiware-servicepath': deviceData.subservice, + 'fiware-correlator': (domain.active && domain.active.corr) || uuid.v4() + } + }; function formatAttributes(originalVector) { - var attributeList = []; + const attributeList = []; if (originalVector && originalVector.length) { - for (var i = 0; i < originalVector.length; i++) { + for (let i = 0; i < originalVector.length; i++) { // (#628) check if attribute has entity_name: // In that case attribute should not be appear in current entity /*jshint camelcase: false */ @@ -415,10 +438,10 @@ function createInitialEntityNgsi1(deviceData, newDevice, callback) { } function formatCommands(originalVector) { - var attributeList = []; + const attributeList = []; if (originalVector && originalVector.length) { - for (var i = 0; i < originalVector.length; i++) { + for (let i = 0; i < originalVector.length; i++) { attributeList.push({ name: originalVector[i].name + constants.COMMAND_STATUS_SUFIX, type: constants.COMMAND_STATUS, @@ -438,11 +461,15 @@ function createInitialEntityNgsi1(deviceData, newDevice, callback) { options.json.contextElements[0].attributes = [].concat( formatAttributes(deviceData.active), deviceData.staticAttributes, - formatCommands(deviceData.commands)); - - if ( (('timestamp' in deviceData && deviceData.timestamp !== undefined) ? - deviceData.timestamp : config.getConfig().timestamp) && - ! utils.isTimestamped(options.json)) { + formatCommands(deviceData.commands) + ); + + if ( + ('timestamp' in deviceData && deviceData.timestamp !== undefined + ? deviceData.timestamp + : config.getConfig().timestamp) && + !utils.isTimestamped(options.json) + ) { options.json.contextElements[0].attributes.push({ name: constants.TIMESTAMP_ATTRIBUTE, type: constants.TIMESTAMP_TYPE, @@ -476,11 +503,10 @@ function createInitialEntity(deviceData, newDevice, callback) { * @param {Object} updatedDevice Device object that will be stored in the database. */ function updateEntityNgsi2(deviceData, updatedDevice, callback) { - var options = { + const options = { url: config.getConfig().contextBroker.url + '/v2/entities/' + String(deviceData.name) + '/attrs', method: 'POST', - json: { - }, + json: {}, headers: { 'fiware-service': deviceData.service, 'fiware-servicepath': deviceData.subservice, @@ -495,16 +521,19 @@ function updateEntityNgsi2(deviceData, updatedDevice, callback) { } if (deviceData.type) { - options.url += '?type=' + deviceData.type; + options.url += '?type=' + deviceData.type; } jsonConcat(options.json, formatAttributesNgsi2(deviceData.active, false)); jsonConcat(options.json, formatAttributesNgsi2(deviceData.staticAttributes, true)); jsonConcat(options.json, formatCommandsNgsi2(deviceData.commands)); - if ( (('timestamp' in deviceData && deviceData.timestamp !== undefined) ? - deviceData.timestamp : config.getConfig().timestamp) && - ! utils.isTimestampedNgsi2(options.json)) { + if ( + ('timestamp' in deviceData && deviceData.timestamp !== undefined + ? deviceData.timestamp + : config.getConfig().timestamp) && + !utils.isTimestampedNgsi2(options.json) + ) { options.json[constants.TIMESTAMP_ATTRIBUTE] = { type: constants.TIMESTAMP_TYPE_NGSI2, value: moment() @@ -515,8 +544,7 @@ function updateEntityNgsi2(deviceData, updatedDevice, callback) { if (Object.keys(options.json).length === 0 && options.json.constructor === Object) { logger.debug(context, 'Skip updating entity in the Context Broker (no actual attribute change)'); callback(null, updatedDevice); - } - else{ + } else { logger.debug(context, 'Updating entity in the Context Broker:\n %s', JSON.stringify(options, null, 4)); request(options, updateEntityHandlerNgsi2(deviceData, updatedDevice, callback)); } @@ -554,18 +582,18 @@ function setDefaultAttributeIds(attribute) { */ function mergeArrays(original, newArray) { /* jshint camelcase: false */ - var originalKeys = _.pluck(original, 'object_id'), - newKeys = _.pluck(newArray, 'object_id'), - addedKeys = _.difference(newKeys, originalKeys), - differenceArray = newArray.filter(function(item) { - return item.object_id && addedKeys.indexOf(item.object_id) >= 0; - }), - originalNames = _.pluck(original, 'name'), - newNames = _.pluck(newArray, 'name'), - addedNames = _.difference(newNames, originalNames), - differenceNamesArray = newArray.filter(function(item) { - return addedNames.indexOf(item.name) >= 0 && (!item.object_id || newKeys.indexOf(item.object_id) < 0); - }); + const originalKeys = _.pluck(original, 'object_id'); + const newKeys = _.pluck(newArray, 'object_id'); + const addedKeys = _.difference(newKeys, originalKeys); + const differenceArray = newArray.filter(function (item) { + return item.object_id && addedKeys.indexOf(item.object_id) >= 0; + }); + const originalNames = _.pluck(original, 'name'); + const newNames = _.pluck(newArray, 'name'); + const addedNames = _.difference(newNames, originalNames); + const differenceNamesArray = newArray.filter(function (item) { + return addedNames.indexOf(item.name) >= 0 && (!item.object_id || newKeys.indexOf(item.object_id) < 0); + }); return original.concat(differenceArray).concat(differenceNamesArray); } @@ -580,8 +608,8 @@ function mergeArrays(original, newArray) { */ function mergeDeviceWithConfiguration(fields, defaults, deviceData, configuration, callback) { logger.debug(context, 'deviceData before merge with conf: %j', deviceData); - for (var i = 0; i < fields.length; i++) { - var confField = (fields[i] === 'active') ? 'attributes' : fields[i]; + for (let i = 0; i < fields.length; i++) { + const confField = fields[i] === 'active' ? 'attributes' : fields[i]; if (deviceData && deviceData[fields[i]] && ['active', 'lazy', 'commands'].indexOf(fields[i]) >= 0) { deviceData[fields[i]] = deviceData[fields[i]].map(setDefaultAttributeIds); @@ -601,8 +629,12 @@ function mergeDeviceWithConfiguration(fields, defaults, deviceData, configuratio if (deviceData[fields[i]] && configuration && configuration[confField]) { deviceData[fields[i]] = mergeArrays(deviceData[fields[i]], configuration[confField]); - } else if (!deviceData[fields[i]] && configuration && - confField in configuration && configuration[confField] !== undefined) { + } else if ( + !deviceData[fields[i]] && + configuration && + confField in configuration && + configuration[confField] !== undefined + ) { deviceData[fields[i]] = configuration[confField]; } else if (!deviceData[fields[i]] && (!configuration || !configuration[confField])) { deviceData[fields[i]] = defaults[i]; @@ -624,7 +656,7 @@ function mergeDeviceWithConfiguration(fields, defaults, deviceData, configuratio */ function findConfigurationGroup(deviceObj, callback) { function handlerGroupFind(error, group) { - var effectiveGroup = group; + let effectiveGroup = group; if (!group && config.getConfig().types[deviceObj.type]) { effectiveGroup = config.getConfig().types[deviceObj.type]; @@ -636,17 +668,17 @@ function findConfigurationGroup(deviceObj, callback) { } if (config.getConfig().singleConfigurationMode === true) { - config.getGroupRegistry().find( - deviceObj.service, - deviceObj.subservice, - handlerGroupFind); + config.getGroupRegistry().find(deviceObj.service, deviceObj.subservice, handlerGroupFind); } else { - config.getGroupRegistry().findTypeSilently( - deviceObj.service, - deviceObj.subservice, - deviceObj.type, - deviceObj.apikey, - handlerGroupFind); + config + .getGroupRegistry() + .findTypeSilently( + deviceObj.service, + deviceObj.subservice, + deviceObj.type, + deviceObj.apikey, + handlerGroupFind + ); } } @@ -664,19 +696,21 @@ function findConfigurationGroup(deviceObj, callback) { */ function registerDevice(deviceObj, callback) { function checkDuplicates(deviceObj, innerCb) { - config.getRegistry().getSilently(deviceObj.id, deviceObj.service, deviceObj.subservice, - function(error, device) { - if (!error) { - innerCb(new errors.DuplicateDeviceId(deviceObj.id)); - } else { - innerCb(); - } - }); + config + .getRegistry() + /* eslint-disable-next-line no-unused-vars */ + .getSilently(deviceObj.id, deviceObj.service, deviceObj.subservice, function (error, device) { + if (!error) { + innerCb(new errors.DuplicateDeviceId(deviceObj.id)); + } else { + innerCb(); + } + }); } function prepareDeviceData(deviceObj, configuration, callback) { - var deviceData = _.clone(deviceObj), - selectedConfiguration; + const deviceData = _.clone(deviceObj); + let selectedConfiguration; if (!deviceData.type) { if (configuration && configuration.type) { @@ -715,50 +749,51 @@ function registerDevice(deviceObj, callback) { logger.debug(context, 'Registering device into NGSI Service:\n%s', JSON.stringify(deviceData, null, 4)); - async.waterfall([ - apply(registrationUtils.sendRegistrations, false, deviceData), - apply(processContextRegistration, deviceData), - apply(createInitialEntity, deviceData) - ], function(error, results) { - if (error) { - callback(error); - } else { - deviceObj.registrationId = results.registrationId; - deviceObj.name = deviceData.name; - deviceObj.service = deviceData.service; - deviceObj.subservice = deviceData.subservice; - deviceObj.type = deviceData.type; - deviceObj.staticAttributes = deviceData.staticAttributes; - deviceObj.commands = deviceData.commands; - if ('timestamp' in deviceData && deviceData.timestamp !== undefined) { - deviceObj.timestamp = deviceData.timestamp; - } - if ('autoprovision' in deviceData && deviceData.autoprovision !== undefined) { - deviceObj.autoprovision = deviceData.autoprovision; - } - if ('explicitAttrs' in deviceData && deviceData.explicitAttrs !== undefined) { - deviceObj.explicitAttrs = deviceData.explicitAttrs; + async.waterfall( + [ + apply(registrationUtils.sendRegistrations, false, deviceData), + apply(processContextRegistration, deviceData), + apply(createInitialEntity, deviceData) + ], + function (error, results) { + if (error) { + callback(error); + } else { + deviceObj.registrationId = results.registrationId; + deviceObj.name = deviceData.name; + deviceObj.service = deviceData.service; + deviceObj.subservice = deviceData.subservice; + deviceObj.type = deviceData.type; + deviceObj.staticAttributes = deviceData.staticAttributes; + deviceObj.commands = deviceData.commands; + if ('timestamp' in deviceData && deviceData.timestamp !== undefined) { + deviceObj.timestamp = deviceData.timestamp; + } + if ('autoprovision' in deviceData && deviceData.autoprovision !== undefined) { + deviceObj.autoprovision = deviceData.autoprovision; + } + if ('explicitAttrs' in deviceData && deviceData.explicitAttrs !== undefined) { + deviceObj.explicitAttrs = deviceData.explicitAttrs; + } + config.getRegistry().store(deviceObj, callback); } - config.getRegistry().store(deviceObj, callback); } - }); + ); } - async.waterfall([ - apply(checkDuplicates, deviceObj), - apply(findConfigurationGroup, deviceObj), - apply(prepareDeviceData, deviceObj), - apply(mergeDeviceWithConfiguration, - [ - 'lazy', - 'active', - 'staticAttributes', - 'commands', - 'subscriptions' - ], - [null, null, [], [], [], [], []] - ) - ], completeRegistrations); + async.waterfall( + [ + apply(checkDuplicates, deviceObj), + apply(findConfigurationGroup, deviceObj), + apply(prepareDeviceData, deviceObj), + apply( + mergeDeviceWithConfiguration, + ['lazy', 'active', 'staticAttributes', 'commands', 'subscriptions'], + [null, null, [], [], [], [], []] + ) + ], + completeRegistrations + ); } function removeAllSubscriptions(device, callback) { @@ -791,36 +826,37 @@ function unregisterDevice(id, service, subservice, callback) { logger.debug(context, 'Removing device register in Device Service'); - config.getRegistry().get(id, service, subservice, function(error, device) { + config.getRegistry().get(id, service, subservice, function (error, device) { if (error) { - callback(error); + callback(error); } else { - async.waterfall([ - apply(findConfigurationGroup, device), - apply(mergeDeviceWithConfiguration, - [ - 'lazy', - 'active', - 'staticAttributes', - 'commands', - 'subscriptions' - ], - [null, null, [], [], [], [], []], - device - ) - ], function(error, mergedDevice) { - if (error) { - callback(error); - } else { - async.waterfall([ - apply(removeAllSubscriptions, mergedDevice), - processUnsubscribes, - apply(registrationUtils.sendRegistrations, true, mergedDevice), - processContextUnregister, - apply(config.getRegistry().remove, id, service, subservice) - ], callback); + async.waterfall( + [ + apply(findConfigurationGroup, device), + apply( + mergeDeviceWithConfiguration, + ['lazy', 'active', 'staticAttributes', 'commands', 'subscriptions'], + [null, null, [], [], [], [], []], + device + ) + ], + function (error, mergedDevice) { + if (error) { + callback(error); + } else { + async.waterfall( + [ + apply(removeAllSubscriptions, mergedDevice), + processUnsubscribes, + apply(registrationUtils.sendRegistrations, true, mergedDevice), + processContextUnregister, + apply(config.getRegistry().remove, id, service, subservice) + ], + callback + ); + } } - }); + ); } }); } @@ -870,10 +906,10 @@ function updateRegisterDeviceNgsi1(deviceObj, callback) { } function getAttributeDifference(oldArray, newArray) { - var oldActiveKeys, - newActiveKeys, - updateKeys, - result; + let oldActiveKeys; + let newActiveKeys; + let updateKeys; + let result; if (oldArray && newArray) { newActiveKeys = _.pluck(newArray, 'name'); @@ -881,7 +917,7 @@ function updateRegisterDeviceNgsi1(deviceObj, callback) { updateKeys = _.difference(newActiveKeys, oldActiveKeys); - result = newArray.filter(function(attribute) { + result = newArray.filter(function (attribute) { return updateKeys.indexOf(attribute.name) >= 0; }); } else if (newArray) { @@ -894,13 +930,13 @@ function updateRegisterDeviceNgsi1(deviceObj, callback) { } function extractDeviceDifference(newDevice, oldDevice, callback) { - var deviceData = { - id: oldDevice.id, - name: oldDevice.name, - type: oldDevice.type, - service: oldDevice.service, - subservice: oldDevice.subservice - }; + const deviceData = { + id: oldDevice.id, + name: oldDevice.name, + type: oldDevice.type, + service: oldDevice.service, + subservice: oldDevice.subservice + }; deviceData.active = getAttributeDifference(oldDevice.active, newDevice.active); deviceData.lazy = getAttributeDifference(oldDevice.lazy, newDevice.lazy); @@ -910,15 +946,18 @@ function updateRegisterDeviceNgsi1(deviceObj, callback) { callback(null, deviceData, oldDevice); } - async.waterfall([ - apply(config.getRegistry().get, deviceObj.id, deviceObj.service, deviceObj.subservice), - apply(extractDeviceDifference, deviceObj), - createInitialEntity, - apply(combineWithNewDevice, deviceObj), - apply(registrationUtils.sendRegistrations, false), - apply(processContextRegistration, deviceObj), - config.getRegistry().update - ], callback); + async.waterfall( + [ + apply(config.getRegistry().get, deviceObj.id, deviceObj.service, deviceObj.subservice), + apply(extractDeviceDifference, deviceObj), + createInitialEntity, + apply(combineWithNewDevice, deviceObj), + apply(registrationUtils.sendRegistrations, false), + apply(processContextRegistration, deviceObj), + config.getRegistry().update + ], + callback + ); } /** @@ -969,10 +1008,10 @@ function updateRegisterDeviceNgsi2(deviceObj, callback) { } function getAttributeDifference(oldArray, newArray) { - var oldActiveKeys, - newActiveKeys, - updateKeys, - result; + let oldActiveKeys; + let newActiveKeys; + let updateKeys; + let result; if (oldArray && newArray) { newActiveKeys = _.pluck(newArray, 'name'); @@ -980,7 +1019,7 @@ function updateRegisterDeviceNgsi2(deviceObj, callback) { updateKeys = _.difference(newActiveKeys, oldActiveKeys); - result = newArray.filter(function(attribute) { + result = newArray.filter(function (attribute) { return updateKeys.indexOf(attribute.name) >= 0; }); } else if (newArray) { @@ -993,13 +1032,13 @@ function updateRegisterDeviceNgsi2(deviceObj, callback) { } function extractDeviceDifference(newDevice, oldDevice, callback) { - var deviceData = { - id: oldDevice.id, - name: oldDevice.name, - type: oldDevice.type, - service: oldDevice.service, - subservice: oldDevice.subservice - }; + const deviceData = { + id: oldDevice.id, + name: oldDevice.name, + type: oldDevice.type, + service: oldDevice.service, + subservice: oldDevice.subservice + }; deviceData.active = getAttributeDifference(oldDevice.active, newDevice.active); deviceData.lazy = getAttributeDifference(oldDevice.lazy, newDevice.lazy); @@ -1009,18 +1048,20 @@ function updateRegisterDeviceNgsi2(deviceObj, callback) { callback(null, deviceData, oldDevice); } - async.waterfall([ - apply(config.getRegistry().get, deviceObj.id, deviceObj.service, deviceObj.subservice), - apply(extractDeviceDifference, deviceObj), - updateEntityNgsi2, - apply(combineWithNewDevice, deviceObj), - apply(registrationUtils.sendRegistrations, false), - apply(processContextRegistration, deviceObj), - config.getRegistry().update - ], callback); + async.waterfall( + [ + apply(config.getRegistry().get, deviceObj.id, deviceObj.service, deviceObj.subservice), + apply(extractDeviceDifference, deviceObj), + updateEntityNgsi2, + apply(combineWithNewDevice, deviceObj), + apply(registrationUtils.sendRegistrations, false), + apply(processContextRegistration, deviceObj), + config.getRegistry().update + ], + callback + ); } - function updateRegisterDevice(deviceObj, callback) { if (config.checkNgsi2()) { updateRegisterDeviceNgsi2(deviceObj, callback); @@ -1049,7 +1090,7 @@ function listDevicesWithType(type, service, subservice, limit, offset, callback) service = null; subservice = null; } else { - logger.fatal(context, 'GENERAL-001: Couldn\'t find callback in listDevices() call.'); + logger.fatal(context, "GENERAL-001: Couldn't find callback in listDevices() call."); } } @@ -1075,7 +1116,7 @@ function listDevices(service, subservice, limit, offset, callback) { service = null; subservice = null; } else { - logger.fatal(context, 'GENERAL-001: Couldn\'t find callback in listDevices() call.'); + logger.fatal(context, "GENERAL-001: Couldn't find callback in listDevices() call."); } } @@ -1141,13 +1182,13 @@ function getDevicesByAttribute(attributeName, attributeValue, service, subservic * @return {Function} Wrapped function. */ function checkRegistry(fn) { - return function() { - var args = Array.prototype.slice.call(arguments), - callbacks = args.slice(-1); + return function () { + const args = Array.prototype.slice.call(arguments); + const callbacks = args.slice(-1); if (config.getRegistry()) { fn.apply(null, args); - } else if (callbacks && callbacks.length === 1 && (typeof callbacks[0] === 'function')) { + } else if (callbacks && callbacks.length === 1 && typeof callbacks[0] === 'function') { logger.error(context, 'Tried to access device information before a registry was available'); callbacks[0](new errors.RegistryNotAvailable()); } else { @@ -1156,13 +1197,12 @@ function checkRegistry(fn) { }; } - function findOrCreate(deviceId, group, callback) { - getDeviceSilently(deviceId, group.service, group.subservice, function(error, device) { + getDeviceSilently(deviceId, group.service, group.subservice, function (error, device) { if (!error && device) { callback(null, device, group); } else if (error.name === 'DEVICE_NOT_FOUND') { - var newDevice = { + const newDevice = { id: deviceId, service: group.service, subservice: group.subservice, @@ -1180,7 +1220,7 @@ function findOrCreate(deviceId, group, callback) { newDevice.autoprovision = group.autoprovision; } - registerDevice(newDevice, function(error, device) { + registerDevice(newDevice, function (error, device) { callback(error, device, group); }); } else { @@ -1198,33 +1238,30 @@ function findOrCreate(deviceId, group, callback) { */ function retrieveDevice(deviceId, apiKey, callback) { if (apiKey === config.getConfig().defaultKey) { - getDevicesByAttribute('id', deviceId, null, null, function(error, devices) { + getDevicesByAttribute('id', deviceId, null, null, function (error, devices) { if (error) { callback(error); } else if (devices && devices.length === 1) { callback(null, devices[0]); } else { - logger.error(context, 'Couldn\'t find device data for APIKey [%s] and DeviceId[%s]', - deviceId, apiKey); + logger.error(context, "Couldn't find device data for APIKey [%s] and DeviceId[%s]", deviceId, apiKey); callback(new errors.DeviceNotFound(deviceId)); } }); } else { - async.waterfall([ - apply(groupService.get, config.getConfig().defaultResource || '', apiKey), - apply(findOrCreate, deviceId), - apply(mergeDeviceWithConfiguration, - [ - 'lazy', - 'active', - 'staticAttributes', - 'commands', - 'subscriptions' - ], - [null, null, [], [], [], [], []] - ) - ], callback); + async.waterfall( + [ + apply(groupService.get, config.getConfig().defaultResource || '', apiKey), + apply(findOrCreate, deviceId), + apply( + mergeDeviceWithConfiguration, + ['lazy', 'active', 'staticAttributes', 'commands', 'subscriptions'], + [null, null, [], [], [], [], []] + ) + ], + callback + ); } } diff --git a/lib/services/devices/registrationUtils.js b/lib/services/devices/registrationUtils.js index 14bfed6d0..d0884326f 100644 --- a/lib/services/devices/registrationUtils.js +++ b/lib/services/devices/registrationUtils.js @@ -24,19 +24,17 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var errors = require('../../errors'), - logger = require('logops'), - _ = require('underscore'), - intoTrans = require('../common/domain').intoTrans, - config = require('../../commonConfig'), - ngsiParser = require('./../ngsi/ngsiParser'), - context = { - op: 'IoTAgentNGSI.DeviceService' - }, - async = require('async'), - deviceService = require('./deviceService'); +const errors = require('../../errors'); +const logger = require('logops'); +const _ = require('underscore'); +const intoTrans = require('../common/domain').intoTrans; +const config = require('../../commonConfig'); +const ngsiParser = require('./../ngsi/ngsiParser'); +const context = { + op: 'IoTAgentNGSI.DeviceService' +}; +const async = require('async'); +const deviceService = require('./deviceService'); /** * Generates a handler for the registration requests that checks all the possible errors derived from the registration. @@ -52,7 +50,7 @@ function createRegistrationHandler(unregister, deviceData, callback) { logger.error(context, 'ORION-002: Connection error sending registrations to the Context Broker: %s', error); callback(error); } else if (response && body && response.statusCode === 200) { - var errorField = ngsiParser.getErrorField(body); + const errorField = ngsiParser.getErrorField(body); if (errorField) { logger.error(context, 'Registration error connecting to the Context Broker: %j', errorField); @@ -62,7 +60,7 @@ function createRegistrationHandler(unregister, deviceData, callback) { callback(null, body); } } else { - var errorObj; + let errorObj; logger.error(context, 'ORION-003: Protocol error connecting to the Context Broker: %j', errorObj); @@ -86,24 +84,24 @@ function createRegistrationHandler(unregister, deviceData, callback) { * @return {Function} The generated handler. */ function createRegistrationHandlerNgsi2(unregister, deviceData, callback) { + /* eslint-disable-next-line no-unused-vars */ return function handleRegistrationResponse(error, response, body) { if (error) { logger.error(context, 'ORION-002: Connection error sending registrations to the Context Broker: %s', error); callback(error); } else if (response && response.statusCode === 201 && response.headers.location && unregister === false) { logger.debug(context, 'Registration success.'); - callback(null, {registrationId: - response.headers.location.substr(response.headers.location.lastIndexOf('/') + 1)}); + callback(null, { + registrationId: response.headers.location.substr(response.headers.location.lastIndexOf('/') + 1) + }); } else if (response && response.statusCode === 204 && unregister === true) { logger.debug(context, 'Unregistration success.'); callback(null, null); - } - else if (response && response.statusCode && response.statusCode !== 500) { + } else if (response && response.statusCode && response.statusCode !== 500) { logger.error(context, 'Registration error connecting to the Context Broker: %j', response.statusCode); callback(new errors.BadRequest(JSON.stringify(response.statusCode))); - } - else { - var errorObj; + } else { + let errorObj; logger.error(context, 'ORION-003: Protocol error connecting to the Context Broker: %j', errorObj); @@ -129,14 +127,14 @@ function createRegistrationHandlerNgsi2(unregister, deviceData, callback) { * @param {Object} deviceData Object containing all the deviceData needed to send the registration. */ function sendRegistrationsNgsi1(unregister, deviceData, callback) { - var cbHost = config.getConfig().contextBroker.url; + let cbHost = config.getConfig().contextBroker.url; if (deviceData.cbHost && deviceData.cbHost.indexOf('://') !== -1) { cbHost = deviceData.cbHost; } else if (deviceData.cbHost && deviceData.cbHost.indexOf('://') === -1) { cbHost = 'http://' + deviceData.cbHost; } - var options = { + const options = { url: cbHost + '/NGSI9/registerContext', method: 'POST', json: { @@ -153,7 +151,7 @@ function sendRegistrationsNgsi1(unregister, deviceData, callback) { providingApplication: config.getConfig().providerUrl } ], - duration: (unregister) ? 'PT1S' : config.getConfig().deviceRegistrationDuration + duration: unregister ? 'PT1S' : config.getConfig().deviceRegistrationDuration }, headers: { 'fiware-service': deviceData.service, @@ -162,10 +160,10 @@ function sendRegistrationsNgsi1(unregister, deviceData, callback) { }; function formatAttributes(originalVector) { - var attributeList = []; + const attributeList = []; if (originalVector && originalVector.length) { - for (var i = 0; i < originalVector.length; i++) { + for (let i = 0; i < originalVector.length; i++) { attributeList.push({ name: originalVector[i].name, type: originalVector[i].type @@ -177,7 +175,7 @@ function sendRegistrationsNgsi1(unregister, deviceData, callback) { } function mergeWithSameName(old, current) { - var keys = _.pluck(old, 'name'); + const keys = _.pluck(old, 'name'); if (keys.indexOf(current.name) < 0) { old.push(current); @@ -190,10 +188,9 @@ function sendRegistrationsNgsi1(unregister, deviceData, callback) { options.json.registrationId = deviceData.registrationId; } - options.json.contextRegistrations[0].attributes = options.json.contextRegistrations[0].attributes.concat( - formatAttributes(deviceData.lazy), - formatAttributes(deviceData.commands) - ).reduce(mergeWithSameName, []); + options.json.contextRegistrations[0].attributes = options.json.contextRegistrations[0].attributes + .concat(formatAttributes(deviceData.lazy), formatAttributes(deviceData.commands)) + .reduce(mergeWithSameName, []); if (options.json.contextRegistrations[0].attributes.length === 0) { logger.debug(context, 'No Context Provider registrations found for unregister'); @@ -205,7 +202,8 @@ function sendRegistrationsNgsi1(unregister, deviceData, callback) { deviceService.executeWithSecurity( options, deviceData, - createRegistrationHandler(unregister, deviceData, callback)); + createRegistrationHandler(unregister, deviceData, callback) + ); } } @@ -215,13 +213,13 @@ function sendRegistrationsNgsi1(unregister, deviceData, callback) { * @param {Object} deviceData Object containing all the deviceData needed to send the registration. */ function sendUnregistrationsNgsi2(deviceData, callback) { - var cbHost = config.getConfig().contextBroker.url; + let cbHost = config.getConfig().contextBroker.url; if (deviceData.cbHost && deviceData.cbHost.indexOf('://') !== -1) { cbHost = deviceData.cbHost; } else if (deviceData.cbHost && deviceData.cbHost.indexOf('://') === -1) { cbHost = 'http://' + deviceData.cbHost; } - var options = { + const options = { url: cbHost + '/v2/registrations/' + deviceData.registrationId, method: 'DELETE', json: true, @@ -242,13 +240,12 @@ function sendUnregistrationsNgsi2(deviceData, callback) { deviceService.executeWithSecurity( options, deviceData, - createRegistrationHandlerNgsi2(true, deviceData, callback)); + createRegistrationHandlerNgsi2(true, deviceData, callback) + ); } else { logger.debug(context, 'No Context Provider registrations found for unregister'); callback(null, deviceData); } - - } /** @@ -258,25 +255,24 @@ function sendUnregistrationsNgsi2(deviceData, callback) { * @param {Object} deviceData Object containing all the deviceData needed to send the registration. */ function sendRegistrationsNgsi2(unregister, deviceData, callback) { - var cbHost = config.getConfig().contextBroker.url; + let cbHost = config.getConfig().contextBroker.url; if (deviceData.cbHost && deviceData.cbHost.indexOf('://') !== -1) { cbHost = deviceData.cbHost; } else if (deviceData.cbHost && deviceData.cbHost.indexOf('://') === -1) { cbHost = 'http://' + deviceData.cbHost; } - var options = { + const options = { url: cbHost + '/v2/registrations', method: 'POST', json: { dataProvided: { - entities: - [ + entities: [ { type: deviceData.type, id: String(deviceData.name) } ], - attrs: [], + attrs: [] }, provider: { http: { @@ -291,10 +287,10 @@ function sendRegistrationsNgsi2(unregister, deviceData, callback) { }; function formatAttributes(originalVector) { - var attributeList = []; + const attributeList = []; if (originalVector && originalVector.length) { - for (var i = 0; i < originalVector.length; i++) { + for (let i = 0; i < originalVector.length; i++) { attributeList.push(originalVector[i].name); } } @@ -302,7 +298,6 @@ function sendRegistrationsNgsi2(unregister, deviceData, callback) { return attributeList; } - function mergeWithSameName(old, current) { if (old.indexOf(current) < 0) { old.push(current); @@ -315,7 +310,7 @@ function sendRegistrationsNgsi2(unregister, deviceData, callback) { // this function should use the new API. This is just a temporary solution which implies deleting the // registration and creating a new one. function updateRegistrationNgsi2(deviceData, callback) { - var functions = []; + const functions = []; function removeRegistrationId(deviceData, unregistrationResult, callback) { delete deviceData.registrationId; @@ -330,34 +325,31 @@ function sendRegistrationsNgsi2(unregister, deviceData, callback) { if (unregister) { sendUnregistrationsNgsi2(deviceData, callback); + } else if (deviceData.registrationId) { + updateRegistrationNgsi2(deviceData, callback); } else { - - if (deviceData.registrationId) { - updateRegistrationNgsi2(deviceData, callback); + options.json.dataProvided.attrs = options.json.dataProvided.attrs + .concat(formatAttributes(deviceData.lazy), formatAttributes(deviceData.commands)) + .reduce(mergeWithSameName, []); + + if (options.json.dataProvided.attrs.length === 0) { + logger.debug( + context, + 'Registration with Context Provider is not needed. Device without lazy atts or commands' + ); + callback(null, deviceData); } else { - options.json.dataProvided.attrs = options.json.dataProvided.attrs.concat( - formatAttributes(deviceData.lazy), - formatAttributes(deviceData.commands) - ).reduce(mergeWithSameName, []); - - if (options.json.dataProvided.attrs.length === 0) { - logger.debug(context, 'Registration with Context Provider is not needed.' + - 'Device without lazy atts or commands'); - callback(null, deviceData); - } else { - logger.debug(context, 'Sending device registrations to Context Broker at [%s]', options.url); - logger.debug(context, 'Using the following request:\n\n%s\n\n', JSON.stringify(options, null, 4)); - deviceService.executeWithSecurity( - options, - deviceData, - createRegistrationHandlerNgsi2(unregister, deviceData, callback)); - } + logger.debug(context, 'Sending device registrations to Context Broker at [%s]', options.url); + logger.debug(context, 'Using the following request:\n\n%s\n\n', JSON.stringify(options, null, 4)); + deviceService.executeWithSecurity( + options, + deviceData, + createRegistrationHandlerNgsi2(unregister, deviceData, callback) + ); } } } - - /** * Sends a Context Provider registration or unregistration request to the Context Broker. As registrations cannot be * removed, an unregistration consists of an update of the existent registration to make reduce its duration to diff --git a/lib/services/groups/groupRegistryMemory.js b/lib/services/groups/groupRegistryMemory.js index 70144ce35..7ccc4ad0b 100644 --- a/lib/services/groups/groupRegistryMemory.js +++ b/lib/services/groups/groupRegistryMemory.js @@ -20,25 +20,28 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; - -var registeredGroups = {}, - logger = require('logops'), - intoTrans = require('../common/domain').intoTrans, - errors = require('../../errors'), - config = require('../../commonConfig'), - _ = require('underscore'), - context = { - op: 'IoTAgentNGSI.InMemoryGroupRegister' - }, - groupIds = 1; + +/* eslint-disable no-prototype-builtins */ + +let registeredGroups = {}; +const logger = require('logops'); +const intoTrans = require('../common/domain').intoTrans; +const errors = require('../../errors'); +const config = require('../../commonConfig'); +const _ = require('underscore'); +const context = { + op: 'IoTAgentNGSI.InMemoryGroupRegister' +}; +let groupIds = 1; function exists(group) { - var keys = _.keys(registeredGroups); + const keys = _.keys(registeredGroups); - for (var i in keys) { - if (registeredGroups[keys[i]].apikey === group.apikey && - registeredGroups[keys[i]].resource === group.resource) { + for (const i in keys) { + if ( + registeredGroups[keys[i]].apikey === group.apikey && + registeredGroups[keys[i]].resource === group.resource + ) { return true; } } @@ -50,15 +53,20 @@ function createGroup(group, callback) { if (exists(group)) { callback(new errors.DuplicateGroup(group.resource, group.apikey)); } else { - var storeGroup = _.clone(group); + const storeGroup = _.clone(group); storeGroup._id = groupIds++; registeredGroups[storeGroup._id] = storeGroup; registeredGroups[storeGroup._id].creationDate = Date.now(); - logger.debug(context, 'Storing device group for service [%s] and subservice [%s]', - storeGroup._id, storeGroup.service, storeGroup.subservice); + logger.debug( + context, + 'Storing device group for service [%s] and subservice [%s]', + storeGroup._id, + storeGroup.service, + storeGroup.subservice + ); callback(null); } @@ -74,9 +82,8 @@ function getConfigurationsByService(service) { return Object.keys(registeredGroups).filter(function filterByService(item) { if (service) { return registeredGroups[item].service === service; - } else { - return true; } + return true; }); } @@ -90,11 +97,11 @@ function getConfigurationsByService(service) { * @param {Number} offset Number of entries to skip for pagination. */ function listGroups(service, limit, offset, callback) { - var result = [], - skipped = 0, - filteredGroups = getConfigurationsByService(service); + const result = []; + let skipped = 0; + const filteredGroups = getConfigurationsByService(service); - for (var i in filteredGroups) { + for (const i in filteredGroups) { if (registeredGroups.hasOwnProperty(filteredGroups[i])) { if (offset && skipped < parseInt(offset, 10)) { skipped++; @@ -125,12 +132,14 @@ function clear(callback) { } function findSingleConfigurationMode(service, subservice, callback) { - var result; + let result; - for (var i in registeredGroups) { - if (registeredGroups.hasOwnProperty(i) && + for (const i in registeredGroups) { + if ( + registeredGroups.hasOwnProperty(i) && registeredGroups[i].service === service && - registeredGroups[i].subservice === subservice) { + registeredGroups[i].subservice === subservice + ) { result = registeredGroups[i]; break; } @@ -144,52 +153,55 @@ function findSingleConfigurationMode(service, subservice, callback) { } function find(service, subservice, callback) { - if (config.getConfig().singleConfigurationMode === true){ + if (config.getConfig().singleConfigurationMode === true) { return findSingleConfigurationMode(service, subservice, callback); } - var result = []; + const result = []; - for (var i in registeredGroups) { - if (registeredGroups.hasOwnProperty(i) && + for (const i in registeredGroups) { + if ( + registeredGroups.hasOwnProperty(i) && registeredGroups[i].service === service && - registeredGroups[i].subservice === subservice) { + registeredGroups[i].subservice === subservice + ) { result.push(registeredGroups[i]); } } if (result.length > 0) { - callback(null, { + return callback(null, { count: result.length, services: result }); } else { - callback(new errors.DeviceGroupNotFound(service, subservice)); + return callback(new errors.DeviceGroupNotFound(service, subservice)); } } function findBy(fields) { - return function() { - var result, - queryObj = {}, - i = 0, - callback; + return function () { + let result; + const queryObj = {}; + let i = 0; + /* eslint-disable-next-line prefer-rest-params */ while (typeof arguments[i] !== 'function') { + /* eslint-disable-next-line prefer-rest-params */ queryObj[fields[i]] = arguments[i]; i++; } - callback = arguments[i]; + /* eslint-disable-next-line prefer-rest-params */ + const callback = arguments[i]; logger.debug(context, 'Looking for device params %j', fields); - for (var p in registeredGroups) { + for (const p in registeredGroups) { if (registeredGroups.hasOwnProperty(p)) { - var found = 0; + let found = 0; - for (var j in queryObj) { - if (queryObj.hasOwnProperty(j) && - registeredGroups[p][j] === queryObj[j]) { + for (const j in queryObj) { + if (queryObj.hasOwnProperty(j) && registeredGroups[p][j] === queryObj[j]) { found++; } } @@ -210,12 +222,14 @@ function findBy(fields) { } function getSingleGroup(resource, apikey, callback) { - var result; + let result; - for (var i in registeredGroups) { - if (registeredGroups.hasOwnProperty(i) && + for (const i in registeredGroups) { + if ( + registeredGroups.hasOwnProperty(i) && registeredGroups[i].resource === resource && - registeredGroups[i].apikey === apikey) { + registeredGroups[i].apikey === apikey + ) { result = registeredGroups[i]; break; } @@ -229,11 +243,10 @@ function getSingleGroup(resource, apikey, callback) { } function getSingleGroupType(type, callback) { - var result; + let result; - for (var i in registeredGroups) { - if (registeredGroups.hasOwnProperty(i) && - registeredGroups[i].type === type) { + for (const i in registeredGroups) { + if (registeredGroups.hasOwnProperty(i) && registeredGroups[i].type === type) { result = registeredGroups[i]; break; } @@ -246,13 +259,11 @@ function getSingleGroupType(type, callback) { } } - - function update(id, body, callback) { - var groupToModify = registeredGroups[id]; + const groupToModify = registeredGroups[id]; if (groupToModify) { - for (var i in body) { + for (const i in body) { if (body.hasOwnProperty(i)) { groupToModify[i] = body[i]; } @@ -265,7 +276,7 @@ function update(id, body, callback) { } function remove(id, callback) { - var removedObject = registeredGroups[id]; + const removedObject = registeredGroups[id]; delete registeredGroups[id]; callback(null, removedObject); diff --git a/lib/services/groups/groupRegistryMongoDB.js b/lib/services/groups/groupRegistryMongoDB.js index 26720b828..325490b74 100644 --- a/lib/services/groups/groupRegistryMongoDB.js +++ b/lib/services/groups/groupRegistryMongoDB.js @@ -22,20 +22,19 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var logger = require('logops'), - dbService = require('../../model/dbConn'), - intoTrans = require('../common/domain').intoTrans, - fillService = require('./../common/domain').fillService, - alarmsInt = require('../common/alarmManagement').intercept, - constants = require('../../constants'), - errors = require('../../errors'), - Group = require('../../model/Group'), - async = require('async'), - context = { - op: 'IoTAgentNGSI.MongoDBGroupRegister' - }; + +const logger = require('logops'); +const dbService = require('../../model/dbConn'); +const intoTrans = require('../common/domain').intoTrans; +const fillService = require('./../common/domain').fillService; +const alarmsInt = require('../common/alarmManagement').intercept; +const constants = require('../../constants'); +const errors = require('../../errors'); +const Group = require('../../model/Group'); +const async = require('async'); +let context = { + op: 'IoTAgentNGSI.MongoDBGroupRegister' +}; /** * Generates a handler for the save device group operations. The handler will take the customary error and the saved @@ -44,6 +43,7 @@ var logger = require('logops'), * @return {Function} The generated handler. */ function saveGroupHandler(groupDAO, callback) { + /* eslint-disable-next-line no-unused-vars */ return function saveHandler(error, result) { if (error) { logger.debug(fillService(context, groupDAO), 'Error storing device group information: %s', error); @@ -56,41 +56,52 @@ function saveGroupHandler(groupDAO, callback) { } function createGroup(group, callback) { - var groupObj = new Group.model(), - attributeList = [ - 'url', - 'resource', - 'apikey', - 'type', - 'service', - 'subservice', - 'description', - 'trust', - 'cbHost', - 'timezone', - 'timestamp', - 'commands', - 'lazy', - 'attributes', - 'staticAttributes', - 'internalAttributes', - 'autoprovision', - 'explicitAttrs', - 'expressionLanguage' - ]; - - for (var i = 0; i < attributeList.length; i++) { + /* eslint-disable-next-line new-cap */ + const groupObj = new Group.model(); + const attributeList = [ + 'url', + 'resource', + 'apikey', + 'type', + 'service', + 'subservice', + 'description', + 'trust', + 'cbHost', + 'timezone', + 'timestamp', + 'commands', + 'lazy', + 'attributes', + 'staticAttributes', + 'internalAttributes', + 'autoprovision', + 'explicitAttrs', + 'expressionLanguage' + ]; + + for (let i = 0; i < attributeList.length; i++) { groupObj[attributeList[i]] = group[attributeList[i]]; } - logger.debug(context, 'Storing device group with id [%s], type [%s], apikey [%s] and resource [%s]', - groupObj._id, groupObj.type, groupObj.apikey, groupObj.resource); + logger.debug( + context, + 'Storing device group with id [%s], type [%s], apikey [%s] and resource [%s]', + groupObj._id, + groupObj.type, + groupObj.apikey, + groupObj.resource + ); groupObj.save(function saveHandler(error, groupDAO) { if (error) { if (error.code === 11000) { - logger.debug(context, 'Duplicate group entry with resource [%s] and apiKey [%s]', - group.resource, group.apikey); + logger.debug( + context, + 'Duplicate group entry with resource [%s] and apiKey [%s]', + group.resource, + group.apikey + ); callback(new errors.DuplicateGroup(group.resource, group.apikey)); } else { @@ -112,8 +123,7 @@ function createGroup(group, callback) { * @param {Number} offset Number of entries to skip for pagination. */ function listGroups(service, limit, offset, callback) { - var condition = {}, - query; + const condition = {}; function toObjectFn(obj) { return obj.toObject(); @@ -123,7 +133,7 @@ function listGroups(service, limit, offset, callback) { condition.service = service; } - query = Group.model.find(condition).sort(); + const query = Group.model.find(condition).sort(); if (limit) { query.limit(parseInt(limit, 10)); @@ -133,10 +143,10 @@ function listGroups(service, limit, offset, callback) { query.skip(parseInt(offset, 10)); } - async.series([ - query.exec.bind(query), - Group.model.countDocuments.bind(Group.model, condition) - ], function(error, results) { + async.series([query.exec.bind(query), Group.model.countDocuments.bind(Group.model, condition)], function ( + error, + results + ) { callback(error, { count: results[1], services: results[0].map(toObjectFn) @@ -145,13 +155,11 @@ function listGroups(service, limit, offset, callback) { } function getById(id, callback) { - var query; - - context = fillService(context, { service: 'n/a', subservice: 'n/a'}); + context = fillService(context, { service: 'n/a', subservice: 'n/a' }); logger.debug(context, 'Looking for device group with id [%s].', id); - query = Group.model.findOne({_id: id}); - query.select({__v: 0}); + const query = Group.model.findOne({ _id: id }); + query.select({ __v: 0 }); query.exec(function handleGet(error, data) { if (error) { @@ -178,8 +186,7 @@ function getById(id, callback) { * @param {Function} callback The callback function. */ function find(service, subservice, callback) { - var condition = {}, - query; + const condition = {}; function toObjectFn(obj) { return obj.toObject(); @@ -188,12 +195,12 @@ function find(service, subservice, callback) { condition.service = service; condition.subservice = subservice; - query = Group.model.find(condition).sort(); + const query = Group.model.find(condition).sort(); - async.series([ - query.exec.bind(query), - Group.model.countDocuments.bind(Group.model, condition) - ], function(error, results) { + async.series([query.exec.bind(query), Group.model.countDocuments.bind(Group.model, condition)], function ( + error, + results + ) { callback(error, { count: results[1], services: results[0].map(toObjectFn) @@ -201,14 +208,12 @@ function find(service, subservice, callback) { }); } - function findBy(fields) { - return function() { - var query, - queryObj = {}, - i = 0, - callback; + return function () { + const queryObj = {}; + let i = 0; + /* eslint-disable prefer-rest-params */ while (typeof arguments[i] !== 'function') { if (arguments[i]) { queryObj[fields[i]] = arguments[i]; @@ -216,13 +221,14 @@ function findBy(fields) { i++; } + const callback = arguments[i]; + /* eslint-enable prefer-rest-params */ - callback = arguments[i]; - context = fillService(context, { service: 'n/a', subservice: 'n/a'}); + context = fillService(context, { service: 'n/a', subservice: 'n/a' }); logger.debug(context, 'Looking for group params %j with queryObj %j', fields, queryObj); - query = Group.model.findOne(queryObj); + const query = Group.model.findOne(queryObj); - query.select({__v: 0}); + query.select({ __v: 0 }); query.exec(function handleGet(error, data) { if (error) { @@ -232,7 +238,6 @@ function findBy(fields) { context = fillService(context, data); logger.debug(context, 'Device group data found: %j', data.toObject()); callback(null, data.toObject()); - } else { logger.debug(context, 'Device group for fields [%j] not found: [%j]', fields, queryObj); @@ -244,11 +249,11 @@ function findBy(fields) { function update(id, body, callback) { logger.debug(context, 'Storing updated values for configuration [%s]:\n%s', id, JSON.stringify(body, null, 4)); - getById(id, function(error, group) { + getById(id, function (error, group) { if (error) { callback(error); } else { - var attributes = [ + const attributes = [ 'url', 'apikey', 'type', @@ -268,7 +273,7 @@ function update(id, body, callback) { 'expressionLanguage' ]; - for (var i = 0; i < attributes.length; i++) { + for (let i = 0; i < attributes.length; i++) { if (body[attributes[i]] !== undefined) { group[attributes[i]] = body[attributes[i]]; } @@ -283,11 +288,11 @@ function update(id, body, callback) { function remove(id, callback) { logger.debug(context, 'Removing device group with id [%s]', id); - getById(id, function(error, deviceGroup) { + getById(id, function (error, deviceGroup) { if (error) { callback(error); } else { - Group.model.deleteOne({ _id: id }, function(error) { + Group.model.deleteOne({ _id: id }, function (error) { if (error) { logger.debug(context, 'Internal MongoDB Error getting device: %s', error); @@ -314,8 +319,10 @@ exports.create = alarmsInt(constants.MONGO_ALARM, intoTrans(context, createGroup exports.list = alarmsInt(constants.MONGO_ALARM, intoTrans(context, listGroups)); exports.init = alarmsInt(constants.MONGO_ALARM, intoTrans(context, init)); exports.find = alarmsInt(constants.MONGO_ALARM, intoTrans(context, find)); -exports.findType = alarmsInt(constants.MONGO_ALARM, - intoTrans(context, findBy(['service', 'subservice', 'type', 'apikey']))); +exports.findType = alarmsInt( + constants.MONGO_ALARM, + intoTrans(context, findBy(['service', 'subservice', 'type', 'apikey'])) +); exports.findTypeSilently = intoTrans(context, findBy(['service', 'subservice', 'type', 'apikey'])); exports.findBy = alarmsInt(constants.MONGO_ALARM, intoTrans(context, findBy)); exports.get = alarmsInt(constants.MONGO_ALARM, intoTrans(context, findBy(['resource', 'apikey']))); diff --git a/lib/services/groups/groupService.js b/lib/services/groups/groupService.js index 892c2cfc7..de2417552 100644 --- a/lib/services/groups/groupService.js +++ b/lib/services/groups/groupService.js @@ -21,19 +21,17 @@ * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; - -var async = require('async'), - iotManagerService = require('./../common/iotManagerService'), - intoTrans = require('../common/domain').intoTrans, - apply = async.apply, - deviceService = require('../devices/deviceService'), - logger = require('logops'), - config = require('../../commonConfig'), - errors = require('../../errors'), - context = { - op: 'IoTAgentNGSI.DeviceGroupService' - }; +const async = require('async'); +const iotManagerService = require('./../common/iotManagerService'); +const intoTrans = require('../common/domain').intoTrans; +const apply = async.apply; +const deviceService = require('../devices/deviceService'); +const logger = require('logops'); +const config = require('../../commonConfig'); +const errors = require('../../errors'); +const context = { + op: 'IoTAgentNGSI.DeviceGroupService' +}; /** * Validate the Device Group: check mandatory params, and its check for duplicates with existing groups. This last @@ -43,11 +41,11 @@ var async = require('async'), * @param {Object} group Validate the device group */ function validateGroup(group, callback) { - var validations = []; + const validations = []; logger.debug(context, 'validateGroup %j', group); function generateDuplicateHandler(innerCb) { - return function(error, foundGroup) { + return function (error, foundGroup) { logger.debug(context, 'generateDuplicateHander error %s and foundGroup %j', error, foundGroup); if (!error || (foundGroup && foundGroup.count > 0)) { innerCb(new errors.DuplicateGroup(group.resource, group.apikey)); @@ -104,12 +102,12 @@ function validateGroup(group, callback) { * @param {Object} groupSet Set of device groups to add to the registry. */ function createGroup(groupSet, callback) { - var insertions = [], - insertedGroups = []; + const insertions = []; + const insertedGroups = []; logger.debug(context, 'Creating new set of %d services', groupSet.services.length); - for (var i = 0; i < groupSet.services.length; i++) { + for (let i = 0; i < groupSet.services.length; i++) { insertions.push(async.apply(validateGroup, groupSet.services[i])); insertions.push(async.apply(config.getGroupRegistry().create, groupSet.services[i])); insertedGroups.push(groupSet.services[i]); @@ -150,7 +148,8 @@ function checkServiceIdentity(service, subservice, deviceGroup, callback) { * @return {Function} A handler for the group related functions. */ function handleWithIotaRegistration(callback) { - return function(error, objectResult) { + /* eslint-disable-next-line no-unused-vars */ + return function (error, objectResult) { if (error) { callback(error); } else { @@ -173,7 +172,7 @@ function remove(service, subservice, resource, apikey, device, callback) { } function unregisterDevice(device, cb) { - deviceService.unregister(device.id, service, subservice, function(error) { + deviceService.unregister(device.id, service, subservice, function (error) { if (error) { cb(error); } @@ -181,19 +180,16 @@ function remove(service, subservice, resource, apikey, device, callback) { } function deleteDevices(device, service, subservice, id, callback) { - if(device) { + if (device) { deviceService.listDevices(service, subservice, function (error, devices) { if (error) { - callback(error); - } else { - if (devices && devices.count > 0){ - - async.map(devices.devices, unregisterDevice, function(error) { - if (error) { - callback(error); - } - }); - } + callback(error); + } else if (devices && devices.count > 0) { + async.map(devices.devices, unregisterDevice, function (error) { + if (error) { + callback(error); + } + }); } }); } @@ -201,13 +197,16 @@ function remove(service, subservice, resource, apikey, device, callback) { callback(null, id); } - async.waterfall([ - apply(config.getGroupRegistry().get, resource, apikey), - apply(checkServiceIdentity, service, subservice), - extractId, - apply(deleteDevices, device, service, subservice), - config.getGroupRegistry().remove - ], handleWithIotaRegistration(callback)); + async.waterfall( + [ + apply(config.getGroupRegistry().get, resource, apikey), + apply(checkServiceIdentity, service, subservice), + extractId, + apply(deleteDevices, device, service, subservice), + config.getGroupRegistry().remove + ], + handleWithIotaRegistration(callback) + ); } /** @@ -225,12 +224,15 @@ function update(service, subservice, resource, apikey, body, callback) { callback(null, deviceGroup._id, body); } - async.waterfall([ - apply(config.getGroupRegistry().get, resource, apikey), - apply(checkServiceIdentity, service, subservice), - extractId, - config.getGroupRegistry().update - ], handleWithIotaRegistration(callback)); + async.waterfall( + [ + apply(config.getGroupRegistry().get, resource, apikey), + apply(checkServiceIdentity, service, subservice), + extractId, + config.getGroupRegistry().update + ], + handleWithIotaRegistration(callback) + ); } /** @@ -277,16 +279,23 @@ function getGroupSilently(resource, apikey, callback) { * @param {String} type Type of the device. */ function getEffectiveApiKey(service, subservice, type, callback) { - logger.debug(context, 'Getting effective API Key for service [%s], subservice [%s] and type [%s]', - service, subservice, type); + logger.debug( + context, + 'Getting effective API Key for service [%s], subservice [%s] and type [%s]', + service, + subservice, + type + ); function handleFindGroup(error, group) { if (group) { logger.debug(context, 'Using found group: %j', group); callback(null, group.apikey); - } else if (config.getConfig().types && + } else if ( + config.getConfig().types && config.getConfig().types[type] && - config.getConfig().types[type].apikey) { + config.getConfig().types[type].apikey + ) { logger.debug(context, 'Using API Key for type [%s]: %s', type, config.getConfig().types[type].apikey); callback(null, config.getConfig().types[type].apikey); } else if (config.getConfig().defaultKey) { diff --git a/lib/services/ngsi/ngsiParser.js b/lib/services/ngsi/ngsiParser.js index b1b76bc97..012b03611 100644 --- a/lib/services/ngsi/ngsiParser.js +++ b/lib/services/ngsi/ngsiParser.js @@ -20,16 +20,11 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; -/*jshint unused:false*/ -var async = require('async'), - errors = require('../../errors'), - logger = require('logops'), - intoTrans = require('../common/domain').intoTrans, - context = { - op: 'IoTAgentNGSI.NGSIParser' - }; +const intoTrans = require('../common/domain').intoTrans; +const context = { + op: 'IoTAgentNGSI.NGSIParser' +}; /** * Given a NGSI Body, determines whether it contains any NGSI error. @@ -38,11 +33,10 @@ var async = require('async'), * @return {Number|*} */ function getErrorField(body) { - var errorField = body.errorCode || - body.orionError; + let errorField = body.errorCode || body.orionError; if (body && body.contextResponses) { - for (var i in body.contextResponses) { + for (const i in body.contextResponses) { if (body.contextResponses[i].statusCode && body.contextResponses[i].statusCode.code !== '200') { errorField = body.contextResponses[i].statusCode; } diff --git a/lib/services/ngsi/ngsiService.js b/lib/services/ngsi/ngsiService.js index 972c891d6..b24907d85 100644 --- a/lib/services/ngsi/ngsiService.js +++ b/lib/services/ngsi/ngsiService.js @@ -24,28 +24,28 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var request = require('request'), - statsService = require('./../stats/statsRegistry'), - async = require('async'), - apply = async.apply, - intoTrans = require('../common/domain').intoTrans, - fillService = require('./../common/domain').fillService, - alarms = require('../common/alarmManagement'), - errors = require('../../errors'), - utils = require('../northBound/restUtils'), - config = require('../../commonConfig'), - constants = require('../../constants'), - moment = require('moment-timezone'), - logger = require('logops'), - ngsiParser = require('./ngsiParser'), - _ = require('underscore'), - context = { - op: 'IoTAgentNGSI.NGSIService' - }, - updateMiddleware = [], - queryMiddleware = []; +/* eslint-disable no-prototype-builtins */ + +const request = require('request'); +const statsService = require('./../stats/statsRegistry'); +const async = require('async'); +const apply = async.apply; +const intoTrans = require('../common/domain').intoTrans; +const fillService = require('./../common/domain').fillService; +const alarms = require('../common/alarmManagement'); +const errors = require('../../errors'); +const utils = require('../northBound/restUtils'); +const config = require('../../commonConfig'); +const constants = require('../../constants'); +const moment = require('moment-timezone'); +const logger = require('logops'); +const ngsiParser = require('./ngsiParser'); +const _ = require('underscore'); +const context = { + op: 'IoTAgentNGSI.NGSIService' +}; +let updateMiddleware = []; +let queryMiddleware = []; /** * Generate an operation handler for NGSI-based operations (query and update). The handler takes care of identifiying @@ -62,32 +62,39 @@ var request = require('request'), * @return {Function} The generated handler. */ function generateNGSIOperationHandler(operationName, entityName, typeInformation, token, options, callback) { - return function(error, response, body) { + return function (error, response, body) { if (error) { logger.error(context, 'Error found executing ' + operationName + ' action in Context Broker: %s', error); alarms.raise(constants.ORION_ALARM, error); callback(error); } else if (body && body.orionError) { - logger.debug(context, 'Orion error found executing ' + operationName + ' action in Context Broker: %j', - body.orionError); + logger.debug( + context, + 'Orion error found executing ' + operationName + ' action in Context Broker: %j', + body.orionError + ); callback(new errors.BadRequest(body.orionError.details)); } else if (response && body && response.statusCode === 200) { - var errorField = ngsiParser.getErrorField(body); + const errorField = ngsiParser.getErrorField(body); - logger.debug(context, - 'Received the following request from the CB:\n\n%s\n\n', JSON.stringify(body, null, 4)); + logger.debug( + context, + 'Received the following request from the CB:\n\n%s\n\n', + JSON.stringify(body, null, 4) + ); if (errorField) { - logger.error(context, - 'Operation ' + operationName + ' error connecting to the Context Broker: %j', errorField); + logger.error( + context, + 'Operation ' + operationName + ' error connecting to the Context Broker: %j', + errorField + ); - if (errorField.code && errorField.code === '404' && - errorField.details.includes(typeInformation.type) ){ + if (errorField.code && errorField.code === '404' && errorField.details.includes(typeInformation.type)) { callback(new errors.DeviceNotFound(entityName)); - } - else if (errorField.code && errorField.code === '404') { + } else if (errorField.code && errorField.code === '404') { callback(new errors.AttributeNotFound()); } else { callback(new errors.EntityGenericError(entityName, typeInformation.type, errorField)); @@ -99,16 +106,26 @@ function generateNGSIOperationHandler(operationName, entityName, typeInformation } } else if (response && (response.statusCode === 403 || response.statusCode === 401)) { logger.debug(context, 'Access forbidden executing ' + operationName + ' operation'); - callback(new errors.AccessForbidden( - token, - options.headers['fiware-service'], - options.headers['fiware-servicepath'])); + callback( + new errors.AccessForbidden( + token, + options.headers['fiware-service'], + options.headers['fiware-servicepath'] + ) + ); } else { logger.debug(context, 'Unknown error executing ' + operationName + ' operation'); - callback(new errors.EntityGenericError(entityName, typeInformation.type, { - details: body - }, response.statusCode)); + callback( + new errors.EntityGenericError( + entityName, + typeInformation.type, + { + details: body + }, + response.statusCode + ) + ); } }; } @@ -128,68 +145,85 @@ function generateNGSIOperationHandler(operationName, entityName, typeInformation * @return {Function} The generated handler. */ function generateNGSI2OperationHandler(operationName, entityName, typeInformation, token, options, callback) { - return function(error, response, body) { + return function (error, response, body) { if (error) { logger.error(context, 'Error found executing ' + operationName + ' action in Context Broker: %s', error); alarms.raise(constants.ORION_ALARM, error); callback(error); } else if (body && body.orionError) { - logger.debug(context, 'Orion error found executing ' + operationName + ' action in Context Broker: %j', - body.orionError); + logger.debug( + context, + 'Orion error found executing ' + operationName + ' action in Context Broker: %j', + body.orionError + ); callback(new errors.BadRequest(body.orionError.details)); - } else if (response && operationName === 'update' && (response.statusCode === 204)) { - logger.info(context, 'Received the following response from the CB: Value updated successfully\n'); - alarms.release(constants.ORION_ALARM); - callback(null, body); + } else if (response && operationName === 'update' && response.statusCode === 204) { + logger.info(context, 'Received the following response from the CB: Value updated successfully\n'); + alarms.release(constants.ORION_ALARM); + callback(null, body); } else if (response && operationName === 'query' && body !== undefined && response.statusCode === 200) { - logger.info(context, - 'Received the following response from the CB:\n\n%s\n\n', JSON.stringify(body, null, 4)); - logger.debug(context, 'Value queried successfully'); - alarms.release(constants.ORION_ALARM); - callback(null, body); + logger.info( + context, + 'Received the following response from the CB:\n\n%s\n\n', + JSON.stringify(body, null, 4) + ); + logger.debug(context, 'Value queried successfully'); + alarms.release(constants.ORION_ALARM); + callback(null, body); } else if (response && operationName === 'query' && response.statusCode === 204) { - logger.info(context, - 'Received the following response from the CB:\n\n%s\n\n', JSON.stringify(body, null, 4)); + logger.info( + context, + 'Received the following response from the CB:\n\n%s\n\n', + JSON.stringify(body, null, 4) + ); - logger.error(context, - 'Operation ' + operationName + ' bad status code from the CB: 204.' + - 'A query operation must always return a body'); + logger.error( + context, + 'Operation ' + + operationName + + ' bad status code from the CB: 204.' + + 'A query operation must always return a body' + ); callback(new errors.BadAnswer(response.statusCode, operationName)); } else if (response && (response.statusCode === 403 || response.statusCode === 401)) { logger.debug(context, 'Access forbidden executing ' + operationName + ' operation'); - callback(new errors.AccessForbidden( - token, - options.headers['fiware-service'], - options.headers['fiware-servicepath'])); + callback( + new errors.AccessForbidden( + token, + options.headers['fiware-service'], + options.headers['fiware-servicepath'] + ) + ); } else if (response && body && response.statusCode === 404) { - logger.info(context, - 'Received the following response from the CB:\n\n%s\n\n', JSON.stringify(body, null, 4)); + logger.info( + context, + 'Received the following response from the CB:\n\n%s\n\n', + JSON.stringify(body, null, 4) + ); - logger.error(context, - 'Operation ' + operationName + ' error connecting to the Context Broker: %j', body); + logger.error(context, 'Operation ' + operationName + ' error connecting to the Context Broker: %j', body); - var errorField = ngsiParser.getErrorField(body); - if (response.statusCode && response.statusCode === 404 && - errorField.details.includes(typeInformation.type) ) { + const errorField = ngsiParser.getErrorField(body); + if ( + response.statusCode && + response.statusCode === 404 && + errorField.details.includes(typeInformation.type) + ) { callback(new errors.DeviceNotFound(entityName)); - } - else if (errorField.code && errorField.code === '404') { + } else if (errorField.code && errorField.code === '404') { callback(new errors.AttributeNotFound()); - } - else { + } else { callback(new errors.EntityGenericError(entityName, typeInformation.type, body)); } } else { logger.debug(context, 'Unknown error executing ' + operationName + ' operation'); - if (! (body instanceof Array || body instanceof Object)) - { + if (!(body instanceof Array || body instanceof Object)) { body = JSON.parse(body); } - callback(new errors.EntityGenericError(entityName, typeInformation.type, - body, response.statusCode)); + callback(new errors.EntityGenericError(entityName, typeInformation.type, body, response.statusCode)); } }; } @@ -203,13 +237,12 @@ function generateNGSI2OperationHandler(operationName, entityName, typeInformatio * @return {Object} Containing all the information of the request but the payload.c */ function createRequestObject(url, typeInformation, token) { - var cbHost = config.getConfig().contextBroker.url, - options, - serviceContext = {}, - headers = { - 'fiware-service': config.getConfig().service, - 'fiware-servicepath': config.getConfig().subservice - }; + let cbHost = config.getConfig().contextBroker.url; + const serviceContext = {}; + const headers = { + 'fiware-service': config.getConfig().service, + 'fiware-servicepath': config.getConfig().subservice + }; if (config.getConfig().authentication && config.getConfig().authentication.enabled) { headers[config.getConfig().authentication.header] = token; @@ -233,14 +266,13 @@ function createRequestObject(url, typeInformation, token) { } } - options = { + const options = { url: cbHost + url, method: 'POST', - headers: headers + headers }; - - return intoTrans(serviceContext, function() { + return intoTrans(serviceContext, function () { return options; })(); } @@ -255,7 +287,7 @@ function applyMiddlewares(middlewareCollection, entity, typeInformation, callbac } if (middlewareCollection && middlewareCollection.length > 0) { - var middlewareList = _.clone(middlewareCollection); + const middlewareList = _.clone(middlewareCollection); middlewareList.unshift(emptyMiddleware); middlewareList.push(endMiddleware); @@ -267,28 +299,29 @@ function applyMiddlewares(middlewareCollection, entity, typeInformation, callbac } function addTimestamp(payload, timezone) { - - var timestamp = { - name: constants.TIMESTAMP_ATTRIBUTE, - type: constants.TIMESTAMP_TYPE - }; + const timestamp = { + name: constants.TIMESTAMP_ATTRIBUTE, + type: constants.TIMESTAMP_TYPE + }; if (!timezone) { - timestamp.value = (new Date()).toISOString(); + timestamp.value = new Date().toISOString(); } else { timestamp.value = moment().tz(timezone).format('YYYY-MM-DD[T]HH:mm:ss.SSSZ'); } function addMetadata(attribute) { - var timestampFound = false; + let timestampFound = false; if (!attribute.metadatas) { attribute.metadatas = []; } - for (var i = 0; i < attribute.metadatas.length; i++) { - if (attribute.metadatas[i].type === constants.TIMESTAMP_TYPE && - attribute.metadatas[i].name === constants.TIMESTAMP_ATTRIBUTE) { + for (let i = 0; i < attribute.metadatas.length; i++) { + if ( + attribute.metadatas[i].type === constants.TIMESTAMP_TYPE && + attribute.metadatas[i].name === constants.TIMESTAMP_ATTRIBUTE + ) { attribute.metadatas[i].value = timestamp.value; timestampFound = true; break; @@ -308,33 +341,33 @@ function addTimestamp(payload, timezone) { } function addTimestampNgsi2(payload, timezone) { - function addTimestampEntity(entity, timezone) { - - var timestamp = { - type: constants.TIMESTAMP_TYPE_NGSI2 - }; + const timestamp = { + type: constants.TIMESTAMP_TYPE_NGSI2 + }; if (!timezone) { - timestamp.value = (new Date()).toISOString(); + timestamp.value = new Date().toISOString(); } else { timestamp.value = moment().tz(timezone).format('YYYY-MM-DD[T]HH:mm:ss.SSSZ'); } function addMetadata(attribute) { - var timestampFound = false; + let timestampFound = false; if (!attribute.metadata) { attribute.metadata = {}; } - for (var i = 0; i < attribute.metadata.length; i++) { + for (let i = 0; i < attribute.metadata.length; i++) { if (attribute.metadata[i] === constants.TIMESTAMP_ATTRIBUTE) { - if (attribute.metadata[constants.TIMESTAMP_ATTRIBUTE].type === constants.TIMESTAMP_TYPE_NGSI2 && - attribute.metadata[constants.TIMESTAMP_ATTRIBUTE].value === timestamp.value) { - timestampFound = true; - break; - } + if ( + attribute.metadata[constants.TIMESTAMP_ATTRIBUTE].type === constants.TIMESTAMP_TYPE_NGSI2 && + attribute.metadata[constants.TIMESTAMP_ATTRIBUTE].value === timestamp.value + ) { + timestampFound = true; + break; + } } } @@ -344,8 +377,8 @@ function addTimestampNgsi2(payload, timezone) { return attribute; } - var keyCount = 0; - for (var key in entity) { + let keyCount = 0; + for (const key in entity) { if (entity.hasOwnProperty(key) && key !== 'id' && key !== 'type') { addMetadata(entity[key]); keyCount += 1; @@ -361,44 +394,41 @@ function addTimestampNgsi2(payload, timezone) { } if (payload instanceof Array) { - for (var i = 0; i < payload.length; i++) { + for (let i = 0; i < payload.length; i++) { if (!utils.isTimestampedNgsi2(payload[i])) { payload[i] = addTimestampEntity(payload[i], timezone); } } return payload; - } else { - return addTimestampEntity(payload, timezone); } - + return addTimestampEntity(payload, timezone); } -function getMetaData(typeInformation, name, metadata){ - if(metadata){ +function getMetaData(typeInformation, name, metadata) { + if (metadata) { return metadata; } - var i; - if(typeInformation.active){ + let i; + if (typeInformation.active) { for (i = 0; i < typeInformation.active.length; i++) { /* jshint camelcase: false */ - if (name === typeInformation.active[i].object_id){ - return typeInformation.active[i].metadata; + if (name === typeInformation.active[i].object_id) { + return typeInformation.active[i].metadata; } } } - if(typeInformation.staticAttributes){ + if (typeInformation.staticAttributes) { for (i = 0; i < typeInformation.staticAttributes.length; i++) { - if (name === typeInformation.staticAttributes[i].name){ - return typeInformation.staticAttributes[i].metadata; + if (name === typeInformation.staticAttributes[i].name) { + return typeInformation.staticAttributes[i].metadata; } } } return undefined; } - /** * It casts attribute values which are reported using JSON native types * @@ -406,7 +436,6 @@ function getMetaData(typeInformation, name, metadata){ * @return {String} New payload where attributes's values are casted to the corresponding JSON types */ function castJsonNativeAttributes(payload) { - /** * Determines if a value is of type float * @@ -421,27 +450,31 @@ function castJsonNativeAttributes(payload) { return payload; } - for (var key in payload) { - if (payload.hasOwnProperty(key) && payload[key].value && - payload[key].type && typeof(payload[key].value) === 'string') { + for (const key in payload) { + if ( + payload.hasOwnProperty(key) && + payload[key].value && + payload[key].type && + typeof payload[key].value === 'string' + ) { if (payload[key].type === 'Number' && isFloat(payload[key].value)) { payload[key].value = Number.parseFloat(payload[key].value); } else if (payload[key].type === 'Number' && Number.parseInt(payload[key].value)) { payload[key].value = Number.parseInt(payload[key].value); - } - else if (payload[key].type === 'Boolean') { - payload[key].value = (payload[key].value === 'true' || payload[key].value === '1'); - } - else if (payload[key].type === 'None') { + } else if (payload[key].type === 'Boolean') { + payload[key].value = payload[key].value === 'true' || payload[key].value === '1'; + } else if (payload[key].type === 'None') { payload[key].value = null; - } - else if (payload[key].type === 'Array' || payload[key].type === 'Object') { + } else if (payload[key].type === 'Array' || payload[key].type === 'Object') { try { - var parsedValue = JSON.parse(payload[key].value); + const parsedValue = JSON.parse(payload[key].value); payload[key].value = parsedValue; } catch (e) { - logger.error(context, 'Bad attribute value type.' + - 'Expecting JSON Array or JSON Object. Received:%s', payload[key].value); + logger.error( + context, + 'Bad attribute value type. Expecting JSON Array or JSON Object. Received:%s', + payload[key].value + ); } } } @@ -460,17 +493,15 @@ function castJsonNativeAttributes(payload) { * @param {String} token User token to identify against the PEP Proxies (optional). */ function sendUpdateValueNgsi2(entityName, attributes, typeInformation, token, callback) { + let payload = {}; - var payload = {}; - - var url = '/v2/entities/' + entityName + '/attrs'; + let url = '/v2/entities/' + entityName + '/attrs'; if (typeInformation.type) { - url += '?type=' + typeInformation.type; + url += '?type=' + typeInformation.type; } - var options = createRequestObject(url, typeInformation, token); - + let options = createRequestObject(url, typeInformation, token); if (typeInformation && typeInformation.staticAttributes) { attributes = attributes.concat(typeInformation.staticAttributes); @@ -484,14 +515,14 @@ function sendUpdateValueNgsi2(entityName, attributes, typeInformation, token, ca payload.id = entityName; payload.type = typeInformation.type; - for (var i = 0; i < attributes.length; i++) { + for (let i = 0; i < attributes.length; i++) { if (attributes[i].name && attributes[i].type) { payload[attributes[i].name] = { - 'value' : attributes[i].value, - 'type' : attributes[i].type + value: attributes[i].value, + type: attributes[i].type }; - var metadata = getMetaData(typeInformation, attributes[i].name, attributes[i].metadata); - if (metadata){ + const metadata = getMetaData(typeInformation, attributes[i].name, attributes[i].metadata); + if (metadata) { payload[attributes[i].name].metadata = metadata; } } else { @@ -501,96 +532,104 @@ function sendUpdateValueNgsi2(entityName, attributes, typeInformation, token, ca } payload = castJsonNativeAttributes(payload); - async.waterfall([ - apply(statsService.add, 'measureRequests', 1), - apply(applyMiddlewares, updateMiddleware, payload, typeInformation)], - function(error, result) { - if (error) { - callback(error); - } else { - if (result) { - // The payload has been transformed by multientity plugin. It is not a JSON object but an Array. - if (result instanceof Array) { - options = createRequestObject( - '/v2/op/update', - typeInformation, - token); - - if ( ('timestamp' in typeInformation && typeInformation.timestamp !== - undefined) ? typeInformation.timestamp : config.getConfig().timestamp) { - // jshint maxdepth:5 - if (!utils.isTimestampedNgsi2(result)) { - options.json = addTimestampNgsi2(result, typeInformation.timezone); - // jshint maxdepth:5 - } else if (!utils.IsValidTimestampedNgsi2(result)) { - logger.error(context, 'Invalid timestamp:%s', JSON.stringify(result)); - callback(new errors.BadTimestamp(result)); - return; + async.waterfall( + [ + apply(statsService.add, 'measureRequests', 1), + apply(applyMiddlewares, updateMiddleware, payload, typeInformation) + ], + function (error, result) { + if (error) { + callback(error); + } else { + if (result) { + // The payload has been transformed by multientity plugin. It is not a JSON object but an Array. + if (result instanceof Array) { + options = createRequestObject('/v2/op/update', typeInformation, token); + + if ( + 'timestamp' in typeInformation && typeInformation.timestamp !== undefined + ? typeInformation.timestamp + : config.getConfig().timestamp + ) { + // jshint maxdepth:5 + if (!utils.isTimestampedNgsi2(result)) { + options.json = addTimestampNgsi2(result, typeInformation.timezone); + // jshint maxdepth:5 + } else if (!utils.IsValidTimestampedNgsi2(result)) { + logger.error(context, 'Invalid timestamp:%s', JSON.stringify(result)); + callback(new errors.BadTimestamp(result)); + return; + } } - } - options.json = { - actionType: 'append', - entities: result - }; - } else { - delete result.id; - delete result.type; - options.json = result; - logger.debug(context, 'typeInformation: %j', typeInformation); - if ( ('timestamp' in typeInformation && typeInformation.timestamp !== - undefined) ? typeInformation.timestamp : config.getConfig().timestamp) { - if (!utils.isTimestampedNgsi2(options.json)) { - options.json = addTimestampNgsi2(options.json, typeInformation.timezone); - } else if (!utils.IsValidTimestampedNgsi2(options.json)) { - logger.error(context, 'Invalid timestamp:%s', JSON.stringify(options.json)); - callback(new errors.BadTimestamp(options.json)); - return; + options.json = { + actionType: 'append', + entities: result + }; + } else { + delete result.id; + delete result.type; + options.json = result; + logger.debug(context, 'typeInformation: %j', typeInformation); + if ( + 'timestamp' in typeInformation && typeInformation.timestamp !== undefined + ? typeInformation.timestamp + : config.getConfig().timestamp + ) { + if (!utils.isTimestampedNgsi2(options.json)) { + options.json = addTimestampNgsi2(options.json, typeInformation.timezone); + } else if (!utils.IsValidTimestampedNgsi2(options.json)) { + logger.error(context, 'Invalid timestamp:%s', JSON.stringify(options.json)); + callback(new errors.BadTimestamp(options.json)); + return; + } } } + } else { + delete payload.id; + delete payload.type; + options.json = payload; } - } else { - delete payload.id; - delete payload.type; - options.json = payload; - } - // Purge object_id from entities before sent to CB - // object_id was added by createNgsi2Entity to allow multientity - // with duplicate attribute names. - var att; - if (options.json.entities) { - for (var entity = 0; entity < options.json.entities.length; entity++) { - for (att in options.json.entities[entity]) { - /*jshint camelcase: false */ - if (options.json.entities[entity][att].object_id) { + // Purge object_id from entities before sent to CB + // object_id was added by createNgsi2Entity to allow multientity + // with duplicate attribute names. + let att; + if (options.json.entities) { + for (let entity = 0; entity < options.json.entities.length; entity++) { + for (att in options.json.entities[entity]) { /*jshint camelcase: false */ - delete options.json.entities[entity][att].object_id; - } - if (options.json.entities[entity][att].multi) { - delete options.json.entities[entity][att].multi; + if (options.json.entities[entity][att].object_id) { + /*jshint camelcase: false */ + delete options.json.entities[entity][att].object_id; + } + if (options.json.entities[entity][att].multi) { + delete options.json.entities[entity][att].multi; + } } } - } - } else { - for (att in options.json) { - /*jshint camelcase: false */ - if (options.json[att].object_id) { + } else { + for (att in options.json) { /*jshint camelcase: false */ - delete options.json[att].object_id; - } - if (options.json[att].multi) { - delete options.json[att].multi; + if (options.json[att].object_id) { + /*jshint camelcase: false */ + delete options.json[att].object_id; + } + if (options.json[att].multi) { + delete options.json[att].multi; + } } } - } - logger.info(context, 'Updating device value in the Context Broker at [%s]', options.url); - logger.info(context, 'Using the following request:\n\n%s\n\n', JSON.stringify(options, null, 4)); + logger.info(context, 'Updating device value in the Context Broker at [%s]', options.url); + logger.info(context, 'Using the following request:\n\n%s\n\n', JSON.stringify(options, null, 4)); - request(options, - generateNGSI2OperationHandler('update', entityName, typeInformation, token, options, callback)); + request( + options, + generateNGSI2OperationHandler('update', entityName, typeInformation, token, options, callback) + ); + } } - }); + ); } /** @@ -603,8 +642,7 @@ function sendUpdateValueNgsi2(entityName, attributes, typeInformation, token, ca * @param {String} token User token to identify against the PEP Proxies (optional). */ function sendUpdateValueNgsi1(entityName, attributes, typeInformation, token, callback) { - var options = createRequestObject('/v1/updateContext', typeInformation, token), - payload; + const options = createRequestObject('/v1/updateContext', typeInformation, token); if (typeInformation && typeInformation.staticAttributes) { attributes = attributes.concat(typeInformation.staticAttributes); @@ -615,55 +653,66 @@ function sendUpdateValueNgsi1(entityName, attributes, typeInformation, token, ca return; } - payload = { - contextElements: [ - { - type: typeInformation.type, - isPattern: 'false', - id: entityName, - attributes: attributes - } - ] + const payload = { + contextElements: [ + { + type: typeInformation.type, + isPattern: 'false', + id: entityName, + attributes + } + ] }; - if ('autoprovision' in typeInformation && + if ( + 'autoprovision' in typeInformation && /* jshint -W101 */ - typeInformation.autoprovision === undefined ? typeInformation.autoprovision === true : config.getConfig().appendMode === true) { + typeInformation.autoprovision === undefined + ? typeInformation.autoprovision === true + : config.getConfig().appendMode === true + ) { payload.updateAction = 'APPEND'; } else { payload.updateAction = 'UPDATE'; } - async.waterfall([ - apply(statsService.add, 'measureRequests', 1), - apply(applyMiddlewares, updateMiddleware, payload, typeInformation) - ], function(error, result) { - if (error) { - callback(error); - } else { - if (result) { - options.json = result; + async.waterfall( + [ + apply(statsService.add, 'measureRequests', 1), + apply(applyMiddlewares, updateMiddleware, payload, typeInformation) + ], + function (error, result) { + if (error) { + callback(error); } else { - options.json = payload; - } - - if ( ('timestamp' in typeInformation && typeInformation.timestamp !== undefined) ? - typeInformation.timestamp : config.getConfig().timestamp) { - if (!utils.isTimestamped(options.json)) { - options.json = addTimestamp(options.json, typeInformation.timezone); - } else if (!utils.IsValidTimestamped(options.json)) { - logger.error(context, 'Invalid timestamp:%s', JSON.stringify(options.json)); - callback(new errors.BadTimestamp(options.json)); - return; + if (result) { + options.json = result; + } else { + options.json = payload; } - } + if ( + 'timestamp' in typeInformation && typeInformation.timestamp !== undefined + ? typeInformation.timestamp + : config.getConfig().timestamp + ) { + if (!utils.isTimestamped(options.json)) { + options.json = addTimestamp(options.json, typeInformation.timezone); + } else if (!utils.IsValidTimestamped(options.json)) { + logger.error(context, 'Invalid timestamp:%s', JSON.stringify(options.json)); + callback(new errors.BadTimestamp(options.json)); + return; + } + } - logger.debug(context, 'Updating device value in the Context Broker at [%s]', options.url); - logger.debug(context, 'Using the following request:\n\n%s\n\n', JSON.stringify(options, null, 4)); + logger.debug(context, 'Updating device value in the Context Broker at [%s]', options.url); + logger.debug(context, 'Using the following request:\n\n%s\n\n', JSON.stringify(options, null, 4)); - request(options, - generateNGSIOperationHandler('update', entityName, typeInformation, token, options, callback)); + request( + options, + generateNGSIOperationHandler('update', entityName, typeInformation, token, options, callback) + ); + } } - }); + ); } /** @@ -693,12 +742,12 @@ function sendUpdateValue(entityName, attributes, typeInformation, token, callbac * @param {String} token User token to identify against the PEP Proxies (optional). */ function sendQueryValueNgsi2(entityName, attributes, typeInformation, token, callback) { - var url = '/v2/entities/' + entityName + '/attrs'; + let url = '/v2/entities/' + entityName + '/attrs'; if (attributes && attributes.length > 0) { - var attributesQueryParam = ''; + let attributesQueryParam = ''; - for (var i = 0; i < attributes.length; i++) { + for (let i = 0; i < attributes.length; i++) { attributesQueryParam = attributesQueryParam + attributes[i]; if (i < attributes.length - 1) { attributesQueryParam = attributesQueryParam + ','; @@ -716,7 +765,7 @@ function sendQueryValueNgsi2(entityName, attributes, typeInformation, token, cal } } - var options = createRequestObject(url, typeInformation, token); + const options = createRequestObject(url, typeInformation, token); options.method = 'GET'; options.json = true; @@ -728,16 +777,16 @@ function sendQueryValueNgsi2(entityName, attributes, typeInformation, token, cal logger.debug(context, 'Querying values of the device in the Context Broker at [%s]', options.url); logger.debug(context, 'Using the following request:\n\n%s\n\n', JSON.stringify(options, null, 4)); - - request(options, - generateNGSI2OperationHandler('query', entityName, typeInformation, token, options, - function(error, result) { - if (error) { - callback(error); - } else { - applyMiddlewares(queryMiddleware, result, typeInformation, callback); - } - })); + request( + options, + generateNGSI2OperationHandler('query', entityName, typeInformation, token, options, function (error, result) { + if (error) { + callback(error); + } else { + applyMiddlewares(queryMiddleware, result, typeInformation, callback); + } + }) + ); } /** @@ -750,7 +799,7 @@ function sendQueryValueNgsi2(entityName, attributes, typeInformation, token, cal * @param {String} token User token to identify against the PEP Proxies (optional). */ function sendQueryValueNgsi1(entityName, attributes, typeInformation, token, callback) { - var options = createRequestObject('/v1/queryContext', typeInformation, token); + const options = createRequestObject('/v1/queryContext', typeInformation, token); if (!typeInformation || !typeInformation.type) { callback(new errors.TypeNotFound(null, entityName)); @@ -758,29 +807,29 @@ function sendQueryValueNgsi1(entityName, attributes, typeInformation, token, cal } options.json = { - entities: [ - { - type: typeInformation.type, - isPattern: 'false', - id: entityName - } - ], - attributes: attributes - }; + entities: [ + { + type: typeInformation.type, + isPattern: 'false', + id: entityName + } + ], + attributes + }; logger.debug(context, 'Querying values of the device in the Context Broker at [%s]', options.url); logger.debug(context, 'Using the following request:\n\n%s\n\n', JSON.stringify(options, null, 4)); - - request(options, - generateNGSIOperationHandler('query', entityName, typeInformation, token, options, - function(error, result) { - if (error) { - callback(error); - } else { - applyMiddlewares(queryMiddleware, result, typeInformation, callback); - } - })); + request( + options, + generateNGSIOperationHandler('query', entityName, typeInformation, token, options, function (error, result) { + if (error) { + callback(error); + } else { + applyMiddlewares(queryMiddleware, result, typeInformation, callback); + } + }) + ); } /** @@ -814,11 +863,12 @@ function sendQueryValue(entityName, attributes, typeInformation, token, callback function updateTrust(deviceGroup, deviceInformation, trust, response, callback) { if (deviceGroup && response && response.body && !config.getConfig().authentication.permanentToken) { - var body = JSON.parse(response.body); + const body = JSON.parse(response.body); /* jshint camelcase: false */ if (body && body.refresh_token) { deviceGroup.trust = body.refresh_token; - config.getGroupRegistry().update(deviceGroup._id, deviceGroup, function(error, cb) { + /* eslint-disable-next-line no-unused-vars */ + config.getGroupRegistry().update(deviceGroup._id, deviceGroup, function (error, cb) { callback(null, response); }); } else { @@ -838,14 +888,19 @@ function updateTrust(deviceGroup, deviceInformation, trust, response, callback) * @return {Function} The function that gets all the information wrapping the given operation. */ function executeWithDeviceInformation(operationFunction) { - - return function(entityName, type, apikey, attributes, deviceInformation, callback) { + return function (entityName, type, apikey, attributes, deviceInformation, callback) { fillService(context, deviceInformation); - logger.debug(context, + logger.debug( + context, 'executeWithDeviceInfo entityName %s type %s apikey %s attributes %j deviceInformation %j', - entityName, type, apikey, attributes, deviceInformation); - config.getGroupRegistry().getType(type, function(error, deviceGroup) { - var typeInformation; + entityName, + type, + apikey, + attributes, + deviceInformation + ); + config.getGroupRegistry().getType(type, function (error, deviceGroup) { + let typeInformation; if (error) { logger.debug(context, 'error %j in get group device', error); } @@ -866,21 +921,24 @@ function executeWithDeviceInformation(operationFunction) { typeInformation.trust = config.getConfig().types[type].trust; } - if(deviceGroup && deviceGroup.cbHost) { + if (deviceGroup && deviceGroup.cbHost) { typeInformation.cbHost = deviceGroup.cbHost; } } } if (config.getConfig().authentication && config.getConfig().authentication.enabled) { - var security = config.getSecurityService(); + const security = config.getSecurityService(); if (typeInformation && typeInformation.trust) { - async.waterfall([ - apply(security.auth, typeInformation.trust), - apply(updateTrust, deviceGroup, deviceInformation, typeInformation.trust), - apply(security.getToken, typeInformation.trust), - apply(operationFunction, entityName, attributes, typeInformation) - ], callback); + async.waterfall( + [ + apply(security.auth, typeInformation.trust), + apply(updateTrust, deviceGroup, deviceInformation, typeInformation.trust), + apply(security.getToken, typeInformation.trust), + apply(operationFunction, entityName, attributes, typeInformation) + ], + callback + ); } else { callback(new errors.SecurityInformationMissing(typeInformation.type)); } @@ -903,25 +961,31 @@ function executeWithDeviceInformation(operationFunction) { * @param {String} commandResult Result of the command in string format. * @param {Object} deviceInformation Device information, including security and service information. (optional). */ -function setCommandResult(entityName, resource, apikey, commandName, - commandResult, status, deviceInformation, callback) { - - config.getGroupRegistry().get(resource, apikey, function(error, deviceGroup) { - var typeInformation, - commandInfo, - attributes = [ - { - name: commandName + constants.COMMAND_STATUS_SUFIX, - type: constants.COMMAND_STATUS, - value: status - }, - { - name: commandName + constants.COMMAND_RESULT_SUFIX, - type: constants.COMMAND_RESULT, - value: commandResult - } - ]; - +function setCommandResult( + entityName, + resource, + apikey, + commandName, + commandResult, + status, + deviceInformation, + callback +) { + config.getGroupRegistry().get(resource, apikey, function (error, deviceGroup) { + let typeInformation; + let commandInfo; + const attributes = [ + { + name: commandName + constants.COMMAND_STATUS_SUFIX, + type: constants.COMMAND_STATUS, + value: status + }, + { + name: commandName + constants.COMMAND_RESULT_SUFIX, + type: constants.COMMAND_RESULT, + value: commandResult + } + ]; if (!callback) { callback = deviceInformation; @@ -951,21 +1015,14 @@ function setCommandResult(entityName, resource, apikey, commandName, typeInformation.subservice = config.getConfig().subservice; } - commandInfo = _.where(typeInformation.commands, {name: commandName}); + commandInfo = _.where(typeInformation.commands, { name: commandName }); - if(deviceGroup && commandInfo.length !== 1){ - commandInfo = _.where(deviceGroup.commands, {name: commandName}); + if (deviceGroup && commandInfo.length !== 1) { + commandInfo = _.where(deviceGroup.commands, { name: commandName }); } if (commandInfo.length === 1) { - exports.update( - entityName, - resource, - apikey, - attributes, - typeInformation, - callback - ); + exports.update(entityName, resource, apikey, attributes, typeInformation, callback); } else { callback(new errors.CommandNotFound(commandName)); } diff --git a/lib/services/ngsi/subscriptionService.js b/lib/services/ngsi/subscriptionService.js index e1e5a3799..29efc300a 100644 --- a/lib/services/ngsi/subscriptionService.js +++ b/lib/services/ngsi/subscriptionService.js @@ -24,17 +24,14 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var errors = require('../../errors'), - intoTrans = require('../common/domain').intoTrans, - logger = require('logops'), - config = require('../../commonConfig'), - deviceService = require('../devices/deviceService'), - context = { - op: 'IoTAgentNGSI.NGSIService' - }; - +const errors = require('../../errors'); +const intoTrans = require('../common/domain').intoTrans; +const logger = require('logops'); +const config = require('../../commonConfig'); +const deviceService = require('../devices/deviceService'); +const context = { + op: 'IoTAgentNGSI.NGSIService' +}; /** * Generate a new subscription request handler using NGSIv1, based on the device and triggers given to the function. @@ -46,27 +43,41 @@ var errors = require('../../errors'), * @return {Function} Returns a request handler for the given data. */ function createSubscriptionHandlerNgsi1(device, triggers, store, callback) { - return function(error, response, body) { + return function (error, response, body) { if (error || !body) { logger.debug( context, - 'Transport error found subscribing device with id [%s] to entity [%s]', device.id, device.name); + 'Transport error found subscribing device with id [%s] to entity [%s]', + device.id, + device.name + ); callback(error); - } else if (response.statusCode !== 200 && response.statusCode !== 201) { - logger.debug(context, 'Unknown error subscribing device with id [%s] to entity [%s]: $s', - response.statusCode); - - callback(new errors.EntityGenericError(device.name, device.type, { - details: body - }, response.statusCode)); + logger.debug( + context, + 'Unknown error subscribing device with id [%s] to entity [%s]: $s', + response.statusCode + ); + callback( + new errors.EntityGenericError( + device.name, + device.type, + { + details: body + }, + response.statusCode + ) + ); } else if (body && body.orionError) { logger.debug( context, 'Orion found subscribing device with id [%s] to entity [%s]: %s', - device.id, device.name, body.orionError); + device.id, + device.name, + body.orionError + ); callback(new errors.BadRequest(body.orionError.details)); } else if (store) { @@ -76,7 +87,7 @@ function createSubscriptionHandlerNgsi1(device, triggers, store, callback) { device.subscriptions.push({ id: body.subscribeResponse.subscriptionId, - triggers: triggers + triggers }); config.getRegistry().update(device, callback); @@ -96,27 +107,41 @@ function createSubscriptionHandlerNgsi1(device, triggers, store, callback) { * @return {Function} Returns a request handler for the given data. */ function createSubscriptionHandlerNgsi2(device, triggers, store, callback) { - return function(error, response, body) { + return function (error, response, body) { if (error) { logger.debug( context, - 'Transport error found subscribing device with id [%s] to entity [%s]', device.id, device.name); + 'Transport error found subscribing device with id [%s] to entity [%s]', + device.id, + device.name + ); callback(error); - } else if (response.statusCode !== 200 && response.statusCode !== 201) { - logger.debug(context, 'Unknown error subscribing device with id [%s] to entity [%s]: $s', - response.statusCode); - - callback(new errors.EntityGenericError(device.name, device.type, { - details: body - }, response.statusCode)); + logger.debug( + context, + 'Unknown error subscribing device with id [%s] to entity [%s]: $s', + response.statusCode + ); + callback( + new errors.EntityGenericError( + device.name, + device.type, + { + details: body + }, + response.statusCode + ) + ); } else if (body && body.orionError) { logger.debug( context, 'Orion found subscribing device with id [%s] to entity [%s]: %s', - device.id, device.name, body.orionError); + device.id, + device.name, + body.orionError + ); callback(new errors.BadRequest(body.orionError.details)); } else if (store) { @@ -126,7 +151,7 @@ function createSubscriptionHandlerNgsi2(device, triggers, store, callback) { device.subscriptions.push({ id: response.headers.location.substr(response.headers.location.lastIndexOf('/') + 1), - triggers: triggers + triggers }); config.getRegistry().update(device, callback); @@ -146,31 +171,31 @@ function createSubscriptionHandlerNgsi2(device, triggers, store, callback) { * @param {Object} content Array with the names of the attributes to retrieve in the notification. */ function subscribeNgsi1(device, triggers, content, callback) { - var options = { + const options = { method: 'POST', headers: { 'fiware-service': device.service, 'fiware-servicepath': device.subservice }, json: { - entities: [ - { - type: device.type, - isPattern: 'false', - id: device.name - } - ], - reference: config.getConfig().providerUrl + '/notify', - duration: config.getConfig().deviceRegistrationDuration || 'P100Y', - notifyConditions: [ - { - type: 'ONCHANGE', - condValues: triggers - } - ] - } - }, - store = true; + entities: [ + { + type: device.type, + isPattern: 'false', + id: device.name + } + ], + reference: config.getConfig().providerUrl + '/notify', + duration: config.getConfig().deviceRegistrationDuration || 'P100Y', + notifyConditions: [ + { + type: 'ONCHANGE', + condValues: triggers + } + ] + } + }; + let store = true; if (content) { options.json.attributes = content; @@ -184,8 +209,11 @@ function subscribeNgsi1(device, triggers, content, callback) { } else { options.uri = config.getConfig().contextBroker.url + '/v1/subscribeContext'; } - deviceService.executeWithSecurity(options, - device, createSubscriptionHandlerNgsi1(device, triggers, store, callback)); + deviceService.executeWithSecurity( + options, + device, + createSubscriptionHandlerNgsi1(device, triggers, store, callback) + ); } /** @@ -198,37 +226,36 @@ function subscribeNgsi1(device, triggers, content, callback) { * @param {Object} content Array with the names of the attributes to retrieve in the notification. */ function subscribeNgsi2(device, triggers, content, callback) { - var options = { + const options = { method: 'POST', headers: { 'fiware-service': device.service, 'fiware-servicepath': device.subservice }, json: { - subject: - { - entities: [ - { - id: device.name, - type: device.type - } - ], - - condition: { - attrs: triggers - }, - }, - notification: { - http: { - url: config.getConfig().providerUrl + '/notify' - }, - attrs: content || [], - attrsFormat: 'normalized' + subject: { + entities: [ + { + id: device.name, + type: device.type + } + ], + + condition: { + attrs: triggers } + }, + notification: { + http: { + url: config.getConfig().providerUrl + '/notify' + }, + attrs: content || [], + attrsFormat: 'normalized' + } } }; - var store = true; + let store = true; if (content) { store = false; @@ -241,8 +268,11 @@ function subscribeNgsi2(device, triggers, content, callback) { } else { options.uri = config.getConfig().contextBroker.url + '/v2/subscriptions'; } - deviceService.executeWithSecurity(options, - device, createSubscriptionHandlerNgsi2(device, triggers, store, callback)); + deviceService.executeWithSecurity( + options, + device, + createSubscriptionHandlerNgsi2(device, triggers, store, callback) + ); } /** @@ -272,29 +302,41 @@ function subscribe(device, triggers, content, callback) { * @return {Function} Returns a request handler for the given data. */ function createUnsubscribeHandlerNgsi1(device, id, callback) { - return function(error, response, body) { + return function (error, response, body) { if (error || !body) { logger.debug( context, - 'Transport error found subscribing device with id [%s] to entity [%s]', device.id, device.name); + 'Transport error found subscribing device with id [%s] to entity [%s]', + device.id, + device.name + ); callback(error); - } else if (response.statusCode !== 200 && response.statusCode !== 201) { logger.debug( context, 'Unknown error subscribing device with id [%s] to entity [%s]: $s', - response.statusCode); - - callback(new errors.EntityGenericError(device.name, device.type, { - details: body - }, response.statusCode)); + response.statusCode + ); + callback( + new errors.EntityGenericError( + device.name, + device.type, + { + details: body + }, + response.statusCode + ) + ); } else if (body && body.orionError) { logger.debug( context, 'Orion found subscribing device with id [%s] to entity [%s]: %s', - device.id, device.name, body.orionError); + device.id, + device.name, + body.orionError + ); callback(new errors.BadRequest(body.orionError.details)); } else { @@ -314,29 +356,41 @@ function createUnsubscribeHandlerNgsi1(device, id, callback) { * @return {Function} Returns a request handler for the given data. */ function createUnsubscribeHandlerNgsi2(device, id, callback) { - return function(error, response, body) { + return function (error, response, body) { if (error) { logger.debug( context, - 'Transport error found subscribing device with id [%s] to entity [%s]', device.id, device.name); + 'Transport error found subscribing device with id [%s] to entity [%s]', + device.id, + device.name + ); callback(error); - } else if (response.statusCode !== 204) { logger.debug( context, 'Unknown error subscribing device with id [%s] to entity [%s]: $s', - response.statusCode); - - callback(new errors.EntityGenericError(device.name, device.type, { - details: body - }, response.statusCode)); + response.statusCode + ); + callback( + new errors.EntityGenericError( + device.name, + device.type, + { + details: body + }, + response.statusCode + ) + ); } else if (body && body.orionError) { logger.debug( context, 'Orion found subscribing device with id [%s] to entity [%s]: %s', - device.id, device.name, body.orionError); + device.id, + device.name, + body.orionError + ); callback(new errors.BadRequest(body.orionError.details)); } else { @@ -353,7 +407,7 @@ function createUnsubscribeHandlerNgsi2(device, id, callback) { * @param {String} id ID of the subscription to remove. */ function unsubscribeNgsi1(device, id, callback) { - var options = { + const options = { method: 'POST', headers: { 'fiware-service': device.service, @@ -362,7 +416,6 @@ function unsubscribeNgsi1(device, id, callback) { json: { subscriptionId: id } - }; if (device.cbHost && device.cbHost.indexOf('://') !== -1) { @@ -382,7 +435,7 @@ function unsubscribeNgsi1(device, id, callback) { * @param {String} id ID of the subscription to remove. */ function unsubscribeNgsi2(device, id, callback) { - var options = { + const options = { method: 'DELETE', headers: { 'fiware-service': device.service, diff --git a/lib/services/northBound/contextServer.js b/lib/services/northBound/contextServer.js index d757bc89b..ebf65d16e 100644 --- a/lib/services/northBound/contextServer.js +++ b/lib/services/northBound/contextServer.js @@ -22,33 +22,37 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var async = require('async'), - apply = async.apply, - logger = require('logops'), - constants = require('../../constants'), - errors = require('../../errors'), - ngsi = require('../ngsi/ngsiService'), - intoTrans = require('../common/domain').intoTrans, - deviceService = require('../devices/deviceService'), - commands = require('../commands/commandService'), - middlewares = require('../common/genericMiddleware'), - _ = require('underscore'), - config = require('../../commonConfig'), - context = { - op: 'IoTAgentNGSI.ContextServer' - }, - updateContextTemplateNgsi1 = require('../../templates/updateContextNgsi1.json'), - updateContextTemplateNgsi2 = require('../../templates/updateContextNgsi2.json'), - queryContextTemplate = require('../../templates/queryContext.json'), - notificationTemplateNgsi1 = require('../../templates/notificationTemplateNgsi1.json'), - notificationTemplateNgsi2 = require('../../templates/notificationTemplateNgsi2.json'), - notificationMiddlewares = [], - updateHandler, - commandHandler, - queryHandler, - notificationHandler; + +/* eslint-disable no-useless-escape */ +/* eslint-disable no-unused-vars */ +/* eslint-disable no-prototype-builtins */ +/* eslint-disable consistent-return */ + +const async = require('async'); +const apply = async.apply; +const logger = require('logops'); +const constants = require('../../constants'); +const errors = require('../../errors'); +const ngsi = require('../ngsi/ngsiService'); +const intoTrans = require('../common/domain').intoTrans; +const deviceService = require('../devices/deviceService'); +const commands = require('../commands/commandService'); +const middlewares = require('../common/genericMiddleware'); +const _ = require('underscore'); +const config = require('../../commonConfig'); +const context = { + op: 'IoTAgentNGSI.ContextServer' +}; +const updateContextTemplateNgsi1 = require('../../templates/updateContextNgsi1.json'); +const updateContextTemplateNgsi2 = require('../../templates/updateContextNgsi2.json'); +const queryContextTemplate = require('../../templates/queryContext.json'); +const notificationTemplateNgsi1 = require('../../templates/notificationTemplateNgsi1.json'); +const notificationTemplateNgsi2 = require('../../templates/notificationTemplateNgsi2.json'); +let notificationMiddlewares = []; +let updateHandler; +let commandHandler; +let queryHandler; +let notificationHandler; /** * Create the response for an UpdateContext operation, based on the results of the individual updates. The signature @@ -60,12 +64,12 @@ var async = require('async'), * @return {{contextResponses: Array}} */ function createUpdateResponse(req, res, results) { - var result = { + const result = { contextResponses: [] }; - for (var i = 0; i < req.body.contextElements.length; i++) { - var contextResponse = { + for (let i = 0; i < req.body.contextElements.length; i++) { + const contextResponse = { contextElement: { attributes: req.body.contextElements[i].attributes, id: req.body.contextElements[i].id, @@ -78,7 +82,7 @@ function createUpdateResponse(req, res, results) { } }; - for (var j = 0; j < contextResponse.contextElement.attributes.length; j++) { + for (let j = 0; j < contextResponse.contextElement.attributes.length; j++) { contextResponse.contextElement.attributes[i].value = ''; } @@ -100,12 +104,12 @@ function createUpdateResponse(req, res, results) { * @return {{contextResponses: Array}} */ function createQueryResponse(req, res, results) { - var result = { + const result = { contextResponses: [] }; - for (var i = 0; i < results.length; i++) { - var contextResponse = { + for (let i = 0; i < results.length; i++) { + const contextResponse = { contextElement: results[i], statusCode: { code: 200, @@ -135,13 +139,13 @@ function createQueryResponse(req, res, results) { * @param {Array} attributes List of attributes to update with their types and values. */ function executeUpdateSideEffects(device, id, type, service, subservice, attributes, callback) { - var sideEffects = []; + const sideEffects = []; if (device.commands) { - for (var i = 0; i < device.commands.length; i++) { - for (var j = 0; j < attributes.length; j++) { + for (let i = 0; i < device.commands.length; i++) { + for (let j = 0; j < attributes.length; j++) { if (device.commands[i].name === attributes[j].name) { - var newAttributes = [ + const newAttributes = [ { name: device.commands[i].name + '_status', type: constants.COMMAND_STATUS, @@ -150,13 +154,7 @@ function executeUpdateSideEffects(device, id, type, service, subservice, attribu ]; sideEffects.push( - apply(ngsi.update, - device.name, - device.resource, - device.apikey, - newAttributes, - device - ) + apply(ngsi.update, device.name, device.resource, device.apikey, newAttributes, device) ); } } @@ -190,13 +188,13 @@ function pushCommandsToQueue(device, id, type, service, subservice, attributes, */ function generateUpdateActionsNgsi1(req, contextElement, callback) { function splitUpdates(device, callback) { - var attributes = [], - commands = [], - found; + let attributes = []; + const commands = []; + let found; if (device.commands) { - attributeLoop: for (var i in contextElement.attributes) { - for (var j in device.commands) { + attributeLoop: for (const i in contextElement.attributes) { + for (const j in device.commands) { if (contextElement.attributes[i].name === device.commands[j].name) { commands.push(contextElement.attributes[i]); found = true; @@ -206,7 +204,6 @@ function generateUpdateActionsNgsi1(req, contextElement, callback) { attributes.push(contextElement.attributes[i]); } - } else { attributes = contextElement.attributes; } @@ -215,7 +212,7 @@ function generateUpdateActionsNgsi1(req, contextElement, callback) { } function createActionsArray(attributes, commands, device, callback) { - var updateActions = []; + const updateActions = []; if (updateHandler) { updateActions.push( @@ -225,7 +222,8 @@ function generateUpdateActionsNgsi1(req, contextElement, callback) { contextElement.type, req.headers['fiware-service'], req.headers['fiware-servicepath'], - attributes) + attributes + ) ); } @@ -239,7 +237,8 @@ function generateUpdateActionsNgsi1(req, contextElement, callback) { contextElement.type, req.headers['fiware-service'], req.headers['fiware-servicepath'], - contextElement.attributes) + contextElement.attributes + ) ); } else { updateActions.push( @@ -249,7 +248,8 @@ function generateUpdateActionsNgsi1(req, contextElement, callback) { contextElement.type, req.headers['fiware-service'], req.headers['fiware-servicepath'], - commands) + commands + ) ); } } @@ -262,36 +262,38 @@ function generateUpdateActionsNgsi1(req, contextElement, callback) { contextElement.type, req.headers['fiware-service'], req.headers['fiware-servicepath'], - contextElement.attributes) + contextElement.attributes + ) ); callback(null, updateActions); } - deviceService.getDeviceByName(contextElement.id, req.headers['fiware-service'], req.headers['fiware-servicepath'], - function(error, deviceObj) { + deviceService.getDeviceByName( + contextElement.id, + req.headers['fiware-service'], + req.headers['fiware-servicepath'], + function (error, deviceObj) { if (error) { callback(error); } else { - async.waterfall([ - apply(deviceService.findConfigurationGroup, deviceObj), - apply(deviceService.mergeDeviceWithConfiguration, - [ - 'lazy', - 'internalAttributes', - 'active', - 'staticAttributes', - 'commands', - 'subscriptions' - ], - [null, null, [], [], [], [], []], - deviceObj - ), - splitUpdates, - createActionsArray - ], callback); + async.waterfall( + [ + apply(deviceService.findConfigurationGroup, deviceObj), + apply( + deviceService.mergeDeviceWithConfiguration, + ['lazy', 'internalAttributes', 'active', 'staticAttributes', 'commands', 'subscriptions'], + [null, null, [], [], [], [], []], + deviceObj + ), + splitUpdates, + createActionsArray + ], + callback + ); } - }); + } + ); } /** @@ -302,27 +304,26 @@ function generateUpdateActionsNgsi1(req, contextElement, callback) { * @param {Object} contextElement Context Element whose actions will be extracted. */ function generateUpdateActionsNgsi2(req, contextElement, callback) { - var entityId; - var entityType; + let entityId; + let entityType; if (contextElement.id && contextElement.type) { entityId = contextElement.id; entityType = contextElement.type; - }else if (req.params.entity) { + } else if (req.params.entity) { entityId = req.params.entity; } function splitUpdates(device, callback) { - var attributes = [], - commands = [], - found, - newAtt, - i; + const attributes = []; + const commands = []; + let found; + let newAtt; + let i; if (device.commands) { attributeLoop: for (i in contextElement) { - for (var j in device.commands) { - + for (const j in device.commands) { if (i === device.commands[j].name) { newAtt = {}; newAtt[i] = contextElement[i]; @@ -333,7 +334,6 @@ function generateUpdateActionsNgsi2(req, contextElement, callback) { } } } - } for (i in contextElement) { @@ -349,9 +349,9 @@ function generateUpdateActionsNgsi2(req, contextElement, callback) { } function createActionsArray(attributes, commands, device, callback) { - var updateActions = []; + const updateActions = []; - if(!entityType) { + if (!entityType) { entityType = device.type; } @@ -363,7 +363,8 @@ function generateUpdateActionsNgsi2(req, contextElement, callback) { entityType, req.headers['fiware-service'], req.headers['fiware-servicepath'], - attributes) + attributes + ) ); } @@ -377,7 +378,8 @@ function generateUpdateActionsNgsi2(req, contextElement, callback) { entityType, req.headers['fiware-service'], req.headers['fiware-servicepath'], - attributes) + attributes + ) ); } else { updateActions.push( @@ -387,7 +389,8 @@ function generateUpdateActionsNgsi2(req, contextElement, callback) { entityType, req.headers['fiware-service'], req.headers['fiware-servicepath'], - commands) + commands + ) ); } } @@ -400,36 +403,36 @@ function generateUpdateActionsNgsi2(req, contextElement, callback) { entityType, req.headers['fiware-service'], req.headers['fiware-servicepath'], - attributes) + attributes + ) ); callback(null, updateActions); } - deviceService.getDeviceByName(entityId, req.headers['fiware-service'], req.headers['fiware-servicepath'], - function(error, deviceObj) { - if (error) { - callback(error); - } else { - async.waterfall([ + deviceService.getDeviceByName(entityId, req.headers['fiware-service'], req.headers['fiware-servicepath'], function ( + error, + deviceObj + ) { + if (error) { + callback(error); + } else { + async.waterfall( + [ apply(deviceService.findConfigurationGroup, deviceObj), - apply(deviceService.mergeDeviceWithConfiguration, - [ - 'lazy', - 'internalAttributes', - 'active', - 'staticAttributes', - 'commands', - 'subscriptions' - ], + apply( + deviceService.mergeDeviceWithConfiguration, + ['lazy', 'internalAttributes', 'active', 'staticAttributes', 'commands', 'subscriptions'], [null, null, [], [], [], [], []], deviceObj ), splitUpdates, createActionsArray - ], callback); - } - }); + ], + callback + ); + } + }); } /** @@ -444,24 +447,23 @@ function handleUpdateNgsi2(req, res, next) { logger.debug(context, 'Handling update from [%s]', req.get('host')); logger.debug(context, req.body); - async.waterfall([ - apply(async.map, req.body.entities, apply(generateUpdateActionsNgsi2, req)), - reduceActions, - async.series - ], function(error, result) { - if (error) { - logger.debug(context, 'There was an error handling the update action: %s.', error); + async.waterfall( + [apply(async.map, req.body.entities, apply(generateUpdateActionsNgsi2, req)), reduceActions, async.series], + function (error, result) { + if (error) { + logger.debug(context, 'There was an error handling the update action: %s.', error); - next(error); - } else { - logger.debug(context, 'Update action from [%s] handled successfully.', req.get('host')); - res.status(204).json(); + next(error); + } else { + logger.debug(context, 'Update action from [%s] handled successfully.', req.get('host')); + res.status(204).json(); + } } - }); + ); } else { logger.error(context, 'Tried to handle an update request before the update handler was stablished.'); - var errorNotFound = new Error({ + const errorNotFound = new Error({ message: 'Update handler not found' }); next(errorNotFound); @@ -474,7 +476,6 @@ function handleUpdateNgsi2(req, res, next) { * to the user update handler function is made. */ function handleUpdateNgsi1(req, res, next) { - function reduceActions(actions, callback) { callback(null, _.flatten(actions)); } @@ -483,24 +484,27 @@ function handleUpdateNgsi1(req, res, next) { logger.debug(context, 'Handling update from [%s]', req.get('host')); logger.debug(context, req.body); - async.waterfall([ - apply(async.map, req.body.contextElements, apply(generateUpdateActionsNgsi1, req)), - reduceActions, - async.series - ], function(error, result) { - if (error) { - logger.debug(context, 'There was an error handling the update action: %s.', error); + async.waterfall( + [ + apply(async.map, req.body.contextElements, apply(generateUpdateActionsNgsi1, req)), + reduceActions, + async.series + ], + function (error, result) { + if (error) { + logger.debug(context, 'There was an error handling the update action: %s.', error); - next(error); - } else { - logger.debug(context, 'Update action from [%s] handled successfully.', req.get('host')); - res.status(200).json(createUpdateResponse(req, res, result)); + next(error); + } else { + logger.debug(context, 'Update action from [%s] handled successfully.', req.get('host')); + res.status(200).json(createUpdateResponse(req, res, result)); + } } - }); + ); } else { logger.error(context, 'Tried to handle an update request before the update handler was stablished.'); - var errorNotFound = new Error({ + const errorNotFound = new Error({ message: 'Update handler not found' }); next(errorNotFound); @@ -518,21 +522,21 @@ function handleUpdateNgsi1(req, res, next) { * @param {Array} attributes List of attributes to read. */ function defaultQueryHandlerNgsi1(id, type, service, subservice, attributes, callback) { - var contextElement = { - type: type, + const contextElement = { + type, isPattern: false, - id: id, + id, attributes: [] }; - deviceService.getDeviceByName(id, service, subservice, function(error, ngsiDevice) { + deviceService.getDeviceByName(id, service, subservice, function (error, ngsiDevice) { if (error) { callback(error); } else { - for (var i = 0; i < attributes.length; i++) { - var lazyAttribute = _.findWhere(ngsiDevice.lazy, { name: attributes[i] }), - command = _.findWhere(ngsiDevice.commands, { name: attributes[i] }), - attributeType; + for (let i = 0; i < attributes.length; i++) { + const lazyAttribute = _.findWhere(ngsiDevice.lazy, { name: attributes[i] }); + const command = _.findWhere(ngsiDevice.commands, { name: attributes[i] }); + let attributeType; if (command) { attributeType = command.type; @@ -565,19 +569,19 @@ function defaultQueryHandlerNgsi1(id, type, service, subservice, attributes, cal * @param {Array} attributes List of attributes to read. */ function defaultQueryHandlerNgsi2(id, type, service, subservice, attributes, callback) { - var contextElement = { - type: type, - id: id + const contextElement = { + type, + id }; - deviceService.getDeviceByName(id, service, subservice, function(error, ngsiDevice) { + deviceService.getDeviceByName(id, service, subservice, function (error, ngsiDevice) { if (error) { callback(error); } else { - for (var i = 0; i < attributes.length; i++) { - var lazyAttribute = _.findWhere(ngsiDevice.lazy, { name: attributes[i] }), - command = _.findWhere(ngsiDevice.commands, { name: attributes[i] }), - attributeType; + for (let i = 0; i < attributes.length; i++) { + const lazyAttribute = _.findWhere(ngsiDevice.lazy, { name: attributes[i] }); + const command = _.findWhere(ngsiDevice.commands, { name: attributes[i] }); + let attributeType; if (command) { attributeType = command.type; @@ -609,13 +613,12 @@ function handleQueryNgsi1(req, res, next) { } function addStaticAttributes(attributes, device, contextElement, callback) { - function inAttributes(item) { return item.name && attributes.indexOf(item.name) >= 0; } if (device.staticAttributes) { - var selectedAttributes = device.staticAttributes.filter(inAttributes); + const selectedAttributes = device.staticAttributes.filter(inAttributes); if (selectedAttributes.length > 0) { if (contextElement.attributes) { @@ -637,13 +640,14 @@ function handleQueryNgsi1(req, res, next) { logger.debug(context, 'Handling stored set of attributes: %j', attributes); callback(null, device.lazy.map(getName)); } else { - logger.debug(context, 'Couldn\'t find any attributes. Handling with null reference'); + logger.debug(context, "Couldn't find any attributes. Handling with null reference"); + callback(null, null); } } function createQueryRequests(attributes, contextEntity, callback) { - var actualHandler; + let actualHandler; if (queryHandler) { actualHandler = queryHandler; @@ -651,39 +655,33 @@ function handleQueryNgsi1(req, res, next) { actualHandler = defaultQueryHandlerNgsi1; } - async.waterfall([ - apply( - deviceService.getDeviceByName, - contextEntity.id, - req.headers['fiware-service'], - req.headers['fiware-servicepath']), - deviceService.findConfigurationGroup - ], function handleFindDevice(error, device) { - var executeCompleteAttributes = apply( - completeAttributes, - attributes, - device + async.waterfall( + [ + apply( + deviceService.getDeviceByName, + contextEntity.id, + req.headers['fiware-service'], + req.headers['fiware-servicepath'] ), - executeQueryHandler = apply( + deviceService.findConfigurationGroup + ], + function handleFindDevice(error, device) { + const executeCompleteAttributes = apply(completeAttributes, attributes, device); + const executeQueryHandler = apply( actualHandler, contextEntity.id, contextEntity.type, req.headers['fiware-service'], req.headers['fiware-servicepath'] - ), - executeAddStaticAttributes = apply( - addStaticAttributes, - attributes, - device ); + const executeAddStaticAttributes = apply(addStaticAttributes, attributes, device); - callback(error, apply(async.waterfall, [ - executeCompleteAttributes, - executeQueryHandler, - executeAddStaticAttributes - ])); - }); - + callback( + error, + apply(async.waterfall, [executeCompleteAttributes, executeQueryHandler, executeAddStaticAttributes]) + ); + } + ); } function handleQueryContextRequests(error, result) { @@ -698,10 +696,10 @@ function handleQueryNgsi1(req, res, next) { logger.debug(context, 'Handling query from [%s]', req.get('host')); - async.waterfall([ - apply(async.map, req.body.entities, apply(createQueryRequests, req.body.attributes)), - async.series - ], handleQueryContextRequests); + async.waterfall( + [apply(async.map, req.body.entities, apply(createQueryRequests, req.body.attributes)), async.series], + handleQueryContextRequests + ); } /** @@ -713,25 +711,22 @@ function handleQueryNgsi2(req, res, next) { } function addStaticAttributes(attributes, device, contextElement, callback) { - function inAttributes(item) { return item.name && attributes.indexOf(item.name) >= 0; } if (device.staticAttributes) { - - var selectedAttributes = []; + let selectedAttributes = []; if (attributes === undefined || attributes.length === 0) { selectedAttributes = device.staticAttributes; - } - else { + } else { selectedAttributes = device.staticAttributes.filter(inAttributes); } - for (var att in selectedAttributes) { + for (const att in selectedAttributes) { contextElement[selectedAttributes[att].name] = { - 'type' : selectedAttributes[att].type, - 'value' : selectedAttributes[att].value + type: selectedAttributes[att].type, + value: selectedAttributes[att].value }; } } @@ -745,55 +740,44 @@ function handleQueryNgsi2(req, res, next) { callback(null, attributes); } else if (device.lazy) { logger.debug(context, 'Handling stored set of attributes: %j', attributes); - var results = device.lazy.map(getName); + const results = device.lazy.map(getName); callback(null, results); } else { - logger.debug(context, 'Couldn\'t find any attributes. Handling with null reference'); + logger.debug(context, "Couldn't find any attributes. Handling with null reference"); + callback(null, null); } } function finishQueryForDevice(attributes, contextEntity, actualHandler, device, callback) { - var contextId = contextEntity.id; - var contextType = contextEntity.type; - if(!contextId) { + let contextId = contextEntity.id; + let contextType = contextEntity.type; + if (!contextId) { contextId = device.id; } - if(!contextType) { + if (!contextType) { contextType = device.type; } - deviceService.findConfigurationGroup(device, function(error, group) { - var executeCompleteAttributes = apply( - completeAttributes, - attributes, - group - ), - executeQueryHandler = apply( - actualHandler, - contextId, - contextType, - req.headers['fiware-service'], - req.headers['fiware-servicepath'] - ), - executeAddStaticAttributes = apply( - addStaticAttributes, - attributes, - group - ); + deviceService.findConfigurationGroup(device, function (error, group) { + const executeCompleteAttributes = apply(completeAttributes, attributes, group); + const executeQueryHandler = apply( + actualHandler, + contextId, + contextType, + req.headers['fiware-service'], + req.headers['fiware-servicepath'] + ); + const executeAddStaticAttributes = apply(addStaticAttributes, attributes, group); - async.waterfall([ - executeCompleteAttributes, - executeQueryHandler, - executeAddStaticAttributes - ], callback); - }); + async.waterfall([executeCompleteAttributes, executeQueryHandler, executeAddStaticAttributes], callback); + }); } function createQueryRequest(attributes, contextEntity, callback) { - var actualHandler; - var getFunction; + let actualHandler; + let getFunction; if (queryHandler) { actualHandler = queryHandler; @@ -806,7 +790,8 @@ function handleQueryNgsi2(req, res, next) { deviceService.getDeviceByName, contextEntity.id, req.headers['fiware-service'], - req.headers['fiware-servicepath']); + req.headers['fiware-servicepath'] + ); } else { getFunction = apply( deviceService.listDevicesWithType, @@ -814,7 +799,8 @@ function handleQueryNgsi2(req, res, next) { req.headers['fiware-service'], req.headers['fiware-servicepath'], null, - null); + null + ); } getFunction(function handleFindDevice(error, innerDevice) { @@ -823,31 +809,31 @@ function handleQueryNgsi2(req, res, next) { return callback(new errors.DeviceNotFound(contextEntity.id)); } - if(innerDevice.count) { + if (innerDevice.count) { if (innerDevice.count === 0) { return callback(null, []); - } else { - deviceList = innerDevice.devices; } + deviceList = innerDevice.devices; } else { deviceList = [innerDevice]; } - async.map(deviceList, async.apply( - finishQueryForDevice, attributes, contextEntity, actualHandler), function (error, results) { - if (error) { - callback(error); - } - else if(innerDevice.count) { - callback(null,results); - } else if(Array.isArray(results) && results.length > 0){ - callback(null, results); - } else { - callback(null, results); + async.map( + deviceList, + async.apply(finishQueryForDevice, attributes, contextEntity, actualHandler), + function (error, results) { + if (error) { + callback(error); + } else if (innerDevice.count) { + callback(null, results); + } else if (Array.isArray(results) && results.length > 0) { + callback(null, results); + } else { + callback(null, results); + } } - }); + ); }); - } function handleQueryContextRequests(error, result) { @@ -861,33 +847,31 @@ function handleQueryNgsi2(req, res, next) { } logger.debug(context, 'Handling query from [%s]', req.get('host')); - var contextEntity = {}; + const contextEntity = {}; // At the present moment, IOTA supports query request with one entity and without patterns. This is aligned // with the utilization cases in combination with ContextBroker. Other cases are returned as error - if (req.body.entities.length !== 1) - { - logger.warn('queries with entities number different to 1 are not supported (%d found)', - req.body.entities.length); - handleQueryContextRequests({code: 400, name: 'BadRequest', message: 'more than one entity in query'}); + if (req.body.entities.length !== 1) { + logger.warn( + 'queries with entities number different to 1 are not supported (%d found)', + req.body.entities.length + ); + handleQueryContextRequests({ code: 400, name: 'BadRequest', message: 'more than one entity in query' }); return; } - if (req.body.entities[0].idPattern) - { + if (req.body.entities[0].idPattern) { logger.warn('queries with idPattern are not supported'); - handleQueryContextRequests({code: 400, name: 'BadRequest', message: 'idPattern usage in query'}); + handleQueryContextRequests({ code: 400, name: 'BadRequest', message: 'idPattern usage in query' }); return; } contextEntity.id = req.body.entities[0].id; contextEntity.type = req.body.entities[0].type; - var queryAtts = req.body.attrs; + const queryAtts = req.body.attrs; createQueryRequest(queryAtts, contextEntity, handleQueryContextRequests); - } function handleNotificationNgsi1(req, res, next) { - function checkStatus(statusCode, callback) { if (statusCode.code && statusCode.code === '200') { callback(); @@ -901,21 +885,22 @@ function handleNotificationNgsi1(req, res, next) { contextResponse.contextElement.id, req.headers['fiware-service'], req.headers['fiware-servicepath'], - function(error, device) { + function (error, device) { if (error) { callback(error); } else { callback(null, device, contextResponse.contextElement.attributes); } - }); + } + ); } function applyNotificationMiddlewares(device, values, callback) { if (notificationMiddlewares.length > 0) { - var firstMiddleware = notificationMiddlewares.slice(0, 1)[0], - rest = notificationMiddlewares.slice(1), - startMiddleware = apply(firstMiddleware, device, values), - composedMiddlewares = [startMiddleware].concat(rest); + const firstMiddleware = notificationMiddlewares.slice(0, 1)[0]; + const rest = notificationMiddlewares.slice(1); + const startMiddleware = apply(firstMiddleware, device, values); + const composedMiddlewares = [startMiddleware].concat(rest); async.waterfall(composedMiddlewares, callback); } else { @@ -924,12 +909,15 @@ function handleNotificationNgsi1(req, res, next) { } function createNotificationHandler(contextResponse, callback) { - async.waterfall([ - apply(checkStatus, contextResponse.statusCode), - apply(extractInformation, contextResponse), - applyNotificationMiddlewares, - notificationHandler - ], callback); + async.waterfall( + [ + apply(checkStatus, contextResponse.statusCode), + apply(extractInformation, contextResponse), + applyNotificationMiddlewares, + notificationHandler + ], + callback + ); } function handleNotificationRequests(error) { @@ -945,9 +933,8 @@ function handleNotificationNgsi1(req, res, next) { logger.debug(context, 'Handling notification from [%s]', req.get('host')); async.map(req.body.contextResponses, createNotificationHandler, handleNotificationRequests); - } else { - var errorNotFound = new Error({ + const errorNotFound = new Error({ message: 'Notification handler not found' }); @@ -959,11 +946,11 @@ function handleNotificationNgsi1(req, res, next) { function handleNotificationNgsi2(req, res, next) { function extractInformation(dataElement, callback) { - var atts = []; - for (var key in dataElement) { + const atts = []; + for (const key in dataElement) { if (dataElement.hasOwnProperty(key)) { if (key !== 'id' && key !== 'type') { - var att = {}; + const att = {}; att.type = dataElement[key].type; att.value = dataElement[key].value; att.name = key; @@ -975,21 +962,22 @@ function handleNotificationNgsi2(req, res, next) { dataElement.id, req.headers['fiware-service'], req.headers['fiware-servicepath'], - function(error, device) { + function (error, device) { if (error) { callback(error); } else { callback(null, device, atts); } - }); + } + ); } function applyNotificationMiddlewares(device, values, callback) { if (notificationMiddlewares.length > 0) { - var firstMiddleware = notificationMiddlewares.slice(0, 1)[0], - rest = notificationMiddlewares.slice(1), - startMiddleware = apply(firstMiddleware, device, values), - composedMiddlewares = [startMiddleware].concat(rest); + const firstMiddleware = notificationMiddlewares.slice(0, 1)[0]; + const rest = notificationMiddlewares.slice(1); + const startMiddleware = apply(firstMiddleware, device, values); + const composedMiddlewares = [startMiddleware].concat(rest); async.waterfall(composedMiddlewares, callback); } else { @@ -998,11 +986,10 @@ function handleNotificationNgsi2(req, res, next) { } function createNotificationHandler(contextResponse, callback) { - async.waterfall([ - apply(extractInformation, contextResponse), - applyNotificationMiddlewares, - notificationHandler - ], callback); + async.waterfall( + [apply(extractInformation, contextResponse), applyNotificationMiddlewares, notificationHandler], + callback + ); } function handleNotificationRequests(error) { @@ -1017,9 +1004,8 @@ function handleNotificationNgsi2(req, res, next) { if (notificationHandler) { logger.debug(context, 'Handling notification from [%s]', req.get('host')); async.map(req.body.data, createNotificationHandler, handleNotificationRequests); - } else { - var errorNotFound = new Error({ + const errorNotFound = new Error({ message: 'Notification handler not found' }); @@ -1027,7 +1013,6 @@ function handleNotificationNgsi2(req, res, next) { next(errorNotFound); } - } /** @@ -1087,7 +1072,7 @@ function setNotificationHandler(newHandler) { } function queryErrorHandlingNgsi1(error, req, res, next) { - var code = 500; + let code = 500; logger.debug(context, 'Query NGSIv1 error [%s] handling request: %s', error.name, error.message); @@ -1097,7 +1082,7 @@ function queryErrorHandlingNgsi1(error, req, res, next) { res.status(code).json({ errorCode: { - code: code, + code, reasonPhrase: error.name, details: error.message.replace(/[<>\"\'=;\(\)]/g, '') } @@ -1105,7 +1090,7 @@ function queryErrorHandlingNgsi1(error, req, res, next) { } function queryErrorHandlingNgsi2(error, req, res, next) { - var code = 500; + let code = 500; logger.debug(context, 'Query NGSIv2 error [%s] handling request: %s', error.name, error.message); @@ -1120,7 +1105,7 @@ function queryErrorHandlingNgsi2(error, req, res, next) { } function updateErrorHandlingNgsi1(error, req, res, next) { - var code = 500; + let code = 500; logger.debug(context, 'Update NGSIv1 error [%s] handing request: %s', error.name, error.message); @@ -1128,24 +1113,22 @@ function updateErrorHandlingNgsi1(error, req, res, next) { code = error.code; } - res.status(code).json( - { - contextResponses: [ - { - contextElement: req.body, - statusCode: { - code: code, - reasonPhrase: error.name, - details: error.message.replace(/[<>\"\'=;\(\)]/g, '') - } + res.status(code).json({ + contextResponses: [ + { + contextElement: req.body, + statusCode: { + code, + reasonPhrase: error.name, + details: error.message.replace(/[<>\"\'=;\(\)]/g, '') } - ] - } - ); + } + ] + }); } function updateErrorHandlingNgsi2(error, req, res, next) { - var code = 500; + let code = 500; logger.debug(context, 'Update NGSIv2 error [%s] handing request: %s', error.name, error.message); @@ -1166,51 +1149,34 @@ function updateErrorHandlingNgsi2(error, req, res, next) { */ function loadContextRoutes(router) { //TODO: remove '//' paths when the appropriate patch comes to Orion - var updateMiddlewaresNgsi1 = [ - middlewares.ensureType, - middlewares.validateJson(updateContextTemplateNgsi1), - handleUpdateNgsi1, - updateErrorHandlingNgsi1 - ], - updateMiddlewaresNgsi2 = [ - middlewares.ensureType, - middlewares.validateJson(updateContextTemplateNgsi2), - handleUpdateNgsi2, - updateErrorHandlingNgsi2 - ], - queryMiddlewaresNgsi1 = [ - middlewares.ensureType, - middlewares.validateJson(queryContextTemplate), - handleQueryNgsi1, - queryErrorHandlingNgsi1 - ], - queryMiddlewaresNgsi2 = [ - handleQueryNgsi2, - queryErrorHandlingNgsi2 - ], - updatePathsNgsi1 = [ - '/v1/updateContext', - '/NGSI10/updateContext', - '//updateContext' - ], - updatePathsNgsi2 = [ - '/v2/op/update', - '//op/update' - ], - queryPathsNgsi1 = [ - '/v1/queryContext', - '/NGSI10/queryContext', - '//queryContext' - ], - queryPathsNgsi2 = [ - '/v2/op/query', - '//op/query' - ]; - // In a more evolved implementation, more endpoints could be added to queryPathsNgsi2 - // according to http://fiware.github.io/specifications/ngsiv2/stable. + const updateMiddlewaresNgsi1 = [ + middlewares.ensureType, + middlewares.validateJson(updateContextTemplateNgsi1), + handleUpdateNgsi1, + updateErrorHandlingNgsi1 + ]; + const updateMiddlewaresNgsi2 = [ + middlewares.ensureType, + middlewares.validateJson(updateContextTemplateNgsi2), + handleUpdateNgsi2, + updateErrorHandlingNgsi2 + ]; + const queryMiddlewaresNgsi1 = [ + middlewares.ensureType, + middlewares.validateJson(queryContextTemplate), + handleQueryNgsi1, + queryErrorHandlingNgsi1 + ]; + const queryMiddlewaresNgsi2 = [handleQueryNgsi2, queryErrorHandlingNgsi2]; + const updatePathsNgsi1 = ['/v1/updateContext', '/NGSI10/updateContext', '//updateContext']; + const updatePathsNgsi2 = ['/v2/op/update', '//op/update']; + const queryPathsNgsi1 = ['/v1/queryContext', '/NGSI10/queryContext', '//queryContext']; + const queryPathsNgsi2 = ['/v2/op/query', '//op/query']; + // In a more evolved implementation, more endpoints could be added to queryPathsNgsi2 + // according to http://fiware.github.io/specifications/ngsiv2/stable. logger.info(context, 'Loading NGSI Contect server routes'); - var i; + let i; if (config.checkNgsi2()) { for (i = 0; i < updatePathsNgsi2.length; i++) { router.post(updatePathsNgsi2[i], updateMiddlewaresNgsi2); diff --git a/lib/services/northBound/deviceGroupAdministrationServer.js b/lib/services/northBound/deviceGroupAdministrationServer.js index 85801399e..40829394f 100644 --- a/lib/services/northBound/deviceGroupAdministrationServer.js +++ b/lib/services/northBound/deviceGroupAdministrationServer.js @@ -22,40 +22,36 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var restUtils = require('./restUtils'), - groupService = require('./../groups/groupService'), - async = require('async'), - apply = async.apply, - templateGroup = require('../../templates/deviceGroup.json'), - configurationHandler, - removeConfigurationHandler, - configurationMiddleware = [], - _ = require('underscore'), - mandatoryHeaders = [ - 'fiware-service', - 'fiware-servicepath' - ], - mandatoryParameters = [ - 'resource', - 'apikey' - ], - apiToInternal = { - 'entity_type': 'type', - 'internal_attributes': 'internalAttributes', - 'static_attributes': 'staticAttributes' - }, - internalToApi = { - 'type': 'entity_type', - 'internalAttributes': 'internal_attributes', - 'staticAttributes': 'static_attributes' - }; + +/* eslint-disable no-prototype-builtins */ + +const restUtils = require('./restUtils'); +const groupService = require('./../groups/groupService'); +const async = require('async'); +const apply = async.apply; +const templateGroup = require('../../templates/deviceGroup.json'); +let configurationHandler; +let removeConfigurationHandler; +let configurationMiddleware = []; +const _ = require('underscore'); +const mandatoryHeaders = ['fiware-service', 'fiware-servicepath']; +const mandatoryParameters = ['resource', 'apikey']; + +const apiToInternal = { + entity_type: 'type', + internal_attributes: 'internalAttributes', + static_attributes: 'staticAttributes' +}; +const internalToApi = { + type: 'entity_type', + internalAttributes: 'internal_attributes', + staticAttributes: 'static_attributes' +}; function applyMap(translation, body) { - var newBody = _.clone(body); + const newBody = _.clone(body); - for (var i in newBody) { + for (const i in newBody) { if (newBody.hasOwnProperty(i) && translation[i]) { newBody[translation[i]] = newBody[i]; delete newBody[i]; @@ -82,7 +78,6 @@ function applyConfigurationHandler(newConfiguration, callback) { } } - /** * Apply the handler for configuration removal. * @@ -93,7 +88,7 @@ function applyRemoveConfigurationHandler(groupToDelete, callback) { removeConfigurationHandler(groupToDelete, callback); } else { callback(); - } + } } /** @@ -103,9 +98,9 @@ function applyRemoveConfigurationHandler(groupToDelete, callback) { */ function applyConfigurationMiddlewares(newConfiguration, callback) { if (configurationMiddleware.length > 0) { - var firstMiddleware = configurationMiddleware.slice(0, 1)[0], - rest = configurationMiddleware.slice(1), - executingMiddlewares = [apply(firstMiddleware, newConfiguration)]; + const firstMiddleware = configurationMiddleware.slice(0, 1)[0]; + const rest = configurationMiddleware.slice(1); + let executingMiddlewares = [apply(firstMiddleware, newConfiguration)]; executingMiddlewares = executingMiddlewares.concat(rest); @@ -115,7 +110,6 @@ function applyConfigurationMiddlewares(newConfiguration, callback) { } } - /** * Handle the device group creation requests, adding the header information to the device group body. * @@ -124,25 +118,26 @@ function applyConfigurationMiddlewares(newConfiguration, callback) { * @param {Function} next Invokes the next middleware in the chain. */ function handleCreateDeviceGroup(req, res, next) { - /*jshint sub:true */ - - for (var i = 0; i < req.body.services.length; i++) { + for (let i = 0; i < req.body.services.length; i++) { req.body.services[i] = applyMap(apiToInternal, req.body.services[i]); req.body.services[i].service = req.headers['fiware-service']; req.body.services[i].subservice = req.headers['fiware-servicepath']; } - async.series([ - apply(groupService.create, req.body), - apply(applyConfigurationMiddlewares, req.body), - apply(applyConfigurationHandler, req.body) - ], function(error) { - if (error) { - next(error); - } else { - res.status(201).send({}); + async.series( + [ + apply(groupService.create, req.body), + apply(applyConfigurationMiddlewares, req.body), + apply(applyConfigurationHandler, req.body) + ], + function (error) { + if (error) { + next(error); + } else { + res.status(201).send({}); + } } - }); + ); } /** @@ -155,11 +150,11 @@ function handleCreateDeviceGroup(req, res, next) { * @param {Function} next Invokes the next middleware in the chain. */ function handleListDeviceGroups(req, res, next) { - var listHandler = function(error, group) { + const listHandler = function (error, group) { if (error) { next(error); } else { - var translatedGroup = _.clone(group); + let translatedGroup = _.clone(group); if (group.services) { translatedGroup.services = group.services.map(applyMap.bind(null, internalToApi)); @@ -172,11 +167,7 @@ function handleListDeviceGroups(req, res, next) { }; if (req.headers['fiware-servicepath'] === '/*') { - groupService.list( - req.headers['fiware-service'], - req.query.limit, - req.query.offset, - listHandler); + groupService.list(req.headers['fiware-service'], req.query.limit, req.query.offset, listHandler); } else { groupService.find(req.headers['fiware-service'], req.headers['fiware-servicepath'], null, listHandler); } @@ -190,7 +181,6 @@ function handleListDeviceGroups(req, res, next) { * @param {Function} next Invokes the next middleware in the chain. */ function handleModifyDeviceGroups(req, res, next) { - /*jshint sub:true */ req.body = applyMap(apiToInternal, req.body); function addInformation(group, callback) { @@ -201,18 +191,27 @@ function handleModifyDeviceGroups(req, res, next) { callback(null, group); } - async.series([ - apply(groupService.update, req.headers['fiware-service'], req.headers['fiware-servicepath'], - req.query.resource, req.query.apikey, req.body), - apply(addInformation, req.body), - apply(applyConfigurationHandler, req.body) - ], function(error) { - if (error) { - next(error); - } else { - res.status(204).send({}); + async.series( + [ + apply( + groupService.update, + req.headers['fiware-service'], + req.headers['fiware-servicepath'], + req.query.resource, + req.query.apikey, + req.body + ), + apply(addInformation, req.body), + apply(applyConfigurationHandler, req.body) + ], + function (error) { + if (error) { + next(error); + } else { + res.status(204).send({}); + } } - }); + ); } /** @@ -224,38 +223,39 @@ function handleModifyDeviceGroups(req, res, next) { */ function handleDeleteDeviceGroups(req, res, next) { - - function getGroup (req, callback) { - groupService.get(req.query.resource, req.query.apikey, function (error, group){ + function getGroup(req, callback) { + groupService.get(req.query.resource, req.query.apikey, function (error, group) { if (error) { callback(error); - } else{ + } else { callback(null, group); - } + } }); } - function deleteGroup (req, groupToDelete, callback) { - groupService.remove(req.headers['fiware-service'], req.headers['fiware-servicepath'], - req.query.resource, req.query.apikey, req.query.device, function (error){ - if (error) { - callback(error); - } else{ - callback(null, groupToDelete); + function deleteGroup(req, groupToDelete, callback) { + groupService.remove( + req.headers['fiware-service'], + req.headers['fiware-servicepath'], + req.query.resource, + req.query.apikey, + req.query.device, + function (error) { + if (error) { + callback(error); + } else { + callback(null, groupToDelete); + } } - }); + ); } - async.waterfall([ - apply(getGroup, req), - apply(deleteGroup, req), - applyRemoveConfigurationHandler], - function(error) { - if (error) { - next(error); - } else { - res.status(204).send({}); - } - }); + async.waterfall([apply(getGroup, req), apply(deleteGroup, req), applyRemoveConfigurationHandler], function (error) { + if (error) { + next(error); + } else { + res.status(204).send({}); + } + }); } /** @@ -264,24 +264,28 @@ function handleDeleteDeviceGroups(req, res, next) { * @param {Object} router Express request router object. */ function loadContextRoutes(router) { - router.post('/iot/services', + router.post( + '/iot/services', restUtils.checkRequestAttributes('headers', mandatoryHeaders), restUtils.checkBody(templateGroup), - handleCreateDeviceGroup); + handleCreateDeviceGroup + ); - router.get('/iot/services', - restUtils.checkRequestAttributes('headers', mandatoryHeaders), - handleListDeviceGroups); + router.get('/iot/services', restUtils.checkRequestAttributes('headers', mandatoryHeaders), handleListDeviceGroups); - router.put('/iot/services', + router.put( + '/iot/services', restUtils.checkRequestAttributes('headers', mandatoryHeaders), restUtils.checkRequestAttributes('query', mandatoryParameters), - handleModifyDeviceGroups); + handleModifyDeviceGroups + ); - router.delete('/iot/services', + router.delete( + '/iot/services', restUtils.checkRequestAttributes('headers', mandatoryHeaders), restUtils.checkRequestAttributes('query', mandatoryParameters), - handleDeleteDeviceGroups); + handleDeleteDeviceGroups + ); } function setConfigurationHandler(newHandler) { diff --git a/lib/services/northBound/deviceProvisioningServer.js b/lib/services/northBound/deviceProvisioningServer.js index 85f648f56..7b9248edb 100644 --- a/lib/services/northBound/deviceProvisioningServer.js +++ b/lib/services/northBound/deviceProvisioningServer.js @@ -20,57 +20,53 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; - -var async = require('async'), - restUtils = require('./restUtils'), - statsRegistry = require('./../stats/statsRegistry'), - deviceService = require('./../devices/deviceService'), - intoTrans = require('../common/domain').intoTrans, - logger = require('logops'), - errors = require('../../errors'), - _ = require('underscore'), - context = { - op: 'IoTAgentNGSI.DeviceProvisioning' - }, - apply = async.apply, - provisioningHandler, - removeDeviceHandler, - updateDeviceTemplate, - createDeviceTemplate, - mandatoryHeaders = [ - 'fiware-service', - 'fiware-servicepath' - ], - provisioningMiddlewares = [], - provisioningAPITranslation = { - /* jshint camelcase:false */ - - name: 'id', - service: 'service', - service_path: 'subservice', - entity_name: 'name', - entity_type: 'type', - timezone: 'timezone', - timestamp: 'timestamp', - protocol: 'protocol', - transport: 'transport', - endpoint: 'endpoint', - attributes: 'active', - commands: 'commands', - lazy: 'lazy', - internal_attributes: 'internalAttributes', - static_attributes: 'staticAttributes', - autoprovision: 'autoprovision', - explicitAttrs: 'explicitAttrs', - expressionLanguage: 'expressionLanguage' - }; + +const async = require('async'); +const restUtils = require('./restUtils'); +const statsRegistry = require('./../stats/statsRegistry'); +const deviceService = require('./../devices/deviceService'); +const intoTrans = require('../common/domain').intoTrans; +const logger = require('logops'); +const errors = require('../../errors'); +const _ = require('underscore'); +const context = { + op: 'IoTAgentNGSI.DeviceProvisioning' +}; +const apply = async.apply; +let provisioningHandler; +let removeDeviceHandler; +let updateDeviceTemplate; +let createDeviceTemplate; +const mandatoryHeaders = ['fiware-service', 'fiware-servicepath']; +let provisioningMiddlewares = []; +const provisioningAPITranslation = { + /* jshint camelcase:false */ + + name: 'id', + service: 'service', + service_path: 'subservice', + entity_name: 'name', + entity_type: 'type', + timezone: 'timezone', + timestamp: 'timestamp', + protocol: 'protocol', + transport: 'transport', + endpoint: 'endpoint', + attributes: 'active', + commands: 'commands', + lazy: 'lazy', + internal_attributes: 'internalAttributes', + static_attributes: 'staticAttributes', + autoprovision: 'autoprovision', + explicitAttrs: 'explicitAttrs', + expressionLanguage: 'expressionLanguage' +}; /** - * Load the templates for validating provisioning requests. The introduction of "Lax Mode" enables the addition of + * Load the templates for validating provisioning requests. The introduction of "Lax Mode" enables the addition of * characters which valid in the OPU-UA IoT Agent (e.g. semi-colons) but are usually forbidden by other IoT Agents */ -function setConfiguration(config){ +function setConfiguration(config) { if (config.relaxTemplateValidation) { updateDeviceTemplate = require('../../templates/updateDeviceLax.json'); createDeviceTemplate = require('../../templates/createDeviceLax.json'); @@ -85,7 +81,7 @@ function setConfiguration(config){ * NGSI Service for the registration. */ function handleProvision(req, res, next) { - + /* eslint-disable-next-line no-unused-vars */ function handleProvisioningFinish(error, results) { if (error) { logger.debug(context, 'Device provisioning failed due to the following error: ', error.message); @@ -106,9 +102,9 @@ function handleProvision(req, res, next) { function applyProvisioningMiddlewares(device, callback) { if (provisioningMiddlewares.length > 0) { - var firstMiddleware = provisioningMiddlewares.slice(0, 1)[0], - rest = provisioningMiddlewares.slice(1), - executingMiddlewares = [apply(firstMiddleware, device)]; + const firstMiddleware = provisioningMiddlewares.slice(0, 1)[0]; + const rest = provisioningMiddlewares.slice(1); + let executingMiddlewares = [apply(firstMiddleware, device)]; executingMiddlewares = executingMiddlewares.concat(rest); @@ -122,39 +118,41 @@ function handleProvision(req, res, next) { /* jshint sub: true */ callback(null, { - id: body['device_id'], - apikey: body['apikey'], - type: body['entity_type'], - name: body['entity_name'], - service: service, - subservice: subservice, - active: body['attributes'], - staticAttributes: body['static_attributes'], - lazy: body['lazy'], - commands: body['commands'], - timezone: body['timezone'], - timestamp: body['timestamp'], - endpoint: body['endpoint'], - internalAttributes: body['internal_attributes'], - protocol: body['protocol'], - transport: body['transport'], + id: body.device_id, + apikey: body.apikey, + type: body.entity_type, + name: body.entity_name, + service, + subservice, + active: body.attributes, + staticAttributes: body.static_attributes, + lazy: body.lazy, + commands: body.commands, + timezone: body.timezone, + timestamp: body.timestamp, + endpoint: body.endpoint, + internalAttributes: body.internal_attributes, + protocol: body.protocol, + transport: body.transport, internalId: null, - autoprovision: body['autoprovision'], - explicitAttrs: body['explicitAttrs'], - expressionLanguage: body['expressionLanguage'] + autoprovision: body.autoprovision, + explicitAttrs: body.explicitAttrs, + expressionLanguage: body.expressionLanguage }); } function provisionSingleDevice(device, callback) { - async.waterfall([ - apply(statsRegistry.add, 'deviceCreationRequests', 1), - apply(restUtils.checkMandatoryQueryParams, - ['device_id'], device), - apply(fillDeviceData, req.headers['fiware-service'], req.headers['fiware-servicepath']), - applyProvisioningMiddlewares, - applyProvisioningHandler, - deviceService.register - ], callback); + async.waterfall( + [ + apply(statsRegistry.add, 'deviceCreationRequests', 1), + apply(restUtils.checkMandatoryQueryParams, ['device_id'], device), + apply(fillDeviceData, req.headers['fiware-service'], req.headers['fiware-servicepath']), + applyProvisioningMiddlewares, + applyProvisioningHandler, + deviceService.register + ], + callback + ); } function extractDevices() { @@ -202,9 +200,9 @@ function toProvisioningAPIFormat(device) { timestamp: device.timestamp, endpoint: device.endpoint, transport: device.transport, - attributes: (device.active) ? device.active.map(attributeToProvisioningAPIFormat) : undefined, - lazy: (device.lazy) ? device.lazy.map(attributeToProvisioningAPIFormat) : undefined, - commands: (device.commands) ? device.commands.map(attributeToProvisioningAPIFormat) : undefined, + attributes: device.active ? device.active.map(attributeToProvisioningAPIFormat) : undefined, + lazy: device.lazy ? device.lazy.map(attributeToProvisioningAPIFormat) : undefined, + commands: device.commands ? device.commands.map(attributeToProvisioningAPIFormat) : undefined, static_attributes: device.staticAttributes, internal_attributes: device.internalAttributes, protocol: device.protocol, @@ -227,12 +225,13 @@ function handleListDevices(req, res, next) { if (error) { next(error); } else { - var response = deviceList; + const response = deviceList; response.devices = deviceList.devices.map(toProvisioningAPIFormat); res.status(200).json(response); } - }); + } + ); } /** @@ -240,8 +239,11 @@ function handleListDevices(req, res, next) { * JSON format. */ function handleGetDevice(req, res, next) { - deviceService.getDevice(req.params.deviceId, req.headers['fiware-service'], req.headers['fiware-servicepath'], - function(error, device) { + deviceService.getDevice( + req.params.deviceId, + req.headers['fiware-service'], + req.headers['fiware-servicepath'], + function (error, device) { if (error) { next(error); } else if (device) { @@ -249,25 +251,24 @@ function handleGetDevice(req, res, next) { } else { next(new errors.DeviceNotFound(req.params.deviceId)); } - }); + } + ); } /** * This middleware handles the removal of a particular device specified with the deviceId. */ function handleRemoveDevice(req, res, next) { - - function getDevice(deviceId, service, subservice, callback){ - deviceService.getDevice(deviceId, service, subservice, - function(error, device) { - if (error) { - callback(error); - } else if (device) { - callback(null, device); - } else { - callback(new errors.DeviceNotFound(deviceId)); - } - }); + function getDevice(deviceId, service, subservice, callback) { + deviceService.getDevice(deviceId, service, subservice, function (error, device) { + if (error) { + callback(error); + } else if (device) { + callback(null, device); + } else { + callback(new errors.DeviceNotFound(deviceId)); + } + }); } function applyRemoveDeviceHandler(device, callback) { @@ -282,20 +283,28 @@ function handleRemoveDevice(req, res, next) { return deviceService.unregister(deviceId, service, subservice, callback); } - async.waterfall([ - apply(statsRegistry.add, 'deviceRemovalRequests', 1), - apply(getDevice, req.params.deviceId, req.headers['fiware-service'], req.headers['fiware-servicepath']), - applyRemoveDeviceHandler, - apply(unregisterDevice, req.params.deviceId, - req.headers['fiware-service'], req.headers['fiware-servicepath'])], function (error) { - if (error && error.code !== 404) { - next(error); - } else if (error && error.code === 404) { - next(new errors.DeviceNotFound(req.params.deviceId)); - } else { - res.status(204).send(); + async.waterfall( + [ + apply(statsRegistry.add, 'deviceRemovalRequests', 1), + apply(getDevice, req.params.deviceId, req.headers['fiware-service'], req.headers['fiware-servicepath']), + applyRemoveDeviceHandler, + apply( + unregisterDevice, + req.params.deviceId, + req.headers['fiware-service'], + req.headers['fiware-servicepath'] + ) + ], + function (error) { + if (error && error.code !== 404) { + next(error); + } else if (error && error.code === 404) { + next(new errors.DeviceNotFound(req.params.deviceId)); + } else { + res.status(204).send(); + } } - }); + ); } /** @@ -303,17 +312,20 @@ function handleRemoveDevice(req, res, next) { */ function handleUpdateDevice(req, res, next) { if (req.body.deviceId) { - next(new errors.BadRequest('Can\'t change the ID of a preprovisioned device')); + next(new errors.BadRequest("Can't change the ID of a preprovisioned device")); } else { - deviceService.getDevice(req.params.deviceId, req.headers['fiware-service'], req.headers['fiware-servicepath'], - function(error, device) { + deviceService.getDevice( + req.params.deviceId, + req.headers['fiware-service'], + req.headers['fiware-servicepath'], + function (error, device) { if (error) { next(error); } else if (device) { - var pairs = _.pairs(req.body), - newDevice = _.clone(device); + const pairs = _.pairs(req.body); + const newDevice = _.clone(device); - for (var i in pairs) { + for (const i in pairs) { newDevice[provisioningAPITranslation[pairs[i][0]]] = pairs[i][1]; } @@ -327,7 +339,8 @@ function handleUpdateDevice(req, res, next) { } else { next(new errors.DeviceNotFound(req.params.deviceId)); } - }); + } + ); } } @@ -337,29 +350,30 @@ function handleUpdateDevice(req, res, next) { * @param {Object} router Express request router object. */ function loadContextRoutes(router) { - router.post('/iot/devices', + router.post( + '/iot/devices', restUtils.checkRequestAttributes('headers', mandatoryHeaders), restUtils.checkBody(createDeviceTemplate), handleProvision ); - router.get('/iot/devices', - restUtils.checkRequestAttributes('headers', mandatoryHeaders), - handleListDevices - ); + router.get('/iot/devices', restUtils.checkRequestAttributes('headers', mandatoryHeaders), handleListDevices); - router.get('/iot/devices/:deviceId', + router.get( + '/iot/devices/:deviceId', restUtils.checkRequestAttributes('headers', mandatoryHeaders), handleGetDevice ); - router.put('/iot/devices/:deviceId', + router.put( + '/iot/devices/:deviceId', restUtils.checkRequestAttributes('headers', mandatoryHeaders), restUtils.checkBody(updateDeviceTemplate), handleUpdateDevice ); - router.delete('/iot/devices/:deviceId', + router.delete( + '/iot/devices/:deviceId', restUtils.checkRequestAttributes('headers', mandatoryHeaders), handleRemoveDevice ); diff --git a/lib/services/northBound/northboundServer.js b/lib/services/northBound/northboundServer.js index 153709e9f..e202e948d 100644 --- a/lib/services/northBound/northboundServer.js +++ b/lib/services/northBound/northboundServer.js @@ -20,31 +20,27 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; - -var http = require('http'), - async = require('async'), - express = require('express'), - packageInformation = require('../../../package.json'), - northboundServer, - contextServer = require('./contextServer'), - domainUtils = require('../common/domain'), - middlewares = require('../common/genericMiddleware'), - intoTrans = domainUtils.intoTrans, - deviceProvisioning = require('./deviceProvisioningServer'), - groupProvisioning = require('./deviceGroupAdministrationServer'), - logger = require('logops'), - context = { - op: 'IoTAgentNGSI.NorthboundServer' - }, - bodyParser = require('body-parser'); -function start(config, callback) { +const http = require('http'); +const async = require('async'); +const express = require('express'); +const packageInformation = require('../../../package.json'); +let northboundServer; +const contextServer = require('./contextServer'); +const domainUtils = require('../common/domain'); +const middlewares = require('../common/genericMiddleware'); +const intoTrans = domainUtils.intoTrans; +const deviceProvisioning = require('./deviceProvisioningServer'); +const groupProvisioning = require('./deviceGroupAdministrationServer'); +const logger = require('logops'); +const context = { + op: 'IoTAgentNGSI.NorthboundServer' +}; +const bodyParser = require('body-parser'); +function start(config, callback) { deviceProvisioning.setConfiguration(config); - - var baseRoot = '/', - iotaInformation; + let baseRoot = '/'; northboundServer = { server: null, @@ -68,10 +64,10 @@ function start(config, callback) { baseRoot = config.server.baseRoot; } - iotaInformation = { + const iotaInformation = { libVersion: packageInformation.version, port: config.server.port, - baseRoot: baseRoot + baseRoot }; if (config.iotaVersion) { @@ -108,11 +104,7 @@ function stop(callback) { } function clear(callback) { - async.series([ - deviceProvisioning.clear, - groupProvisioning.clear, - contextServer.clear - ], callback); + async.series([deviceProvisioning.clear, groupProvisioning.clear, contextServer.clear], callback); } exports.setUpdateHandler = intoTrans(context, contextServer.setUpdateHandler); @@ -120,7 +112,7 @@ exports.setQueryHandler = intoTrans(context, contextServer.setQueryHandler); exports.setCommandHandler = intoTrans(context, contextServer.setCommandHandler); exports.setNotificationHandler = intoTrans(context, contextServer.setNotificationHandler); exports.setConfigurationHandler = intoTrans(context, groupProvisioning.setConfigurationHandler); -exports.setRemoveConfigurationHandler = intoTrans (context, groupProvisioning.setRemoveConfigurationHandler); +exports.setRemoveConfigurationHandler = intoTrans(context, groupProvisioning.setRemoveConfigurationHandler); exports.setProvisioningHandler = intoTrans(context, deviceProvisioning.setProvisioningHandler); exports.setRemoveDeviceHandler = intoTrans(context, deviceProvisioning.setRemoveDeviceHandler); exports.addDeviceProvisionMiddleware = deviceProvisioning.addDeviceProvisionMiddleware; diff --git a/lib/services/northBound/restUtils.js b/lib/services/northBound/restUtils.js index 7bcbfd35a..4ccca70f0 100644 --- a/lib/services/northBound/restUtils.js +++ b/lib/services/northBound/restUtils.js @@ -22,18 +22,19 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var logger = require('logops'), - errors = require('../../errors'), - constants = require('../../constants'), - intoTrans = require('../common/domain').intoTrans, - revalidator = require('revalidator'), - moment = require('moment'), - context = { - op: 'IoTAgentNGSI.RestUtils' - }, - _ = require('underscore'); + +/* eslint-disable no-prototype-builtins */ + +const logger = require('logops'); +const errors = require('../../errors'); +const constants = require('../../constants'); +const intoTrans = require('../common/domain').intoTrans; +const revalidator = require('revalidator'); +const moment = require('moment'); +const context = { + op: 'IoTAgentNGSI.RestUtils' +}; +const _ = require('underscore'); /** * Checks all the mandatory attributes in the selected array are present in the presented body object. @@ -42,12 +43,12 @@ var logger = require('logops'), * @param {Object} body Body whose attributes are going to be checked. */ function checkMandatoryQueryParams(mandatoryAttributes, body, callback) { - var missing = []; + const missing = []; - for (var p in mandatoryAttributes) { - var found = false; + for (const p in mandatoryAttributes) { + let found = false; - for (var i in body) { + for (const i in body) { if (body.hasOwnProperty(i)) { if (i === mandatoryAttributes[p]) { found = true; @@ -61,7 +62,7 @@ function checkMandatoryQueryParams(mandatoryAttributes, body, callback) { } if (missing.length !== 0) { - var error = new errors.MissingAttributes('Missing attributes: ' + JSON.stringify(missing)); + const error = new errors.MissingAttributes('Missing attributes: ' + JSON.stringify(missing)); error.code = '400'; callback(error); @@ -81,10 +82,10 @@ function checkMandatoryQueryParams(mandatoryAttributes, body, callback) { */ function checkRequestAttributes(attribute, mandatoryAttributes) { return function headerChecker(req, res, next) { - var headerKeys = _.keys(req[attribute]), - missing = []; + const headerKeys = _.keys(req[attribute]); + const missing = []; - for (var i = 0; i < mandatoryAttributes.length; i++) { + for (let i = 0; i < mandatoryAttributes.length; i++) { if (headerKeys.indexOf(mandatoryAttributes[i]) < 0) { missing.push(mandatoryAttributes[i]); } @@ -106,7 +107,7 @@ function checkRequestAttributes(attribute, mandatoryAttributes) { */ function checkBody(template) { return function bodyMiddleware(req, res, next) { - var errorList = revalidator.validate(req.body, template); + const errorList = revalidator.validate(req.body, template); if (errorList.valid) { next(); @@ -124,9 +125,11 @@ function checkBody(template) { * @return {Boolean} true if timestamp attributes are valid ISO8601. false if not. */ function IsValidTimestamped(payload) { - for (var i in payload.contextElements[0].attributes) { - if (payload.contextElements[0].attributes[i].name === constants.TIMESTAMP_ATTRIBUTE && - ! moment(payload.contextElements[0].attributes[i].value, moment.ISO_8601).isValid()) { + for (const i in payload.contextElements[0].attributes) { + if ( + payload.contextElements[0].attributes[i].name === constants.TIMESTAMP_ATTRIBUTE && + !moment(payload.contextElements[0].attributes[i].value, moment.ISO_8601).isValid() + ) { return false; } } @@ -142,10 +145,9 @@ function IsValidTimestamped(payload) { */ function IsValidTimestampedNgsi2(payload) { function isValidTimestampedNgsi2Entity(entity) { - for (var i in entity) { + for (const i in entity) { if (entity.hasOwnProperty(i)) { - if (i === constants.TIMESTAMP_ATTRIBUTE && - ! moment(entity[i].value, moment.ISO_8601).isValid()) { + if (i === constants.TIMESTAMP_ATTRIBUTE && !moment(entity[i].value, moment.ISO_8601).isValid()) { return false; } } @@ -155,16 +157,15 @@ function IsValidTimestampedNgsi2(payload) { } if (payload instanceof Array) { - for (var i = 0; i < payload.length; i++) { + for (let i = 0; i < payload.length; i++) { if (!isValidTimestampedNgsi2Entity(payload[i])) { return false; } } return true; - } else { - return isValidTimestampedNgsi2Entity(payload); } + return isValidTimestampedNgsi2Entity(payload); } /** @@ -174,7 +175,7 @@ function IsValidTimestampedNgsi2(payload) { * @return {Boolean} true if timestamp attributes are included. false if not. */ function isTimestamped(payload) { - for (var i in payload.contextElements[0].attributes) { + for (const i in payload.contextElements[0].attributes) { if (payload.contextElements[0].attributes[i].name === constants.TIMESTAMP_ATTRIBUTE) { return true; } @@ -190,9 +191,8 @@ function isTimestamped(payload) { * @return {Boolean} true if timestamp attributes are included. false if not. */ function isTimestampedNgsi2(payload) { - function isTimestampedNgsi2Entity(entity) { - for (var i in entity) { + for (const i in entity) { if (entity.hasOwnProperty(i)) { if (i === constants.TIMESTAMP_ATTRIBUTE) { return true; @@ -204,16 +204,15 @@ function isTimestampedNgsi2(payload) { } if (payload instanceof Array) { - for (var i = 0; i < payload.length; i++) { + for (let i = 0; i < payload.length; i++) { if (!isTimestampedNgsi2Entity(payload[i])) { return false; } } return true; - } else { - return isTimestampedNgsi2Entity(payload); } + return isTimestampedNgsi2Entity(payload); } exports.checkMandatoryQueryParams = intoTrans(context, checkMandatoryQueryParams); diff --git a/lib/services/stats/statsRegistry.js b/lib/services/stats/statsRegistry.js index 7577692f2..6900c9940 100644 --- a/lib/services/stats/statsRegistry.js +++ b/lib/services/stats/statsRegistry.js @@ -20,21 +20,22 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; - -var async = require('async'), - _ = require('underscore'), - apply = async.apply, - logger = require('logops'), - config = require('../../commonConfig'), - dbService = require('../../model/dbConn'), - globalStats = {}, - currentStats = {}, - timerActions = [], - timerHandler, - statsContext = { - op: 'IoTAgentNGSI.TimedStats' - }; + +/* eslint-disable no-prototype-builtins */ + +const async = require('async'); +const _ = require('underscore'); +const apply = async.apply; +const logger = require('logops'); +const config = require('../../commonConfig'); +const dbService = require('../../model/dbConn'); +let globalStats = {}; +let currentStats = {}; +let timerActions = []; +let timerHandler; +const statsContext = { + op: 'IoTAgentNGSI.TimedStats' +}; /** * Add a new stat value to the specified key of the stats registry. The stat is added @@ -100,7 +101,7 @@ function globalLoad(values, callback) { globalStats = values; currentStats = {}; - for (var i in values) { + for (const i in values) { if (values.hasOwnProperty(i)) { currentStats[i] = 0; } @@ -113,7 +114,7 @@ function globalLoad(values, callback) { * Reset each of the current stats to value zero. */ function resetCurrent(callback) { - for (var i in currentStats) { + for (const i in currentStats) { if (currentStats.hasOwnProperty(i)) { currentStats[i] = 0; } @@ -176,7 +177,7 @@ function logStats(currentValues, globalValues, callback) { * @param {Object} globalValues Global stat values. */ function mongodbPersistence(currentValues, globalValues, callback) { - var statStamp = _.clone(globalValues); + const statStamp = _.clone(globalValues); statStamp.timestamp = new Date().toISOString(); dbService.db.collection('kpis').insertOne(statStamp, callback); diff --git a/package.json b/package.json index 604c6f028..e4f0c5cbd 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,6 @@ { "name": "iotagent-node-lib", + "license": "AGPL-3.0-only", "description": "IoT Agent library to interface with NGSI Context Broker", "version": "2.14.0-next", "homepage": "https://github.com/telefonicaid/iotagent-node-lib", @@ -30,11 +31,13 @@ }, "scripts": { "clean": "rm -rf package-lock.json && rm -rf node_modules && rm -rf coverage", - "lint": "jshint lib/ --config .jshintrc && jshint test/ --config test/.jshintrc", + "lint": "eslint lib/ bin/ test/ --cache --fix", "lint:md": "remark -f '*.md' 'doc/*.md'", "lint:text": "textlint '*.md' 'doc/*.md'", - "test": "nyc --reporter=text mocha --recursive 'test/**/*.js' --reporter spec --timeout 3000 --ui bdd --exit", - "test:coverage": "nyc --reporter=lcov mocha -- --recursive 'test/**/*.js' --reporter spec --exit", + "prettier": "prettier --config .prettierrc.json --write '**/**/**/**/*.js' '**/**/**/*.js' '**/**/*.js' '**/*.js' '*.js'", + "prettier:text": "prettier 'README.md' 'doc/*.md' 'doc/**/*.md' --no-config --tab-width 4 --print-width 120 --write --prose-wrap always", + "test": "nyc --reporter=text mocha --recursive 'test/**/*.js' --reporter spec --timeout 5000 --ui bdd --exit", + "test:coverage": "nyc --reporter=lcov mocha -- --recursive 'test/**/*.js' --reporter spec --timeout 5000 --exit", "test:coveralls": "npm run test:coverage && cat ./coverage/lcov.info | coveralls && rm -rf ./coverage", "test:watch": "npm run test -- -w ./lib", "watch": "watch 'npm test && npm run lint' ./lib ./test" @@ -60,21 +63,40 @@ }, "devDependencies": { "coveralls": "~3.1.0", - "jshint": "~2.11.1", + "eslint": "~7.5.0", + "eslint-config-tamia": "~7.2.5", + "eslint-plugin-prettier": "~3.1.4", + "husky": "~4.2.5", + "lint-staged": "~10.2.11", + "prettier": "~2.0.5", "mocha": "8.0.1", "nock": "13.0.3", "nyc": "~15.1.0", "remark-cli": "~8.0.1", "remark-preset-lint-recommended": "~4.0.1", + "should": "13.2.3", + "sinon": "~9.0.2", "textlint": "~11.7.6", - "textlint-filter-rule-comments": "~1.2.2", "textlint-rule-common-misspellings": "~1.0.1", "textlint-rule-no-dead-link": "~4.7.0", "textlint-rule-terminology": "~2.1.4", "textlint-rule-write-good": "~1.6.2", - "should": "13.2.3", - "sinon": "~9.0.2", "timekeeper": "2.2.0", "watch": "~1.0.2" + }, + "husky": { + "hooks": { + "pre-commit": "lint-staged" + } + }, + "lint-staged": { + "*.md": [ + "prettier --parser markdown --tab-width 4 --print-width 120 --write --prose-wrap always", + "git add" + ], + "*.js": [ + "prettier --config .prettierrc.json --write", + "git add" + ] } } diff --git a/test/.jshintrc b/test/.jshintrc deleted file mode 100644 index 2cbeefda0..000000000 --- a/test/.jshintrc +++ /dev/null @@ -1,35 +0,0 @@ -{ - "curly": true, - "eqeqeq": true, - "immed": true, - "latedef": true, - "newcap": true, - "noarg": true, - "noempty": true, - "quotmark": "single", - "undef": true, - "unused": true, - "trailing": true, - "maxparams": 6, - "maxdepth": 4, - "camelcase": true, - "maxlen": 120, - "node": true, - "expr": true, - "unused": "vars", - "esversion": 6, - "globals": { - "describe":true, - "it": true, - "expect": true, - "before": true, - "after": true, - "beforeEach": true, - "afterEach": true, - "mock": true - }, - "predef": - [ - "describe", "beforeEach", "afterEach", "it" - ] -} \ No newline at end of file diff --git a/test/tools/utils.js b/test/tools/utils.js index cd3df447a..2ec507dfe 100644 --- a/test/tools/utils.js +++ b/test/tools/utils.js @@ -21,9 +21,7 @@ * please contact with::[daniel.moranjimenez@telefonica.com] */ -'use strict'; - -var fs = require('fs'); +const fs = require('fs'); function readExampleFile(name, raw) { let text = null; diff --git a/test/unit/expressions/expression-test.js b/test/unit/expressions/expression-test.js index 2bd6ddcb4..790fc350a 100644 --- a/test/unit/expressions/expression-test.js +++ b/test/unit/expressions/expression-test.js @@ -20,27 +20,27 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; - -var should = require('should'), - expressionParser = require('../../../lib/plugins/expressionParser'); - -describe('Expression interpreter', function() { - var arithmetic, - scope = { - value: 6, - other: 3, - theString: '12.6, -19.4', - spaces: '5 a b c d 5', - big: 2000, - number: 145, - number2: 155, - number3inside: 200 - }; - - describe('When a expression with a single value is parsed', function() { - it('should return that value', function(done) { - expressionParser.parse('5 * @value', scope, 'Number', function(error, result) { + +/* eslint-disable no-unused-vars */ + +const should = require('should'); +const expressionParser = require('../../../lib/plugins/expressionParser'); + +describe('Expression interpreter', function () { + const scope = { + value: 6, + other: 3, + theString: '12.6, -19.4', + spaces: '5 a b c d 5', + big: 2000, + number: 145, + number2: 155, + number3inside: 200 + }; + + describe('When a expression with a single value is parsed', function () { + it('should return that value', function (done) { + expressionParser.parse('5 * @value', scope, 'Number', function (error, result) { should.not.exist(error); result.should.equal(30); done(); @@ -48,7 +48,7 @@ describe('Expression interpreter', function() { }); }); - arithmetic = [ + const arithmetic = [ ['5 * @value', 30], ['(6 + @value) * 3', 36], ['@value / 12 + 1', 1.5], @@ -59,9 +59,9 @@ describe('Expression interpreter', function() { ]; function arithmeticUseCase(arithmeticExpr) { - describe('When an expression with the arithmetic operation [' + arithmeticExpr[0] + '] is parsed', function() { - it('should be interpreted appropriately', function(done) { - expressionParser.parse(arithmeticExpr[0], scope, 'Number', function(error, result) { + describe('When an expression with the arithmetic operation [' + arithmeticExpr[0] + '] is parsed', function () { + it('should be interpreted appropriately', function (done) { + expressionParser.parse(arithmeticExpr[0], scope, 'Number', function (error, result) { should.not.exist(error); result.should.approximately(arithmeticExpr[1], 0.000001); done(); @@ -70,13 +70,13 @@ describe('Expression interpreter', function() { }); } - for (var i = 0; i < arithmetic.length; i++) { + for (let i = 0; i < arithmetic.length; i++) { arithmeticUseCase(arithmetic[i]); } - describe('When an expression with two strings is concatenated', function() { - it('should return the concatenation of both strings', function(done) { - expressionParser.parse('"Pruebas" # "DeStrings"', scope, 'String', function(error, result) { + describe('When an expression with two strings is concatenated', function () { + it('should return the concatenation of both strings', function (done) { + expressionParser.parse('"Pruebas" # "DeStrings"', scope, 'String', function (error, result) { should.not.exist(error); result.should.equal('PruebasDeStrings'); done(); @@ -84,24 +84,24 @@ describe('Expression interpreter', function() { }); }); - describe('When string transformation functions are executed', function() { - it('should return the appropriate piece of the string', function(done) { + describe('When string transformation functions are executed', function () { + it('should return the appropriate piece of the string', function (done) { expressionParser.parse( - 'trim(substr(@theString, indexOf(@theString, \",\") + 1, length(@theString)))', + 'trim(substr(@theString, indexOf(@theString, ",") + 1, length(@theString)))', scope, 'String', - function(error, result) { + function (error, result) { should.not.exist(error); result.should.equal('-19.4'); done(); - }); + } + ); }); }); - describe('When an expression contains variables with numbers', function() { - it('should return the appropriate result', function(done) { - expressionParser.parse('@number + @number2 + @number3inside', - scope, 'String', function(error, result) { + describe('When an expression contains variables with numbers', function () { + it('should return the appropriate result', function (done) { + expressionParser.parse('@number + @number2 + @number3inside', scope, 'String', function (error, result) { should.not.exist(error); result.should.equal(500); done(); @@ -109,44 +109,29 @@ describe('Expression interpreter', function() { }); }); - describe('When an expression contains multiple parenthesis', function() { - it('should return the appropriate result', function(done) { - expressionParser.parse('((@number) * (@number2))', - scope, 'String', function(error, result) { - should.not.exist(error); - result.should.equal(22475); - done(); - }); - }); - }); - - describe('When trim() function is executed', function() { - it('should return the appropriate piece of the string', function(done) { - expressionParser.parse( - 'trim(@spaces)', - scope, - 'String', - function(error, result) { - should.not.exist(error); - result.should.equal('5 a b c d 5'); - done(); - }); + describe('When an expression contains multiple parenthesis', function () { + it('should return the appropriate result', function (done) { + expressionParser.parse('((@number) * (@number2))', scope, 'String', function (error, result) { + should.not.exist(error); + result.should.equal(22475); + done(); + }); }); }); - describe('When an expression with strings containing spaces is concatenated', function() { - it('should honour the whitespaces', function(done) { - expressionParser.parse('"Pruebas " # "De Strings"', scope, 'String', function(error, result) { + describe('When trim() function is executed', function () { + it('should return the appropriate piece of the string', function (done) { + expressionParser.parse('trim(@spaces)', scope, 'String', function (error, result) { should.not.exist(error); - result.should.equal('Pruebas De Strings'); + result.should.equal('5 a b c d 5'); done(); }); }); }); - describe('When an expression with strings with single quotation marks is parsed', function() { - it('should accept the strings', function(done) { - expressionParser.parse('\'Pruebas \' # \'De Strings\'', scope, 'String', function(error, result) { + describe('When an expression with strings containing spaces is concatenated', function () { + it('should honour the whitespaces', function (done) { + expressionParser.parse('"Pruebas " # "De Strings"', scope, 'String', function (error, result) { should.not.exist(error); result.should.equal('Pruebas De Strings'); done(); @@ -154,9 +139,25 @@ describe('Expression interpreter', function() { }); }); - describe('When a string is concatenated with a number', function() { - it('should result in a string concatenation', function(done) { - expressionParser.parse('"number " # 5', scope, 'String', function(error, result) { + describe('When an expression with strings with single quotation marks is parsed', function () { + it('should accept the strings', function (done) { + expressionParser.parse( + "'Pruebas ' # 'De Strings'", + + scope, + 'String', + function (error, result) { + should.not.exist(error); + result.should.equal('Pruebas De Strings'); + done(); + } + ); + }); + }); + + describe('When a string is concatenated with a number', function () { + it('should result in a string concatenation', function (done) { + expressionParser.parse('"number " # 5', scope, 'String', function (error, result) { should.not.exist(error); result.should.equal('number 5'); done(); @@ -164,9 +165,9 @@ describe('Expression interpreter', function() { }); }); - describe('When an expression with a wrong type is parsed', function() { - it('should raise a WRONG_EXPRESSION_TYPE error', function(done) { - expressionParser.parse('"number " # 5', scope, 'Device', function(error, result) { + describe('When an expression with a wrong type is parsed', function () { + it('should raise a WRONG_EXPRESSION_TYPE error', function (done) { + expressionParser.parse('"number " # 5', scope, 'Device', function (error, result) { should.exist(error); error.name.should.equal('WRONG_EXPRESSION_TYPE'); done(); @@ -174,9 +175,9 @@ describe('Expression interpreter', function() { }); }); - describe('When an expression with a parse error is parsed', function() { - it('should raise an INVALID_EXPRESSION error', function(done) { - expressionParser.parse('"numb+sd ññ ((', scope, 'Number', function(error, result) { + describe('When an expression with a parse error is parsed', function () { + it('should raise an INVALID_EXPRESSION error', function (done) { + expressionParser.parse('"numb+sd ññ ((', scope, 'Number', function (error, result) { should.exist(error); error.name.should.equal('INVALID_EXPRESSION'); done(); @@ -184,14 +185,13 @@ describe('Expression interpreter', function() { }); }); - describe('When an string function is used with an expression', function() { - it('should work on the expression value', function(done) { - expressionParser.parse('indexOf(24 * @big, "80")', scope, 'String', function(error, result) { + describe('When an string function is used with an expression', function () { + it('should work on the expression value', function (done) { + expressionParser.parse('indexOf(24 * @big, "80")', scope, 'String', function (error, result) { should.not.exist(error); result.should.equal(1); done(); }); }); }); - }); diff --git a/test/unit/expressions/expressionBasedTransformations-test.js b/test/unit/expressions/expressionBasedTransformations-test.js index c59cafb9c..2d823590d 100644 --- a/test/unit/expressions/expressionBasedTransformations-test.js +++ b/test/unit/expressions/expressionBasedTransformations-test.js @@ -20,110 +20,107 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; -/* jshint camelcase: false */ - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm', + expression: '${@pressure * 20}' + } + ] }, - server: { - port: 4041 + LightError: { + commands: [], + type: 'Light', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm', + expression: '${@pressure * / 20}' + } + ] }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm', - expression: '${@pressure * 20}' - } - ] - }, - 'LightError': { - commands: [], - type: 'Light', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm', - expression: '${@pressure * / 20}' - } - ] - }, - 'WeatherStation': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm', - expression: '${@pressure * 20}' - }, - { - object_id: 'h', - name: 'humidity', - type: 'Percentage' - }, - { - name: 'weather', - type: 'Summary', - expression: 'Humidity ${@humidity / 2} and pressure ${@pressure * 20}' - } - ] - }, - 'WeatherStationMultiple': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure25', - type: 'Hgmm', - expression: '${@pressure * 20}' - }, - { - object_id: 'h', - name: 'humidity12', - type: 'Percentage' - }, - { - name: 'weather', - type: 'Summary', - expression: 'Humidity ${@humidity12 / 2} and pressure ${@pressure25 * 20}' - } - ] - } + WeatherStation: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm', + expression: '${@pressure * 20}' + }, + { + object_id: 'h', + name: 'humidity', + type: 'Percentage' + }, + { + name: 'weather', + type: 'Summary', + expression: 'Humidity ${@humidity / 2} and pressure ${@pressure * 20}' + } + ] }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }; + WeatherStationMultiple: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure25', + type: 'Hgmm', + expression: '${@pressure * 20}' + }, + { + object_id: 'h', + name: 'humidity12', + type: 'Percentage' + }, + { + name: 'weather', + type: 'Summary', + expression: 'Humidity ${@humidity12 / 2} and pressure ${@pressure25 * 20}' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; -describe('NGSI-v1 - Expression-based transformations plugin', function() { - beforeEach(function(done) { +describe('NGSI-v1 - Expression-based transformations plugin', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.attributeAlias.update); iotAgentLib.addQueryMiddleware(iotAgentLib.dataPlugins.attributeAlias.query); iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.expressionTransformation.update); @@ -132,14 +129,14 @@ describe('NGSI-v1 - Expression-based transformations plugin', function() { }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When an update comes for attributes with expressions', function() { - var values = [ + describe('When an update comes for attributes with expressions', function () { + const values = [ { name: 'p', type: 'centigrades', @@ -147,20 +144,26 @@ describe('NGSI-v1 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextExpressionPlugin1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextExpressionPlugin1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextExpressionPlugin1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextExpressionPlugin1Success.json' + ) + ); }); - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -168,8 +171,8 @@ describe('NGSI-v1 - Expression-based transformations plugin', function() { }); }); - describe('When an update comes for expressions with syntax errors', function() { - var values = [ + describe('When an update comes for expressions with syntax errors', function () { + const values = [ { name: 'p', type: 'centigrades', @@ -177,20 +180,26 @@ describe('NGSI-v1 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextExpressionPlugin4.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextExpressionPlugin1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextExpressionPlugin4.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextExpressionPlugin1Success.json' + ) + ); }); - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'LightError', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'LightError', '', values, function (error) { should.exist(error); error.name.should.equal('INVALID_EXPRESSION'); error.code.should.equal(400); @@ -199,8 +208,8 @@ describe('NGSI-v1 - Expression-based transformations plugin', function() { }); }); - describe('When there are expression attributes that are just calculated (not sent by the device)', function() { - var values = [ + describe('When there are expression attributes that are just calculated (not sent by the device)', function () { + const values = [ { name: 'p', type: 'centigrades', @@ -213,20 +222,26 @@ describe('NGSI-v1 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextExpressionPlugin2.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextExpressionPlugin2Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextExpressionPlugin2.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextExpressionPlugin2Success.json' + ) + ); }); - it('should calculate them and add them to the payload', function(done) { - iotAgentLib.update('ws1', 'WeatherStation', '', values, function(error) { + it('should calculate them and add them to the payload', function (done) { + iotAgentLib.update('ws1', 'WeatherStation', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -234,8 +249,8 @@ describe('NGSI-v1 - Expression-based transformations plugin', function() { }); }); - describe('When an expression with multiple variables with numbers arrive', function() { - var values = [ + describe('When an expression with multiple variables with numbers arrive', function () { + const values = [ { name: 'p', type: 'centigrades', @@ -248,20 +263,26 @@ describe('NGSI-v1 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextExpressionPlugin5.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextExpressionPlugin5Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextExpressionPlugin5.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextExpressionPlugin5Success.json' + ) + ); }); - it('should calculate it and add it to the payload', function(done) { - iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function(error) { + it('should calculate it and add it to the payload', function (done) { + iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -269,8 +290,8 @@ describe('NGSI-v1 - Expression-based transformations plugin', function() { }); }); - describe('When a measure arrives and there is not enough information to calculate an expression', function() { - var values = [ + describe('When a measure arrives and there is not enough information to calculate an expression', function () { + const values = [ { name: 'p', type: 'centigrades', @@ -278,20 +299,26 @@ describe('NGSI-v1 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextExpressionPlugin3.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextExpressionPlugin3Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextExpressionPlugin3.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextExpressionPlugin3Success.json' + ) + ); }); - it('should not calculate the expression', function(done) { - iotAgentLib.update('ws1', 'WeatherStation', '', values, function(error) { + it('should not calculate the expression', function (done) { + iotAgentLib.update('ws1', 'WeatherStation', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); diff --git a/test/unit/expressions/expressionCombinedTransformations-test.js b/test/unit/expressions/expressionCombinedTransformations-test.js index 8132d9474..fc539a1cd 100644 --- a/test/unit/expressions/expressionCombinedTransformations-test.js +++ b/test/unit/expressions/expressionCombinedTransformations-test.js @@ -22,110 +22,109 @@ * * Developed by: Federico M. Facca - Martel Innovate */ -'use strict'; /* jshint camelcase: false */ -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfigJexl = { - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 - }, - defaultExpressionLanguage: 'jexl', - types: { - 'WeatherStationLegacy': { - commands: [], - type: 'WeatherStation', - expressionLanguage: 'legacy', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm', - expression: '${@pressure * 20}' - } - ] - }, - 'WeatherStationJexl': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm', - expression: 'pressure * 20' - } - ] - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M', - throttling: 'PT5S' +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfigJexl = { + contextBroker: { + host: '192.168.1.1', + port: '1026' }, - iotAgentConfigLegacy = { - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 + server: { + port: 4041 + }, + defaultExpressionLanguage: 'jexl', + types: { + WeatherStationLegacy: { + commands: [], + type: 'WeatherStation', + expressionLanguage: 'legacy', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm', + expression: '${@pressure * 20}' + } + ] }, - types: { - 'WeatherStationLegacy': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm', - expression: '${@pressure * 20}' - } - ] - }, - 'WeatherStationJexl': { - commands: [], - type: 'WeatherStation', - expressionLanguage: 'jexl', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm', - expression: 'pressure * 20' - } - ] - } + WeatherStationJexl: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm', + expression: 'pressure * 20' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M', + throttling: 'PT5S' +}; +const iotAgentConfigLegacy = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + WeatherStationLegacy: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm', + expression: '${@pressure * 20}' + } + ] }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M', - throttling: 'PT5S' - }; + WeatherStationJexl: { + commands: [], + type: 'WeatherStation', + expressionLanguage: 'jexl', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm', + expression: 'pressure * 20' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M', + throttling: 'PT5S' +}; -describe('Combine Jexl and legacy expressions (default JEXL)', function() { - beforeEach(function(done) { +describe('Combine Jexl and legacy expressions (default JEXL)', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfigJexl, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfigJexl, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.attributeAlias.update); iotAgentLib.addQueryMiddleware(iotAgentLib.dataPlugins.attributeAlias.query); iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.expressionTransformation.update); @@ -134,35 +133,41 @@ describe('Combine Jexl and legacy expressions (default JEXL)', function() { }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When an update comes for type with expression "legacy"', function() { - var values = [ + describe('When an update comes for type with expression "legacy"', function () { + const values = [ { name: 'p', type: 'centigrades', value: '52' } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextExpressionPlugin3.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextExpressionPlugin3Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextExpressionPlugin3.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextExpressionPlugin3Success.json' + ) + ); }); - - it('should apply the legacy expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStationLegacy', '', values, function(error) { + + it('should apply the legacy expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStationLegacy', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -170,44 +175,49 @@ describe('Combine Jexl and legacy expressions (default JEXL)', function() { }); }); - describe('When an update comes for type with expression "JEXL" - default', function() { - var values = [ + describe('When an update comes for type with expression "JEXL" - default', function () { + const values = [ { name: 'p', type: 'centigrades', value: '52' } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextExpressionPlugin3.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextExpressionPlugin3Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextExpressionPlugin3.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextExpressionPlugin3Success.json' + ) + ); }); - - it('should apply the default (JEXL) expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStationJexl', '', values, function(error) { - should.not.exist(error); - contextBrokerMock.done(); - done(); + + it('should apply the default (JEXL) expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStationJexl', '', values, function (error) { + should.not.exist(error); + contextBrokerMock.done(); + done(); }); }); }); - }); -describe('Combine Jexl and legacy expressions (default Legacy)', function() { - beforeEach(function(done) { +describe('Combine Jexl and legacy expressions (default Legacy)', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfigLegacy, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfigLegacy, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.attributeAlias.update); iotAgentLib.addQueryMiddleware(iotAgentLib.dataPlugins.attributeAlias.query); iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.expressionTransformation.update); @@ -216,35 +226,41 @@ describe('Combine Jexl and legacy expressions (default Legacy)', function() { }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When an update comes for type with expression "legacy" - default', function() { - var values = [ + describe('When an update comes for type with expression "legacy" - default', function () { + const values = [ { name: 'p', type: 'centigrades', value: '52' } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextExpressionPlugin3.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextExpressionPlugin3Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextExpressionPlugin3.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextExpressionPlugin3Success.json' + ) + ); }); - - it('should apply the legacy expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStationLegacy', '', values, function(error) { + + it('should apply the legacy expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStationLegacy', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -252,34 +268,39 @@ describe('Combine Jexl and legacy expressions (default Legacy)', function() { }); }); - describe('When an update comes for type with expression "JEXL"', function() { - var values = [ + describe('When an update comes for type with expression "JEXL"', function () { + const values = [ { name: 'p', type: 'centigrades', value: '52' } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextExpressionPlugin3.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextExpressionPlugin3Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextExpressionPlugin3.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextExpressionPlugin3Success.json' + ) + ); }); - - it('should apply the default (JEXL) expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStationJexl', '', values, function(error) { - should.not.exist(error); - contextBrokerMock.done(); - done(); + + it('should apply the default (JEXL) expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStationJexl', '', values, function (error) { + should.not.exist(error); + contextBrokerMock.done(); + done(); }); }); }); - }); diff --git a/test/unit/expressions/jexlBasedTransformations-test.js b/test/unit/expressions/jexlBasedTransformations-test.js index 31f74cd0e..405566b66 100644 --- a/test/unit/expressions/jexlBasedTransformations-test.js +++ b/test/unit/expressions/jexlBasedTransformations-test.js @@ -22,112 +22,111 @@ * * Developed by: Federico M. Facca - Martel Innovate */ -'use strict'; /* jshint camelcase: false */ -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + defaultExpressionLanguage: 'jexl', + types: { + Light: { + commands: [], + type: 'Light', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm', + expression: 'pressure * 20' + } + ] }, - server: { - port: 4041 + LightError: { + commands: [], + type: 'Light', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm', + expression: 'pressure * / 20' + } + ] }, - defaultExpressionLanguage: 'jexl', - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm', - expression: 'pressure * 20' - } - ] - }, - 'LightError': { - commands: [], - type: 'Light', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm', - expression: 'pressure * / 20' - } - ] - }, - 'WeatherStation': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm', - expression: 'pressure * 20' - }, - { - object_id: 'h', - name: 'humidity', - type: 'Percentage' - }, - { - name: 'weather', - type: 'Summary', - expression: '"Humidity " + (humidity / 2) + " and pressure " + (pressure * 20)' - } - ] - }, - 'WeatherStationMultiple': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure25', - type: 'Hgmm', - expression: 'pressure * 20' - }, - { - object_id: 'h', - name: 'humidity12', - type: 'Percentage' - }, - { - name: 'weather', - type: 'Summary', - expression: '"Humidity " + (humidity12 / 2) + " and pressure " + (pressure25 * 20)' - } - ] - } + WeatherStation: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm', + expression: 'pressure * 20' + }, + { + object_id: 'h', + name: 'humidity', + type: 'Percentage' + }, + { + name: 'weather', + type: 'Summary', + expression: '"Humidity " + (humidity / 2) + " and pressure " + (pressure * 20)' + } + ] }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M', - throttling: 'PT5S' - }; + WeatherStationMultiple: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure25', + type: 'Hgmm', + expression: 'pressure * 20' + }, + { + object_id: 'h', + name: 'humidity12', + type: 'Percentage' + }, + { + name: 'weather', + type: 'Summary', + expression: '"Humidity " + (humidity12 / 2) + " and pressure " + (pressure25 * 20)' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M', + throttling: 'PT5S' +}; -describe('Javascript Expression Language (JEXL) based transformations plugin ', function() { - beforeEach(function(done) { +describe('Javascript Expression Language (JEXL) based transformations plugin ', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.attributeAlias.update); iotAgentLib.addQueryMiddleware(iotAgentLib.dataPlugins.attributeAlias.query); iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.expressionTransformation.update); @@ -136,35 +135,41 @@ describe('Javascript Expression Language (JEXL) based transformations plugin ', }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When an update comes for attributes with expressions', function() { - var values = [ + describe('When an update comes for attributes with expressions', function () { + const values = [ { name: 'p', type: 'centigrades', value: '52' } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextExpressionPlugin1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextExpressionPlugin1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextExpressionPlugin1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextExpressionPlugin1Success.json' + ) + ); }); - - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -172,29 +177,35 @@ describe('Javascript Expression Language (JEXL) based transformations plugin ', }); }); - describe('When an update comes for expressions with syntax errors', function() { - var values = [ + describe('When an update comes for expressions with syntax errors', function () { + const values = [ { name: 'p', type: 'centigrades', value: '52' } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextExpressionPlugin4.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextExpressionPlugin1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextExpressionPlugin4.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextExpressionPlugin1Success.json' + ) + ); }); - - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'LightError', '', values, function(error) { + + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'LightError', '', values, function (error) { should.exist(error); error.name.should.equal('INVALID_EXPRESSION'); error.code.should.equal(400); @@ -202,9 +213,9 @@ describe('Javascript Expression Language (JEXL) based transformations plugin ', }); }); }); - - describe('When there are expression attributes that are just calculated (not sent by the device)', function() { - var values = [ + + describe('When there are expression attributes that are just calculated (not sent by the device)', function () { + const values = [ { name: 'p', type: 'centigrades', @@ -216,30 +227,36 @@ describe('Javascript Expression Language (JEXL) based transformations plugin ', value: '12' } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextExpressionPlugin2.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextExpressionPlugin2Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextExpressionPlugin2.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextExpressionPlugin2Success.json' + ) + ); }); - - it('should calculate them and add them to the payload', function(done) { - iotAgentLib.update('ws1', 'WeatherStation', '', values, function(error) { + + it('should calculate them and add them to the payload', function (done) { + iotAgentLib.update('ws1', 'WeatherStation', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - - describe('When an expression with multiple variables with numbers arrive', function() { - var values = [ + + describe('When an expression with multiple variables with numbers arrive', function () { + const values = [ { name: 'p', type: 'centigrades', @@ -251,51 +268,63 @@ describe('Javascript Expression Language (JEXL) based transformations plugin ', value: '12' } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextExpressionPlugin5.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextExpressionPlugin5Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextExpressionPlugin5.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextExpressionPlugin5Success.json' + ) + ); }); - - it('should calculate it and add it to the payload', function(done) { - iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function(error) { + + it('should calculate it and add it to the payload', function (done) { + iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - - describe('When a measure arrives and there is not enough information to calculate an expression', function() { - var values = [ + + describe('When a measure arrives and there is not enough information to calculate an expression', function () { + const values = [ { name: 'p', type: 'centigrades', value: '52' } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextExpressionPlugin3.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextExpressionPlugin3Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextExpressionPlugin3.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextExpressionPlugin3Success.json' + ) + ); }); - - it('should not calculate the expression', function(done) { - iotAgentLib.update('ws1', 'WeatherStation', '', values, function(error) { + + it('should not calculate the expression', function (done) { + iotAgentLib.update('ws1', 'WeatherStation', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); diff --git a/test/unit/expressions/jexlExpression-test.js b/test/unit/expressions/jexlExpression-test.js index 316a7e6b3..0ff8095d4 100644 --- a/test/unit/expressions/jexlExpression-test.js +++ b/test/unit/expressions/jexlExpression-test.js @@ -20,33 +20,31 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; -var should = require('should'), - expressionParser = require('../../../lib/plugins/jexlParser'); - -describe('Jexl expression interpreter', function() { - var arithmetic, - scope = { - value: 6, - other: 3, - theString: '12.6, -19.4', - spaces: '5 a b c d 5', - big: 2000, - number: 145, - number2: 155, - number3inside: 200, - floatNumber: 1.2, - array: [1,2], - object: { - name: 'John', - surname: 'Doe' - } - }; - - describe('When a expression with a single value is parsed', function() { - it('should return that value', function(done) { - expressionParser.parse('5 * value', scope, function(error, result) { +const should = require('should'); +const expressionParser = require('../../../lib/plugins/jexlParser'); + +describe('Jexl expression interpreter', function () { + const scope = { + value: 6, + other: 3, + theString: '12.6, -19.4', + spaces: '5 a b c d 5', + big: 2000, + number: 145, + number2: 155, + number3inside: 200, + floatNumber: 1.2, + array: [1, 2], + object: { + name: 'John', + surname: 'Doe' + } + }; + + describe('When a expression with a single value is parsed', function () { + it('should return that value', function (done) { + expressionParser.parse('5 * value', scope, function (error, result) { should.not.exist(error); result.should.equal(30); done(); @@ -54,7 +52,7 @@ describe('Jexl expression interpreter', function() { }); }); - arithmetic = [ + const arithmetic = [ ['5 * value', 30], ['(6 + value) * 3', 36], ['value / 12 + 1', 1.5], @@ -65,9 +63,9 @@ describe('Jexl expression interpreter', function() { ]; function arithmeticUseCase(arithmeticExpr) { - describe('When an expression with the arithmetic operation [' + arithmeticExpr[0] + '] is parsed', function() { - it('should be interpreted appropriately', function(done) { - expressionParser.parse(arithmeticExpr[0], scope, function(error, result) { + describe('When an expression with the arithmetic operation [' + arithmeticExpr[0] + '] is parsed', function () { + it('should be interpreted appropriately', function (done) { + expressionParser.parse(arithmeticExpr[0], scope, function (error, result) { should.not.exist(error); result.should.approximately(arithmeticExpr[1], 0.000001); done(); @@ -76,13 +74,13 @@ describe('Jexl expression interpreter', function() { }); } - for (var i = 0; i < arithmetic.length; i++) { + for (let i = 0; i < arithmetic.length; i++) { arithmeticUseCase(arithmetic[i]); } - describe('When an expression with two strings is concatenated', function() { - it('should return the concatenation of both strings', function(done) { - expressionParser.parse('"Pruebas" + "DeStrings"', scope, function(error, result) { + describe('When an expression with two strings is concatenated', function () { + it('should return the concatenation of both strings', function (done) { + expressionParser.parse('"Pruebas" + "DeStrings"', scope, function (error, result) { should.not.exist(error); result.should.equal('PruebasDeStrings'); done(); @@ -90,23 +88,23 @@ describe('Jexl expression interpreter', function() { }); }); - describe('When string transformation functions are executed', function() { - it('should return the appropriate piece of the string', function(done) { + describe('When string transformation functions are executed', function () { + it('should return the appropriate piece of the string', function (done) { expressionParser.parse( - 'theString|substr(theString|indexOf(\",\") + 1, theString|length)|trim', + 'theString|substr(theString|indexOf(",") + 1, theString|length)|trim', scope, - function(error, result) { + function (error, result) { should.not.exist(error); result.should.equal('-19.4'); done(); - }); + } + ); }); }); - describe('When an expression contains variables with numbers', function() { - it('should return the appropriate result', function(done) { - expressionParser.parse('number + number2 + number3inside', - scope, function(error, result) { + describe('When an expression contains variables with numbers', function () { + it('should return the appropriate result', function (done) { + expressionParser.parse('number + number2 + number3inside', scope, function (error, result) { should.not.exist(error); result.should.equal(500); done(); @@ -114,10 +112,9 @@ describe('Jexl expression interpreter', function() { }); }); - describe('When an expression contains variables with float numbers', function() { - it('should return the appropriate result', function(done) { - expressionParser.parse('floatNumber * 2', - scope, function(error, result) { + describe('When an expression contains variables with float numbers', function () { + it('should return the appropriate result', function (done) { + expressionParser.parse('floatNumber * 2', scope, function (error, result) { should.not.exist(error); result.should.equal(2.4); done(); @@ -125,10 +122,9 @@ describe('Jexl expression interpreter', function() { }); }); - describe('When an expression contains variables with float numbers and strings', function() { - it('should return the appropriate result', function(done) { - expressionParser.parse('floatNumber +"echo"', - scope, function(error, result) { + describe('When an expression contains variables with float numbers and strings', function () { + it('should return the appropriate result', function (done) { + expressionParser.parse('floatNumber +"echo"', scope, function (error, result) { should.not.exist(error); result.should.equal('1.2echo'); done(); @@ -136,33 +132,29 @@ describe('Jexl expression interpreter', function() { }); }); - describe('When an expression contains multiple parenthesis', function() { - it('should return the appropriate result', function(done) { - expressionParser.parse('((number) * (number2))', - scope, function(error, result) { - should.not.exist(error); - result.should.equal(22475); - done(); - }); + describe('When an expression contains multiple parenthesis', function () { + it('should return the appropriate result', function (done) { + expressionParser.parse('((number) * (number2))', scope, function (error, result) { + should.not.exist(error); + result.should.equal(22475); + done(); + }); }); }); - describe('When trim() function is executed', function() { - it('should return the appropriate piece of the string', function(done) { - expressionParser.parse( - 'spaces|trim', - scope, - function(error, result) { - should.not.exist(error); - result.should.equal('5 a b c d 5'); - done(); - }); + describe('When trim() function is executed', function () { + it('should return the appropriate piece of the string', function (done) { + expressionParser.parse('spaces|trim', scope, function (error, result) { + should.not.exist(error); + result.should.equal('5 a b c d 5'); + done(); + }); }); }); - describe('When an expression with strings containing spaces is concatenated', function() { - it('should honour the whitespaces', function(done) { - expressionParser.parse('"Pruebas " + "De Strings"', scope, function(error, result) { + describe('When an expression with strings containing spaces is concatenated', function () { + it('should honour the whitespaces', function (done) { + expressionParser.parse('"Pruebas " + "De Strings"', scope, function (error, result) { should.not.exist(error); result.should.equal('Pruebas De Strings'); done(); @@ -170,9 +162,9 @@ describe('Jexl expression interpreter', function() { }); }); - describe('When an expression with strings with single quotation marks is parsed', function() { - it('should accept the strings', function(done) { - expressionParser.parse('\'Pruebas \' + \'De Strings\'', scope, function(error, result) { + describe('When an expression with strings with single quotation marks is parsed', function () { + it('should accept the strings', function (done) { + expressionParser.parse("'Pruebas ' + 'De Strings'", scope, function (error, result) { should.not.exist(error); result.should.equal('Pruebas De Strings'); done(); @@ -180,9 +172,9 @@ describe('Jexl expression interpreter', function() { }); }); - describe('When a string is concatenated with a number', function() { - it('should result in a string concatenation', function(done) { - expressionParser.parse('"number " + 5', scope, function(error, result) { + describe('When a string is concatenated with a number', function () { + it('should result in a string concatenation', function (done) { + expressionParser.parse('"number " + 5', scope, function (error, result) { should.not.exist(error); result.should.equal('number 5'); done(); @@ -190,9 +182,10 @@ describe('Jexl expression interpreter', function() { }); }); - describe('When an expression with a parse error is parsed', function() { - it('should raise an INVALID_EXPRESSION error', function(done) { - expressionParser.parse('"numb+sd ññ ((', scope, function(error, result) { + describe('When an expression with a parse error is parsed', function () { + it('should raise an INVALID_EXPRESSION error', function (done) { + /* eslint-disable-next-line no-unused-vars */ + expressionParser.parse('"numb+sd ññ ((', scope, function (error, result) { should.exist(error); error.name.should.equal('INVALID_EXPRESSION'); done(); @@ -200,9 +193,9 @@ describe('Jexl expression interpreter', function() { }); }); - describe('When an string function is used with an expression', function() { - it('should work on the expression value', function(done) { - expressionParser.parse('(24 * big)|indexOf("80")', scope, function(error, result) { + describe('When an string function is used with an expression', function () { + it('should work on the expression value', function (done) { + expressionParser.parse('(24 * big)|indexOf("80")', scope, function (error, result) { should.not.exist(error); result.should.equal(1); done(); @@ -210,9 +203,9 @@ describe('Jexl expression interpreter', function() { }); }); - describe('When an ternary operator is used with an expression', function() { - it('should work on the expression value', function(done) { - expressionParser.parse('value == 6? true : false', scope, function(error, result) { + describe('When an ternary operator is used with an expression', function () { + it('should work on the expression value', function (done) { + expressionParser.parse('value == 6? true : false', scope, function (error, result) { should.not.exist(error); result.should.equal(true); done(); @@ -220,9 +213,9 @@ describe('Jexl expression interpreter', function() { }); }); - describe('When an logic operator is used with an expression', function() { - it('should work on the expression value', function(done) { - expressionParser.parse('value == 6 && spaces|indexOf("a")>0', scope, function(error, result) { + describe('When an logic operator is used with an expression', function () { + it('should work on the expression value', function (done) { + expressionParser.parse('value == 6 && spaces|indexOf("a")>0', scope, function (error, result) { should.not.exist(error); result.should.equal(true); done(); @@ -230,9 +223,9 @@ describe('Jexl expression interpreter', function() { }); }); - describe('When a function is applied to an array', function() { - it('should work on the expression value', function(done) { - expressionParser.parse('array[1]+1', scope, function(error, result) { + describe('When a function is applied to an array', function () { + it('should work on the expression value', function (done) { + expressionParser.parse('array[1]+1', scope, function (error, result) { should.not.exist(error); result.should.equal(3); done(); @@ -240,9 +233,9 @@ describe('Jexl expression interpreter', function() { }); }); - describe('When a function is applied to an object', function() { - it('should work on the expression value', function(done) { - expressionParser.parse('object.name', scope, function(error, result) { + describe('When a function is applied to an object', function () { + it('should work on the expression value', function (done) { + expressionParser.parse('object.name', scope, function (error, result) { should.not.exist(error); result.should.equal('John'); done(); @@ -250,14 +243,13 @@ describe('Jexl expression interpreter', function() { }); }); - describe('When an expression aims at creating an object', function() { - it('it should work', function(done) { - expressionParser.parse('{type:"Point",coordinates: [value,other]}', scope, function(error, result) { + describe('When an expression aims at creating an object', function () { + it('it should work', function (done) { + expressionParser.parse('{type:"Point",coordinates: [value,other]}', scope, function (error, result) { should.not.exist(error); - result.should.deepEqual({type:'Point',coordinates: [6,3]}); + result.should.deepEqual({ type: 'Point', coordinates: [6, 3] }); done(); }); }); }); - }); diff --git a/test/unit/general/alarmManagement-test.js b/test/unit/general/alarmManagement-test.js index 8579070df..01a543282 100644 --- a/test/unit/general/alarmManagement-test.js +++ b/test/unit/general/alarmManagement-test.js @@ -20,56 +20,49 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; -var iotagentLib = require('../../../lib/fiware-iotagent-lib'), - alarmManagement = iotagentLib.alarms, - logger = require('logops'), - should = require('should'); +const iotagentLib = require('../../../lib/fiware-iotagent-lib'); +const alarmManagement = iotagentLib.alarms; +const logger = require('logops'); +const should = require('should'); -describe('Alarm management system', function() { - /* jshint sub:true */ - - beforeEach(function() { +describe('Alarm management system', function () { + beforeEach(function () { logger.setLevel('FATAL'); alarmManagement.clean(); }); - afterEach(function() { + afterEach(function () { alarmManagement.clean(); }); - describe('When a new alarm is raised', function() { - it('should add it to the list of risen alarms', function() { - var alarmList; - + describe('When a new alarm is raised', function () { + it('should add it to the list of risen alarms', function () { alarmManagement.raise('TEST_ALARM', 'Test description'); - alarmList = alarmManagement.list(); + const alarmList = alarmManagement.list(); - should.exist(alarmList['TEST_ALARM']); - alarmList['TEST_ALARM'].name.should.equal('TEST_ALARM'); - alarmList['TEST_ALARM'].description.should.equal('Test description'); + should.exist(alarmList.TEST_ALARM); + alarmList.TEST_ALARM.name.should.equal('TEST_ALARM'); + alarmList.TEST_ALARM.description.should.equal('Test description'); }); }); - describe('When a new alarm is raised multiple times', function() { - it('should only add it once to the risen alarms list', function() { - var alarmList; - + describe('When a new alarm is raised multiple times', function () { + it('should only add it once to the risen alarms list', function () { alarmManagement.raise('TEST_ALARM', 'Test description'); alarmManagement.raise('TEST_ALARM', 'Test description'); alarmManagement.raise('TEST_ALARM', 'Test description'); alarmManagement.raise('TEST_ALARM', 'Test description'); alarmManagement.raise('TEST_ALARM', 'Test description'); - alarmList = alarmManagement.list(); + const alarmList = alarmManagement.list(); Object.keys(alarmList).length.should.equal(1); }); }); - describe('When an alarm is released', function() { - beforeEach(function() { + describe('When an alarm is released', function () { + beforeEach(function () { alarmManagement.raise('TEST_ALARM1', 'Test description'); alarmManagement.raise('TEST_ALARM2', 'Test description'); alarmManagement.raise('TEST_ALARM3', 'Test description'); @@ -78,23 +71,23 @@ describe('Alarm management system', function() { alarmManagement.release('TEST_ALARM3'); }); - it('should disappear from the alarms list', function() { - var alarmList = alarmManagement.list(); + it('should disappear from the alarms list', function () { + const alarmList = alarmManagement.list(); - should.not.exist(alarmList['TEST_ALARM3']); + should.not.exist(alarmList.TEST_ALARM3); }); - it('should not affect other alarms', function() { - var alarmList = alarmManagement.list(); + it('should not affect other alarms', function () { + const alarmList = alarmManagement.list(); - should.exist(alarmList['TEST_ALARM1']); - should.exist(alarmList['TEST_ALARM2']); - should.exist(alarmList['TEST_ALARM4']); + should.exist(alarmList.TEST_ALARM1); + should.exist(alarmList.TEST_ALARM2); + should.exist(alarmList.TEST_ALARM4); }); }); - describe('When the alarm instrumentation function is used on a function', function() { - var interceptedFn; + describe('When the alarm instrumentation function is used on a function', function () { + let interceptedFn; function mockFunction(raiseError, callback) { if (raiseError) { @@ -104,34 +97,34 @@ describe('Alarm management system', function() { } } - beforeEach(function() { + beforeEach(function () { interceptedFn = alarmManagement.intercept('TEST_INTERCEPT', mockFunction); }); - it('should release the alarm if the function returns a non-error result', function(done) { + it('should release the alarm if the function returns a non-error result', function (done) { alarmManagement.raise('TEST_INTERCEPT', 'Test description'); - interceptedFn(false, function() { - var alarmList = alarmManagement.list(); + interceptedFn(false, function () { + const alarmList = alarmManagement.list(); - should.not.exist(alarmList['TEST_INTERCEPT']); + should.not.exist(alarmList.TEST_INTERCEPT); done(); }); }); - it('should raise the alarm if the funciton returns an error result', function(done) { - interceptedFn(true, function() { - var alarmList = alarmManagement.list(); + it('should raise the alarm if the funciton returns an error result', function (done) { + interceptedFn(true, function () { + const alarmList = alarmManagement.list(); - should.exist(alarmList['TEST_INTERCEPT']); + should.exist(alarmList.TEST_INTERCEPT); done(); }); }); }); - describe('When an instrumented function calls the callback with a null value', function() { - var interceptedFn; + describe('When an instrumented function calls the callback with a null value', function () { + let interceptedFn; function mockFunction(raiseError, callback) { if (raiseError) { @@ -141,15 +134,15 @@ describe('Alarm management system', function() { } } - beforeEach(function() { + beforeEach(function () { interceptedFn = alarmManagement.intercept('TEST_INTERCEPT', mockFunction); }); - it('should not raise the alarm', function(done) { - interceptedFn(false, function() { - var alarmList = alarmManagement.list(); + it('should not raise the alarm', function (done) { + interceptedFn(false, function () { + const alarmList = alarmManagement.list(); - should.not.exist(alarmList['TEST_INTERCEPT']); + should.not.exist(alarmList.TEST_INTERCEPT); done(); }); diff --git a/test/unit/general/config-multi-core-test.js b/test/unit/general/config-multi-core-test.js index 251fc3d30..f85ffe587 100644 --- a/test/unit/general/config-multi-core-test.js +++ b/test/unit/general/config-multi-core-test.js @@ -23,195 +23,203 @@ * Modified by: Fernando López - FIWARE Foundation, e.V. * */ -'use strict'; - -let config = require('../../../lib/commonConfig'), - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026', - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - attributes: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - } - }, - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M', - throttling: 'PT5S', - }; - - -describe('Startup Multi-Core tests', function() { - - describe('When the IoT Agent is started with Multi-Core environment variable with value \'true\'', function() { - beforeEach(function() { + +const config = require('../../../lib/commonConfig'); +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + attributes: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] + } + }, + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M', + throttling: 'PT5S' +}; + +describe('Startup Multi-Core tests', function () { + describe('When the IoT Agent is started with Multi-Core environment variable with value=true', function () { + beforeEach(function () { process.env.IOTA_MULTI_CORE = 'true'; iotAgentConfig.multiCore = false; }); - afterEach(function() { + afterEach(function () { delete process.env.IOTA_MULTI_CORE; }); - it('should load the correct configuration parameter with value \'true\'', function(done) { + it('should load the correct configuration parameter with value=true', function (done) { config.setConfig(iotAgentConfig); config.getConfig().multiCore.should.equal(true); done(); }); - }); - describe('When the IoT Agent is started with Multi-Core environment variable with value \'false\'', function() { - beforeEach(function() { + describe('When the IoT Agent is started with Multi-Core environment variable with value=false', function () { + beforeEach(function () { process.env.IOTA_MULTI_CORE = 'false'; iotAgentConfig.multiCore = true; }); - afterEach(function() { - delete process.env.IOTA_MULTI_CORE; - }); - - it('should load the correct configuration parameter with value \'false\'', function(done) { - config.setConfig(iotAgentConfig); - config.getConfig().multiCore.should.equal(false); - done(); - }); - }); - - - describe('When the IoT Agent is started with Multi-Core environment variable with any other value except ' + - '\'true\' or \'false\'', function() { - beforeEach(function() { - process.env.IOTA_MULTI_CORE = 'foo'; - iotAgentConfig.multiCore = true; - }); - - afterEach(function() { + afterEach(function () { delete process.env.IOTA_MULTI_CORE; }); - it('should load the correct configuration parameter with value \'false\'', function(done) { + it('should load the correct configuration parameter with value=false', function (done) { config.setConfig(iotAgentConfig); config.getConfig().multiCore.should.equal(false); done(); }); }); - describe('When the IoT Agent is started with Multi-Core environment variable with a numeric value', function() { - beforeEach(function() { + describe( + 'When the IoT Agent is started with Multi-Core environment variable with any other value except ' + + 'true or false', + function () { + beforeEach(function () { + process.env.IOTA_MULTI_CORE = 'foo'; + iotAgentConfig.multiCore = true; + }); + + afterEach(function () { + delete process.env.IOTA_MULTI_CORE; + }); + + it('should load the correct configuration parameter with value=false', function (done) { + config.setConfig(iotAgentConfig); + config.getConfig().multiCore.should.equal(false); + done(); + }); + } + ); + + describe('When the IoT Agent is started with Multi-Core environment variable with a numeric value', function () { + beforeEach(function () { process.env.IOTA_MULTI_CORE = 123; iotAgentConfig.multiCore = true; }); - afterEach(function() { - delete process.env.IOTA_MULTI_CORE; - }); - - it('should load the correct configuration parameter with value \'false\'', function(done) { - config.setConfig(iotAgentConfig); - config.getConfig().multiCore.should.equal(false); - done(); - }); - }); - - describe('When the IoT Agent is either started with Multi-Core environment variable nor it is ' + - 'configured', function() { - beforeEach(function() { - }); - - afterEach(function() { - delete process.env.IOTA_MULTI_CORE; - }); - - it('should load the correct configuration parameter with value \'false\'', function(done) { - config.setConfig(iotAgentConfig); - config.getConfig().multiCore.should.equal(false); - done(); - }); - }); - - describe('When the IoT Agent is not started with Multi-Core environment variable and it is configured with ' + - 'value \'true\'', function() { - beforeEach(function() { - iotAgentConfig.multiCore = true; - }); - - afterEach(function() { - delete process.env.IOTA_MULTI_CORE; - }); - - it('should load the correct configuration parameter with value \'true\'', function(done) { - config.setConfig(iotAgentConfig); - config.getConfig().multiCore.should.equal(true); - done(); - }); - }); - - describe('When the IoT Agent is not started with Multi-Core environment variable and it is configured with ' + - 'value \'false\'', function() { - beforeEach(function() { - iotAgentConfig.multiCore = false; - }); - - afterEach(function() { + afterEach(function () { delete process.env.IOTA_MULTI_CORE; }); - it('should load the correct configuration parameter with value \'false\'', function(done) { + it('should load the correct configuration parameter with value=false', function (done) { config.setConfig(iotAgentConfig); config.getConfig().multiCore.should.equal(false); done(); }); }); - describe('When the IoT Agent is not started with Multi-Core environment variable and it is configured with ' + - 'any other value except \'true\' or \'false\'', function() { - beforeEach(function() { - iotAgentConfig.multiCore = 'foo'; - }); + describe('When the IoT Agent is either started with Multi-Core environment variable nor it is configured', function () { + beforeEach(function () {}); - afterEach(function() { + afterEach(function () { delete process.env.IOTA_MULTI_CORE; }); - it('should load the correct configuration parameter with value \'false\'', function(done) { + it('should load the correct configuration parameter with value=false', function (done) { config.setConfig(iotAgentConfig); config.getConfig().multiCore.should.equal(false); done(); }); }); - describe('When the IoT Agent is not started with Multi-Core environment variable and it is configured with ' + - 'a numeric value', function() { - beforeEach(function() { - iotAgentConfig.multiCore = 123; - }); - - afterEach(function() { - delete process.env.IOTA_MULTI_CORE; - }); - it('should load the correct configuration parameter with value \'false\'', function(done) { - config.setConfig(iotAgentConfig); - config.getConfig().multiCore.should.equal(false); - done(); - }); - }); + describe( + 'When the IoT Agent is not started with Multi-Core environment variable and it is configured with ' + + 'value=true', + function () { + beforeEach(function () { + iotAgentConfig.multiCore = true; + }); + + afterEach(function () { + delete process.env.IOTA_MULTI_CORE; + }); + + it('should load the correct configuration parameter with value=true', function (done) { + config.setConfig(iotAgentConfig); + config.getConfig().multiCore.should.equal(true); + done(); + }); + } + ); + + describe( + 'When the IoT Agent is not started with Multi-Core environment variable and it is configured with ' + + 'value=false', + function () { + beforeEach(function () { + iotAgentConfig.multiCore = false; + }); + + afterEach(function () { + delete process.env.IOTA_MULTI_CORE; + }); + + it('should load the correct configuration parameter with value=false', function (done) { + config.setConfig(iotAgentConfig); + config.getConfig().multiCore.should.equal(false); + done(); + }); + } + ); + + describe( + 'When the IoT Agent is not started with Multi-Core environment variable and it is configured with ' + + 'any other value except true or false', + function () { + beforeEach(function () { + iotAgentConfig.multiCore = 'foo'; + }); + + afterEach(function () { + delete process.env.IOTA_MULTI_CORE; + }); + + it('should load the correct configuration parameter with value=false', function (done) { + config.setConfig(iotAgentConfig); + config.getConfig().multiCore.should.equal(false); + done(); + }); + } + ); + + describe( + 'When the IoT Agent is not started with Multi-Core environment variable and it is configured with ' + + 'a numeric value', + function () { + beforeEach(function () { + iotAgentConfig.multiCore = 123; + }); + + afterEach(function () { + delete process.env.IOTA_MULTI_CORE; + }); + it('should load the correct configuration parameter with value=false', function (done) { + config.setConfig(iotAgentConfig); + config.getConfig().multiCore.should.equal(false); + done(); + }); + } + ); }); diff --git a/test/unit/general/contextBrokerKeystoneSecurityAccess-test.js b/test/unit/general/contextBrokerKeystoneSecurityAccess-test.js index ddfca1bf3..9d2a05aa9 100644 --- a/test/unit/general/contextBrokerKeystoneSecurityAccess-test.js +++ b/test/unit/general/contextBrokerKeystoneSecurityAccess-test.js @@ -20,75 +20,75 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - request = require('request'), - contextBrokerMock, - keystoneMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 - }, - authentication: { - // Next line is syntactically correct from a configuration point of - // view, but we comment it in order to ensure backward compability - // type: keystone, - host: '128.16.109.11', - port: '5000', - user: 'iotagent', - password: 'iotagent', - enabled: true - }, - types: { - 'Light': { - service: 'smartGondor', - subservice: 'electricity', - trust: 'BBBB987654321', - type: 'Light', - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'Termometer': { - commands: [], - type: 'Termometer', - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ] - } + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +const request = require('request'); +let contextBrokerMock; +let keystoneMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + authentication: { + // Next line is syntactically correct from a configuration point of + // view, but we comment it in order to ensure backward compability + // type: keystone, + host: '128.16.109.11', + port: '5000', + user: 'iotagent', + password: 'iotagent', + enabled: true + }, + types: { + Light: { + service: 'smartGondor', + subservice: 'electricity', + trust: 'BBBB987654321', + type: 'Light', + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }; - -describe('NGSI-v1 - Secured access to the Context Broker with Keystone', function() { - var values = [ + Termometer: { + commands: [], + type: 'Termometer', + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; + +describe('NGSI-v1 - Secured access to the Context Broker with Keystone', function () { + const values = [ { name: 'state', type: 'Boolean', @@ -101,68 +101,66 @@ describe('NGSI-v1 - Secured access to the Context Broker with Keystone', functio } ]; - beforeEach(function() { + beforeEach(function () { logger.setLevel('FATAL'); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); nock.cleanAll(); }); - describe('When a measure is sent to the Context Broker via an Update Context operation', function() { - beforeEach(function(done) { + describe('When a measure is sent to the Context Broker via an Update Context operation', function () { + beforeEach(function (done) { nock.cleanAll(); keystoneMock = nock('http://128.16.109.11:5000') - .post('/v3/auth/tokens', - utils.readExampleFile('./test/unit/examples/keystoneRequests/getTokenFromTrust.json')) - .reply( - 201, - utils.readExampleFile('./test/unit/examples/keystoneResponses/tokenFromTrust.json'), - { - 'X-Subject-Token': '12345679ABCDEF' - }); + .post( + '/v3/auth/tokens', + utils.readExampleFile('./test/unit/examples/keystoneRequests/getTokenFromTrust.json') + ) + .reply(201, utils.readExampleFile('./test/unit/examples/keystoneResponses/tokenFromTrust.json'), { + 'X-Subject-Token': '12345679ABCDEF' + }); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'electricity') .matchHeader('X-Auth-Token', '12345679ABCDEF') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json')) - .reply( - 200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); iotAgentLib.activate(iotAgentConfig, done); }); - it('should ask Keystone for a token based on the trust token', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should ask Keystone for a token based on the trust token', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); keystoneMock.done(); done(); }); }); - it('should send the generated token in the x-auth header', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should send the generated token in the x-auth header', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - describe('When a measure is sent to the Context Broker and the access is forbidden', function() { - beforeEach(function(done) { + describe('When a measure is sent to the Context Broker and the access is forbidden', function () { + beforeEach(function (done) { nock.cleanAll(); keystoneMock = nock('http://128.16.109.11:5000') - .post('/v3/auth/tokens', - utils.readExampleFile('./test/unit/examples/keystoneRequests/getTokenFromTrust.json')) - .reply( - 201, - utils.readExampleFile('./test/unit/examples/keystoneResponses/tokenFromTrust.json'), - { + .post( + '/v3/auth/tokens', + utils.readExampleFile('./test/unit/examples/keystoneRequests/getTokenFromTrust.json') + ) + .reply(201, utils.readExampleFile('./test/unit/examples/keystoneResponses/tokenFromTrust.json'), { 'X-Subject-Token': '12345679ABCDEF' }); @@ -170,49 +168,52 @@ describe('NGSI-v1 - Secured access to the Context Broker with Keystone', functio .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'electricity') .matchHeader('X-Auth-Token', '12345679ABCDEF') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json')) - .reply( - 403, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json') + ) + .reply(403, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); iotAgentLib.activate(iotAgentConfig, done); }); - it('it should return a ACCESS_FORBIDDEN error to the caller', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('it should return a ACCESS_FORBIDDEN error to the caller', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.exist(error); error.name.should.equal('ACCESS_FORBIDDEN'); done(); }); }); }); - describe('When a measure is sent and the trust is rejected asking for the token', function() { - beforeEach(function(done) { + describe('When a measure is sent and the trust is rejected asking for the token', function () { + beforeEach(function (done) { nock.cleanAll(); keystoneMock = nock('http://128.16.109.11:5000') - .post('/v3/auth/tokens', - utils.readExampleFile('./test/unit/examples/keystoneRequests/getTokenFromTrust.json')) + .post( + '/v3/auth/tokens', + utils.readExampleFile('./test/unit/examples/keystoneRequests/getTokenFromTrust.json') + ) .reply( - 401, - utils.readExampleFile('./test/unit/examples/keystoneResponses/tokenFromTrustUnauthorized.json')); + 401, + utils.readExampleFile('./test/unit/examples/keystoneResponses/tokenFromTrustUnauthorized.json') + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'electricity') .matchHeader('X-Auth-Token', '12345679ABCDEF') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json')) - .reply( - 200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); iotAgentLib.activate(iotAgentConfig, done); }); - it('it should return a AUTHENTICATION_ERROR error to the caller', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('it should return a AUTHENTICATION_ERROR error to the caller', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.exist(error); error.name.should.equal('AUTHENTICATION_ERROR'); done(); @@ -220,22 +221,18 @@ describe('NGSI-v1 - Secured access to the Context Broker with Keystone', functio }); }); - describe('When the user requests information about a device in a protected CB', function() { - var attributes = [ - 'state', - 'dimming' - ]; + describe('When the user requests information about a device in a protected CB', function () { + const attributes = ['state', 'dimming']; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); keystoneMock = nock('http://128.16.109.11:5000') - .post('/v3/auth/tokens', - utils.readExampleFile('./test/unit/examples/keystoneRequests/getTokenFromTrust.json')) - .reply( - 201, - utils.readExampleFile('./test/unit/examples/keystoneResponses/tokenFromTrust.json'), - { + .post( + '/v3/auth/tokens', + utils.readExampleFile('./test/unit/examples/keystoneRequests/getTokenFromTrust.json') + ) + .reply(201, utils.readExampleFile('./test/unit/examples/keystoneResponses/tokenFromTrust.json'), { 'X-Subject-Token': '12345679ABCDEF' }); @@ -243,16 +240,17 @@ describe('NGSI-v1 - Secured access to the Context Broker with Keystone', functio .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'electricity') .matchHeader('X-Auth-Token', '12345679ABCDEF') - .post('/v1/queryContext', - utils.readExampleFile('./test/unit/examples/contextRequests/queryContext1.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/queryContext1Success.json')); + .post( + '/v1/queryContext', + utils.readExampleFile('./test/unit/examples/contextRequests/queryContext1.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/queryContext1Success.json')); iotAgentLib.activate(iotAgentConfig, done); }); - it('should send the Auth Token along with the information query', function(done) { - iotAgentLib.query('light1', 'Light', '', attributes, function(error) { + it('should send the Auth Token along with the information query', function (done) { + iotAgentLib.query('light1', 'Light', '', attributes, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -260,76 +258,88 @@ describe('NGSI-v1 - Secured access to the Context Broker with Keystone', functio }); }); - describe('When subscriptions are used on a protected Context Broker', function() { - beforeEach(function(done) { - - var optionsProvision = { + describe('When subscriptions are used on a protected Context Broker', function () { + beforeEach(function (done) { + const optionsProvision = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice3.json'), + './test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice3.json' + ), headers: { 'fiware-service': 'smartGondor', 'fiware-servicepath': 'electricity' } }; - + nock.cleanAll(); - - iotAgentLib.activate(iotAgentConfig, function() { + + iotAgentLib.activate(iotAgentConfig, function () { keystoneMock = nock('http://128.16.109.11:5000') - .post('/v3/auth/tokens', - utils.readExampleFile( - './test/unit/examples/keystoneRequests/getTokenFromTrust.json')) + .post( + '/v3/auth/tokens', + utils.readExampleFile('./test/unit/examples/keystoneRequests/getTokenFromTrust.json') + ) .times(3) - .reply( - 201, - utils.readExampleFile('./test/unit/examples/keystoneResponses/tokenFromTrust.json'), - { + .reply(201, utils.readExampleFile('./test/unit/examples/keystoneResponses/tokenFromTrust.json'), { 'X-Subject-Token': '12345679ABCDEF' }); - contextBrokerMock = nock('http://192.168.1.1:1026'); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'electricity') .matchHeader('X-Auth-Token', '12345679ABCDEF') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext5.json')) + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext5.json') + ) .reply( - 200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json') + ); contextBrokerMock - .post('/NGSI9/registerContext', - utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerNewDevice1.json')) + .post( + '/NGSI9/registerContext', + utils.readExampleFile( + './test/unit/examples/contextAvailabilityRequests/registerNewDevice1.json' + ) + ) .reply( - 200, - utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerNewDevice1Success.json')); + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerNewDevice1Success.json' + ) + ); contextBrokerMock - .post('/v1/subscribeContext', + .post( + '/v1/subscribeContext', utils.readExampleFile( - './test/unit/examples/subscriptionRequests/simpleSubscriptionRequest1.json')) + './test/unit/examples/subscriptionRequests/simpleSubscriptionRequest1.json' + ) + ) .matchHeader('X-Auth-Token', '12345679ABCDEF') - .reply(200, + .reply( + 200, utils.readExampleFile( - './test/unit/examples/subscriptionResponses/simpleSubscriptionSuccess.json')); - - iotAgentLib.clearAll(function() { - request(optionsProvision, function(error, result, body) { + './test/unit/examples/subscriptionResponses/simpleSubscriptionSuccess.json' + ) + ); + + iotAgentLib.clearAll(function () { + request(optionsProvision, function (error, result, body) { done(); }); }); }); }); - it('subscribe requests use auth header', function(done) { - iotAgentLib.getDevice('Light1', 'smartGondor', 'electricity', function(error, device) { - iotAgentLib.subscribe(device, ['dimming'], null, function(error) { + it('subscribe requests use auth header', function (done) { + iotAgentLib.getDevice('Light1', 'smartGondor', 'electricity', function (error, device) { + iotAgentLib.subscribe(device, ['dimming'], null, function (error) { should.not.exist(error); contextBrokerMock.done(); @@ -339,34 +349,35 @@ describe('NGSI-v1 - Secured access to the Context Broker with Keystone', functio }); }); - it('unsubscribe requests use auth header', function(done) { - - keystoneMock - .post('/v3/auth/tokens', - utils.readExampleFile('./test/unit/examples/keystoneRequests/getTokenFromTrust.json')) - .reply( - 201, - utils.readExampleFile('./test/unit/examples/keystoneResponses/tokenFromTrust.json'), - { - 'X-Subject-Token': '12345679ABCDEF' - }); - - contextBrokerMock = nock('http://192.168.1.1:1026') - .post('/v1/unsubscribeContext', - utils.readExampleFile('./test/unit/examples/subscriptionRequests/simpleSubscriptionRemove.json')) - .matchHeader('X-Auth-Token', '12345679ABCDEF') - .reply(200, - utils.readExampleFile('./test/unit/examples/subscriptionResponses/simpleSubscriptionSuccess.json')); - - iotAgentLib.getDevice('Light1', 'smartGondor', 'electricity', function(error, device) { - iotAgentLib.subscribe(device, ['dimming'], null, function(error) { - iotAgentLib.unsubscribe(device, '51c0ac9ed714fb3b37d7d5a8', function(error) { + it('unsubscribe requests use auth header', function (done) { + keystoneMock + .post( + '/v3/auth/tokens', + utils.readExampleFile('./test/unit/examples/keystoneRequests/getTokenFromTrust.json') + ) + .reply(201, utils.readExampleFile('./test/unit/examples/keystoneResponses/tokenFromTrust.json'), { + 'X-Subject-Token': '12345679ABCDEF' + }); + + contextBrokerMock = nock('http://192.168.1.1:1026') + .post( + '/v1/unsubscribeContext', + utils.readExampleFile('./test/unit/examples/subscriptionRequests/simpleSubscriptionRemove.json') + ) + .matchHeader('X-Auth-Token', '12345679ABCDEF') + .reply( + 200, + utils.readExampleFile('./test/unit/examples/subscriptionResponses/simpleSubscriptionSuccess.json') + ); + + iotAgentLib.getDevice('Light1', 'smartGondor', 'electricity', function (error, device) { + iotAgentLib.subscribe(device, ['dimming'], null, function (error) { + iotAgentLib.unsubscribe(device, '51c0ac9ed714fb3b37d7d5a8', function (error) { contextBrokerMock.done(); done(); }); }); }); }); - }); }); diff --git a/test/unit/general/contextBrokerOAuthSecurityAccess-test.js b/test/unit/general/contextBrokerOAuthSecurityAccess-test.js index 59d2bf191..d73733bcb 100644 --- a/test/unit/general/contextBrokerOAuthSecurityAccess-test.js +++ b/test/unit/general/contextBrokerOAuthSecurityAccess-test.js @@ -22,74 +22,74 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - request = require('request'), - contextBrokerMock, - oauth2Mock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 - }, - authentication: { - type: 'oauth2', - url: 'http://192.168.1.1:3000', - header: 'Authorization', - clientId: 'context-broker', - clientSecret: 'c8d58d16-0a42-400e-9765-f32e154a5a9e', - tokenPath: '/auth/realms/default/protocol/openid-connect/token', - enabled: true - }, - types: { - 'Light': { - service: 'smartGondor', - subservice: 'electricity', - trust: 'eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3cHdWclJ3', - type: 'Light', - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'Termometer': { - commands: [], - type: 'Termometer', - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ] - } + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +const request = require('request'); +let contextBrokerMock; +let oauth2Mock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + authentication: { + type: 'oauth2', + url: 'http://192.168.1.1:3000', + header: 'Authorization', + clientId: 'context-broker', + clientSecret: 'c8d58d16-0a42-400e-9765-f32e154a5a9e', + tokenPath: '/auth/realms/default/protocol/openid-connect/token', + enabled: true + }, + types: { + Light: { + service: 'smartGondor', + subservice: 'electricity', + trust: 'eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3cHdWclJ3', + type: 'Light', + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }; - -describe('NGSI-v1 - Secured access to the Context Broker with OAuth2 provider', function() { - var values = [ + Termometer: { + commands: [], + type: 'Termometer', + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; + +describe('NGSI-v1 - Secured access to the Context Broker with OAuth2 provider', function () { + const values = [ { name: 'state', type: 'Boolean', @@ -102,114 +102,115 @@ describe('NGSI-v1 - Secured access to the Context Broker with OAuth2 provider', } ]; - beforeEach(function() { + beforeEach(function () { logger.setLevel('FATAL'); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); nock.cleanAll(); }); - describe('When a measure is sent to the Context Broker via an Update Context operation', function() { - beforeEach(function(done) { + describe('When a measure is sent to the Context Broker via an Update Context operation', function () { + beforeEach(function (done) { nock.cleanAll(); oauth2Mock = nock('http://192.168.1.1:3000') - .post('/auth/realms/default/protocol/openid-connect/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) - .reply( - 201, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrust.json'), - {}); + .post( + '/auth/realms/default/protocol/openid-connect/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) + .reply(201, utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrust.json'), {}); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'electricity') .matchHeader('Authorization', 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3cHdWclJ3') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json')) - .reply( - 200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); iotAgentLib.activate(iotAgentConfig, done); }); - it('should ask OAuth2 provider for a token based on the trust token', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should ask OAuth2 provider for a token based on the trust token', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); oauth2Mock.done(); done(); }); }); - it('should send the generated token in the auth header', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should send the generated token in the auth header', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - describe('When a measure is sent to the Context Broker and the access is forbidden', function() { - beforeEach(function(done) { + describe('When a measure is sent to the Context Broker and the access is forbidden', function () { + beforeEach(function (done) { nock.cleanAll(); oauth2Mock = nock('http://192.168.1.1:3000') - .post('/auth/realms/default/protocol/openid-connect/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) - .reply( - 201, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrust.json'), - {}); + .post( + '/auth/realms/default/protocol/openid-connect/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) + .reply(201, utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrust.json'), {}); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'electricity') .matchHeader('Authorization', 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3cHdWclJ3') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json')) - .reply( - 403, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json') + ) + .reply(403, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); iotAgentLib.activate(iotAgentConfig, done); }); - it('it should return a ACCESS_FORBIDDEN error to the caller', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('it should return a ACCESS_FORBIDDEN error to the caller', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.exist(error); error.name.should.equal('ACCESS_FORBIDDEN'); done(); }); }); }); - describe('When a measure is sent and the trust is rejected asking for the token', function() { - beforeEach(function(done) { + describe('When a measure is sent and the trust is rejected asking for the token', function () { + beforeEach(function (done) { nock.cleanAll(); - oauth2Mock = nock('http://192.168.1.1:3000') - .post('/auth/realms/default/protocol/openid-connect/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) + oauth2Mock = nock('http://192.168.1.1:3000') + .post( + '/auth/realms/default/protocol/openid-connect/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) .reply( - 400, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustUnauthorized.json')); + 400, + utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustUnauthorized.json') + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'electricity') .matchHeader('Authorization', 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3cHdWclJ3') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json')) - .reply( - 200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); iotAgentLib.activate(iotAgentConfig, done); }); - it('it should return a AUTHENTICATION_ERROR error to the caller', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('it should return a AUTHENTICATION_ERROR error to the caller', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.exist(error); error.name.should.equal('AUTHENTICATION_ERROR'); done(); @@ -217,37 +218,34 @@ describe('NGSI-v1 - Secured access to the Context Broker with OAuth2 provider', }); }); - describe('When the user requests information about a device in a protected CB', function() { - var attributes = [ - 'state', - 'dimming' - ]; + describe('When the user requests information about a device in a protected CB', function () { + const attributes = ['state', 'dimming']; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); oauth2Mock = nock('http://192.168.1.1:3000') - .post('/auth/realms/default/protocol/openid-connect/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) - .reply( - 201, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrust.json'), - {}); + .post( + '/auth/realms/default/protocol/openid-connect/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) + .reply(201, utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrust.json'), {}); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'electricity') .matchHeader('Authorization', 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3cHdWclJ3') - .post('/v1/queryContext', - utils.readExampleFile('./test/unit/examples/contextRequests/queryContext1.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/queryContext1Success.json')); + .post( + '/v1/queryContext', + utils.readExampleFile('./test/unit/examples/contextRequests/queryContext1.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/queryContext1Success.json')); iotAgentLib.activate(iotAgentConfig, done); }); - it('should send the Auth Token along with the information query', function(done) { - iotAgentLib.query('light1', 'Light', '', attributes, function(error) { + it('should send the Auth Token along with the information query', function (done) { + iotAgentLib.query('light1', 'Light', '', attributes, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -255,32 +253,30 @@ describe('NGSI-v1 - Secured access to the Context Broker with OAuth2 provider', }); }); - describe('When subscriptions are used on a protected Context Broker', function() { - beforeEach(function(done) { - - var optionsProvision = { + describe('When subscriptions are used on a protected Context Broker', function () { + beforeEach(function (done) { + const optionsProvision = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice3.json'), + './test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice3.json' + ), headers: { 'fiware-service': 'smartGondor', 'fiware-servicepath': 'electricity' } }; - + nock.cleanAll(); - - iotAgentLib.activate(iotAgentConfig, function() { + + iotAgentLib.activate(iotAgentConfig, function () { oauth2Mock = nock('http://192.168.1.1:3000') - .post('/auth/realms/default/protocol/openid-connect/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) + .post( + '/auth/realms/default/protocol/openid-connect/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) .times(3) - .reply( - 201, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrust.json'), - {}); - + .reply(201, utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrust.json'), {}); contextBrokerMock = nock('http://192.168.1.1:1026'); @@ -288,41 +284,55 @@ describe('NGSI-v1 - Secured access to the Context Broker with OAuth2 provider', .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'electricity') .matchHeader('Authorization', 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3cHdWclJ3') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext5.json')) + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext5.json') + ) .reply( - 200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json') + ); contextBrokerMock - .post('/NGSI9/registerContext', - utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerNewDevice1.json')) + .post( + '/NGSI9/registerContext', + utils.readExampleFile( + './test/unit/examples/contextAvailabilityRequests/registerNewDevice1.json' + ) + ) .reply( - 200, - utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerNewDevice1Success.json')); + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerNewDevice1Success.json' + ) + ); contextBrokerMock - .post('/v1/subscribeContext', + .post( + '/v1/subscribeContext', utils.readExampleFile( - './test/unit/examples/subscriptionRequests/simpleSubscriptionRequest1.json')) + './test/unit/examples/subscriptionRequests/simpleSubscriptionRequest1.json' + ) + ) .matchHeader('Authorization', 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3cHdWclJ3') - .reply(200, + .reply( + 200, utils.readExampleFile( - './test/unit/examples/subscriptionResponses/simpleSubscriptionSuccess.json')); - - iotAgentLib.clearAll(function() { - request(optionsProvision, function(error, result, body) { + './test/unit/examples/subscriptionResponses/simpleSubscriptionSuccess.json' + ) + ); + + iotAgentLib.clearAll(function () { + request(optionsProvision, function (error, result, body) { done(); }); }); }); }); - it('subscribe requests use auth header', function(done) { - iotAgentLib.getDevice('Light1', 'smartGondor', 'electricity', function(error, device) { - iotAgentLib.subscribe(device, ['dimming'], null, function(error) { + it('subscribe requests use auth header', function (done) { + iotAgentLib.getDevice('Light1', 'smartGondor', 'electricity', function (error, device) { + iotAgentLib.subscribe(device, ['dimming'], null, function (error) { should.not.exist(error); contextBrokerMock.done(); @@ -332,39 +342,39 @@ describe('NGSI-v1 - Secured access to the Context Broker with OAuth2 provider', }); }); - it('unsubscribe requests use auth header', function(done) { - - oauth2Mock - .post('/auth/realms/default/protocol/openid-connect/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) - .reply( - 201, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrust.json'), - {}); - - contextBrokerMock = nock('http://192.168.1.1:1026') - .post('/v1/unsubscribeContext', - utils.readExampleFile('./test/unit/examples/subscriptionRequests/simpleSubscriptionRemove.json')) - .matchHeader('Authorization', 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3cHdWclJ3') - .reply(200, - utils.readExampleFile('./test/unit/examples/subscriptionResponses/simpleSubscriptionSuccess.json')); - - iotAgentLib.getDevice('Light1', 'smartGondor', 'electricity', function(error, device) { - iotAgentLib.subscribe(device, ['dimming'], null, function(error) { - iotAgentLib.unsubscribe(device, '51c0ac9ed714fb3b37d7d5a8', function(error) { + it('unsubscribe requests use auth header', function (done) { + oauth2Mock + .post( + '/auth/realms/default/protocol/openid-connect/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) + .reply(201, utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrust.json'), {}); + + contextBrokerMock = nock('http://192.168.1.1:1026') + .post( + '/v1/unsubscribeContext', + utils.readExampleFile('./test/unit/examples/subscriptionRequests/simpleSubscriptionRemove.json') + ) + .matchHeader('Authorization', 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3cHdWclJ3') + .reply( + 200, + utils.readExampleFile('./test/unit/examples/subscriptionResponses/simpleSubscriptionSuccess.json') + ); + + iotAgentLib.getDevice('Light1', 'smartGondor', 'electricity', function (error, device) { + iotAgentLib.subscribe(device, ['dimming'], null, function (error) { + iotAgentLib.unsubscribe(device, '51c0ac9ed714fb3b37d7d5a8', function (error) { contextBrokerMock.done(); done(); }); }); }); }); - }); }); -describe('Secured access to the Context Broker with OAuth2 provider (FIWARE Keyrock IDM)', function() { - - var values = [ +describe('Secured access to the Context Broker with OAuth2 provider (FIWARE Keyrock IDM)', function () { + const values = [ { name: 'state', type: 'Boolean', @@ -377,50 +387,53 @@ describe('Secured access to the Context Broker with OAuth2 provider (FIWARE Keyr } ]; - beforeEach(function() { + beforeEach(function () { logger.setLevel('FATAL'); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); nock.cleanAll(); }); - describe('When a measure is sent to the Context Broker via an Update Context operation', function() { - beforeEach(function(done) { + describe('When a measure is sent to the Context Broker via an Update Context operation', function () { + beforeEach(function (done) { nock.cleanAll(); oauth2Mock = nock('http://192.168.1.1:3000') - .post('/oauth2/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) + .post( + '/oauth2/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) .reply( 200, utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock.json'), - {}); + {} + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'electricity') .matchHeader('Authorization', 'Bearer c1b752e377680acd1349a3ed59db855a1db07605') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json')) - .reply( - 200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); iotAgentConfig.authentication.tokenPath = '/oauth2/token'; iotAgentLib.activate(iotAgentConfig, done); }); - it('should ask OAuth2 provider for a token based on the trust token', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should ask OAuth2 provider for a token based on the trust token', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); oauth2Mock.done(); done(); }); }); - it('should send the generated token in the auth header', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should send the generated token in the auth header', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -428,37 +441,38 @@ describe('Secured access to the Context Broker with OAuth2 provider (FIWARE Keyr }); }); - describe('When the user requests information about a device in a protected CB', function() { - var attributes = [ - 'state', - 'dimming' - ]; + describe('When the user requests information about a device in a protected CB', function () { + const attributes = ['state', 'dimming']; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); oauth2Mock = nock('http://192.168.1.1:3000') - .post('/oauth2/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) + .post( + '/oauth2/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) .reply( 200, utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock.json'), - {}); + {} + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'electricity') .matchHeader('Authorization', 'Bearer c1b752e377680acd1349a3ed59db855a1db07605') - .post('/v1/queryContext', - utils.readExampleFile('./test/unit/examples/contextRequests/queryContext1.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/queryContext1Success.json')); + .post( + '/v1/queryContext', + utils.readExampleFile('./test/unit/examples/contextRequests/queryContext1.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/queryContext1Success.json')); iotAgentLib.activate(iotAgentConfig, done); }); - it('should send the Auth Token along with the information query', function(done) { - iotAgentLib.query('light1', 'Light', '', attributes, function(error) { + it('should send the Auth Token along with the information query', function (done) { + iotAgentLib.query('light1', 'Light', '', attributes, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -466,22 +480,25 @@ describe('Secured access to the Context Broker with OAuth2 provider (FIWARE Keyr }); }); - describe('When a measure is sent and the refresh token is not valid', function() { - beforeEach(function(done) { + describe('When a measure is sent and the refresh token is not valid', function () { + beforeEach(function (done) { nock.cleanAll(); oauth2Mock = nock('http://192.168.1.1:3000') - .post('/oauth2/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) + .post( + '/oauth2/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) .reply( - 400, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustUnauthorizedKeyrock.json')); + 400, + utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustUnauthorizedKeyrock.json') + ); iotAgentLib.activate(iotAgentConfig, done); }); - it('it should return a AUTHENTICATION_ERROR error to the caller', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('it should return a AUTHENTICATION_ERROR error to the caller', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.exist(error); error.name.should.equal('AUTHENTICATION_ERROR'); done(); @@ -489,23 +506,28 @@ describe('Secured access to the Context Broker with OAuth2 provider (FIWARE Keyr }); }); - describe('When a measure is sent to the Context Broker and the client credentials are invalid', function() { - beforeEach(function(done) { + describe('When a measure is sent to the Context Broker and the client credentials are invalid', function () { + beforeEach(function (done) { nock.cleanAll(); oauth2Mock = nock('http://192.168.1.1:3000') - .post('/oauth2/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) + .post( + '/oauth2/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) .reply( - 400, - utils.readExampleFile('./test/unit/examples/oauthResponses/' + - 'tokenFromTrustInvalidCredentialsKeyrock.json'), {}); + 400, + utils.readExampleFile( + './test/unit/examples/oauthResponses/tokenFromTrustInvalidCredentialsKeyrock.json' + ), + {} + ); iotAgentLib.activate(iotAgentConfig, done); }); - it('it should return a AUTHENTICATION_ERROR error to the caller', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('it should return a AUTHENTICATION_ERROR error to the caller', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.exist(error); error.name.should.equal('AUTHENTICATION_ERROR'); done(); @@ -513,33 +535,36 @@ describe('Secured access to the Context Broker with OAuth2 provider (FIWARE Keyr }); }); - describe('When a measure is sent to the Context Broker and the access is unauthorized', function() { - beforeEach(function(done) { + describe('When a measure is sent to the Context Broker and the access is unauthorized', function () { + beforeEach(function (done) { nock.cleanAll(); oauth2Mock = nock('http://192.168.1.1:3000') - .post('/oauth2/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) + .post( + '/oauth2/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) .reply( 200, utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock.json'), - {}); + {} + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'electricity') .matchHeader('Authorization', 'Bearer c1b752e377680acd1349a3ed59db855a1db07605') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json')) - .reply( - 401, - 'Auth-token not found in request header'); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json') + ) + .reply(401, 'Auth-token not found in request header'); iotAgentLib.activate(iotAgentConfig, done); }); - it('it should return a ACCESS_FORBIDDEN error to the caller', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('it should return a ACCESS_FORBIDDEN error to the caller', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.exist(error); error.name.should.equal('ACCESS_FORBIDDEN'); done(); @@ -548,266 +573,330 @@ describe('Secured access to the Context Broker with OAuth2 provider (FIWARE Keyr }); }); -describe('Secured access to the Context Broker with OAuth2 provider (FIWARE Keyrock IDM)' + - 'configured through group provisioning', function() { - var groupCreation = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionFullGroup.json'), - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - } - }; - - var values = [ - { - name: 'status', - type: 'String', - value: 'STARTING' - } - ]; +describe( + 'Secured access to the Context Broker with OAuth2 provider (FIWARE Keyrock IDM)' + + 'configured through group provisioning', + function () { + const groupCreation = { + url: 'http://localhost:4041/iot/services', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionFullGroup.json'), + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } + }; - beforeEach(function() { - logger.setLevel('FATAL'); - }); + const values = [ + { + name: 'status', + type: 'String', + value: 'STARTING' + } + ]; - afterEach(function(done) { - iotAgentLib.deactivate(done); - nock.cleanAll(); - }); + beforeEach(function () { + logger.setLevel('FATAL'); + }); - describe('When a measure is sent to the Context Broker via an Update Context operation', function() { - var oauth2Mock2; - var contextBrokerMock2; - beforeEach(function(done) { + afterEach(function (done) { + iotAgentLib.deactivate(done); nock.cleanAll(); - oauth2Mock = nock('http://192.168.1.1:3000') - .post('/oauth2/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrustKeyrockGroup.json', true)) - .reply( - 200, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock.json'), - {}); + }); - oauth2Mock2 = nock('http://192.168.1.1:3000') - .post('/oauth2/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrustKeyrockGroup2.json', true)) - .reply( - 200, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock2.json'), - {}); + describe('When a measure is sent to the Context Broker via an Update Context operation', function () { + let oauth2Mock2; + let contextBrokerMock2; + beforeEach(function (done) { + nock.cleanAll(); + oauth2Mock = nock('http://192.168.1.1:3000') + .post( + '/oauth2/token', + utils.readExampleFile( + './test/unit/examples/oauthRequests/getTokenFromTrustKeyrockGroup.json', + true + ) + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock.json'), + {} + ); + + oauth2Mock2 = nock('http://192.168.1.1:3000') + .post( + '/oauth2/token', + utils.readExampleFile( + './test/unit/examples/oauthRequests/getTokenFromTrustKeyrockGroup2.json', + true + ) + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock2.json'), + {} + ); + + contextBrokerMock = nock('http://unexistentHost:1026') + .matchHeader('fiware-service', 'TestService') + .matchHeader('fiware-servicepath', '/testingPath') + .matchHeader('Authorization', 'Bearer c1b752e377680acd1349a3ed59db855a1db07605') + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext3WithStatic.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json') + ); + + contextBrokerMock2 = nock('http://unexistentHost:1026') + .matchHeader('fiware-service', 'TestService') + .matchHeader('fiware-servicepath', '/testingPath') + .matchHeader('Authorization', 'Bearer bbb752e377680acd1349a3ed59db855a1db076aa') + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext3WithStatic.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json') + ); + iotAgentConfig.authentication.tokenPath = '/oauth2/token'; + iotAgentLib.activate(iotAgentConfig, function () { + request(groupCreation, function (error, response, body) { + done(); + }); + }); + }); + it( + 'should ask OAuth2 provider for a token based on the' + + 'trust token and send the generated token in the auth header', + function (done) { + iotAgentLib.update('machine1', 'SensorMachine', '', values, function (error) { + should.not.exist(error); + oauth2Mock.done(); + contextBrokerMock.done(); + done(); + }); + } + ); - contextBrokerMock = nock('http://unexistentHost:1026') - .matchHeader('fiware-service', 'TestService') - .matchHeader('fiware-servicepath', '/testingPath') - .matchHeader('Authorization', 'Bearer c1b752e377680acd1349a3ed59db855a1db07605') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext3WithStatic.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); - - contextBrokerMock2 = nock('http://unexistentHost:1026') - .matchHeader('fiware-service', 'TestService') - .matchHeader('fiware-servicepath', '/testingPath') - .matchHeader('Authorization', 'Bearer bbb752e377680acd1349a3ed59db855a1db076aa') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext3WithStatic.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); - iotAgentConfig.authentication.tokenPath = '/oauth2/token'; - iotAgentLib.activate(iotAgentConfig, function() { - request(groupCreation, function(error, response, body) { + it('should use the updated trust token in the following requests', function (done) { + iotAgentLib.update('machine1', 'SensorMachine', '', values, function (error) { + should.not.exist(error); + oauth2Mock2.done(); + contextBrokerMock2.done(); done(); }); }); }); - it('should ask OAuth2 provider for a token based on the' + - 'trust token and send the generated token in the auth header', function(done) { - iotAgentLib.update('machine1', 'SensorMachine', '', values, function(error) { - should.not.exist(error); - oauth2Mock.done(); - contextBrokerMock.done(); - done(); + + describe('When a device is provisioned for a configuration contains an OAuth2 trust token', function () { + const values = [ + { + name: 'status', + type: 'String', + value: 'STARTING' + } + ]; + const deviceCreation = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice2.json'), + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } + }; + let contextBrokerMock2; + let contextBrokerMock3; + beforeEach(function (done) { + nock.cleanAll(); + + oauth2Mock = nock('http://192.168.1.1:3000') + .post( + '/oauth2/token', + utils.readExampleFile( + './test/unit/examples/oauthRequests/getTokenFromTrustKeyrockGroup3.json', + true + ) + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock3.json'), + {} + ) + .post( + '/oauth2/token', + utils.readExampleFile( + './test/unit/examples/oauthRequests/getTokenFromTrustKeyrockGroup4.json', + true + ) + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock4.json'), + {} + ) + .post( + '/oauth2/token', + utils.readExampleFile( + './test/unit/examples/oauthRequests/getTokenFromTrustKeyrockGroup5.json', + true + ) + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock5.json'), + {} + ); + + contextBrokerMock = nock('http://unexistenthost:1026') + .matchHeader('fiware-service', 'TestService') + .matchHeader('fiware-servicepath', '/testingPath') + .matchHeader('Authorization', 'Bearer asd752e377680acd1349a3ed59db855a1db07ere') + .post( + '/NGSI9/registerContext', + utils.readExampleFile( + './test/unit/examples/contextAvailabilityRequests/registerProvisionedDeviceWithGroup2.json' + ) + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); + + contextBrokerMock2 = nock('http://unexistenthost:1026') + .matchHeader('fiware-service', 'TestService') + .matchHeader('fiware-servicepath', '/testingPath') + .matchHeader('authorization', 'Bearer bea752e377680acd1349a3ed59db855a1db07zxc') + .post( + '/v1/updateContext', + utils.readExampleFile( + './test/unit/examples/contextRequests/createProvisionedDeviceWithGroupAndStatic2.json' + ) + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json' + ) + ); + + contextBrokerMock3 = nock('http://unexistentHost:1026') + .matchHeader('fiware-service', 'TestService') + .matchHeader('fiware-servicepath', '/testingPath') + .matchHeader('authorization', 'Bearer zzz752e377680acd1349a3ed59db855a1db07bbb') + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext4.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json') + ); + + iotAgentConfig.authentication.tokenPath = '/oauth2/token'; + iotAgentLib.activate(iotAgentConfig, function () { + done(); + }); }); - }); - it('should use the updated trust token in the following requests', function(done) { - iotAgentLib.update('machine1', 'SensorMachine', '', values, function(error) { - should.not.exist(error); - oauth2Mock2.done(); - contextBrokerMock2.done(); - done(); + it('should not raise any error', function (done) { + request(deviceCreation, function (error, response, body) { + should.not.exist(error); + response.statusCode.should.equal(201); + contextBrokerMock.done(); + contextBrokerMock2.done(); + done(); + }); }); - }); - }); + it('should send the mixed data to the Context Broker', function (done) { + iotAgentLib.update('Light1', 'SensorMachine', '', values, function (error) { + should.not.exist(error); + contextBrokerMock3.done(); + done(); + }); + }); + }); + } +); - describe('When a device is provisioned for a configuration contains an OAuth2 trust token', function() { - var values = [ - { - name: 'status', - type: 'String', - value: 'STARTING' - } - ]; - var deviceCreation = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', +describe( + 'Secured access to the Context Broker with OAuth2 provider (FIWARE Keyrock IDM)' + + 'configured through group provisioning. Permanent token', + function () { + const groupCreation = { + url: 'http://localhost:4041/iot/services', method: 'POST', - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice2.json'), + json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionFullGroup.json'), headers: { 'fiware-service': 'TestService', 'fiware-servicepath': '/testingPath' } }; - var contextBrokerMock2; - var contextBrokerMock3; - beforeEach(function(done) { - nock.cleanAll(); - - oauth2Mock = nock('http://192.168.1.1:3000') - .post('/oauth2/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrustKeyrockGroup3.json', true)) - .reply( - 200, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock3.json'), - {}) - .post('/oauth2/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrustKeyrockGroup4.json', true)) - .reply( - 200, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock4.json'), - {}) - .post('/oauth2/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrustKeyrockGroup5.json', true)) - .reply( - 200, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock5.json'), - {}); - - - contextBrokerMock = nock('http://unexistenthost:1026') - .matchHeader('fiware-service', 'TestService') - .matchHeader('fiware-servicepath', '/testingPath') - .matchHeader('Authorization', 'Bearer asd752e377680acd1349a3ed59db855a1db07ere') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerProvisionedDeviceWithGroup2.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); - - contextBrokerMock2 = nock('http://unexistenthost:1026') - .matchHeader('fiware-service', 'TestService') - .matchHeader('fiware-servicepath', '/testingPath') - .matchHeader('authorization', 'Bearer bea752e377680acd1349a3ed59db855a1db07zxc') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/createProvisionedDeviceWithGroupAndStatic2.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); - - contextBrokerMock3 = nock('http://unexistentHost:1026') - - .matchHeader('fiware-service', 'TestService') - .matchHeader('fiware-servicepath', '/testingPath') - .matchHeader('authorization', 'Bearer zzz752e377680acd1349a3ed59db855a1db07bbb') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext4.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + const values = [ + { + name: 'status', + type: 'String', + value: 'STARTING' + } + ]; - iotAgentConfig.authentication.tokenPath = '/oauth2/token'; - iotAgentLib.activate(iotAgentConfig, function() { - done(); - }); - }); - - it('should not raise any error', function(done) { - request(deviceCreation, function(error, response, body) { - should.not.exist(error); - response.statusCode.should.equal(201); - contextBrokerMock.done(); - contextBrokerMock2.done(); - done(); - }); - }); - - it('should send the mixed data to the Context Broker', function(done) { - iotAgentLib.update('Light1', 'SensorMachine', '', values, function(error) { - should.not.exist(error); - contextBrokerMock3.done(); - done(); - }); + beforeEach(function () { + logger.setLevel('FATAL'); + iotAgentConfig.authentication.permanentToken = true; }); - }); -}); - -describe('Secured access to the Context Broker with OAuth2 provider (FIWARE Keyrock IDM)' + - 'configured through group provisioning. Permanent token', function() { - var groupCreation = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionFullGroup.json'), - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - } - }; - - var values = [ - { - name: 'status', - type: 'String', - value: 'STARTING' - } - ]; - - beforeEach(function() { - logger.setLevel('FATAL'); - iotAgentConfig.authentication.permanentToken = true; - }); - - afterEach(function(done) { - iotAgentLib.deactivate(done); - nock.cleanAll(); - }); - - describe('When a measure is sent to the Context Broker via an Update Context operation', function() { - beforeEach(function(done) { + afterEach(function (done) { + iotAgentLib.deactivate(done); nock.cleanAll(); + }); - contextBrokerMock = nock('http://unexistentHost:1026') - .matchHeader('fiware-service', 'TestService') - .matchHeader('fiware-servicepath', '/testingPath') - .matchHeader('Authorization', 'Bearer 999210dacf913772606c95dd0b895d5506cbc988') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext3WithStatic.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + describe('When a measure is sent to the Context Broker via an Update Context operation', function () { + beforeEach(function (done) { + nock.cleanAll(); + contextBrokerMock = nock('http://unexistentHost:1026') + .matchHeader('fiware-service', 'TestService') + .matchHeader('fiware-servicepath', '/testingPath') + .matchHeader('Authorization', 'Bearer 999210dacf913772606c95dd0b895d5506cbc988') + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext3WithStatic.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json') + ); - iotAgentConfig.authentication.tokenPath = '/oauth2/token'; - iotAgentLib.activate(iotAgentConfig, function() { - request(groupCreation, function(error, response, body) { - done(); + iotAgentConfig.authentication.tokenPath = '/oauth2/token'; + iotAgentLib.activate(iotAgentConfig, function () { + request(groupCreation, function (error, response, body) { + done(); + }); }); }); - }); - it('should send the permanent token in the auth header', function(done) { - iotAgentLib.update('machine1', 'SensorMachine', '', values, function(error) { - should.not.exist(error); - contextBrokerMock.done(); - done(); + it('should send the permanent token in the auth header', function (done) { + iotAgentLib.update('machine1', 'SensorMachine', '', values, function (error) { + should.not.exist(error); + contextBrokerMock.done(); + done(); + }); }); - }); - it('should use the permanent trust token in the following requests', function(done) { - iotAgentLib.update('machine1', 'SensorMachine', '', values, function(error) { - should.not.exist(error); - contextBrokerMock.done(); - done(); + it('should use the permanent trust token in the following requests', function (done) { + iotAgentLib.update('machine1', 'SensorMachine', '', values, function (error) { + should.not.exist(error); + contextBrokerMock.done(); + done(); + }); }); }); - }); -}); - + } +); diff --git a/test/unit/general/deviceService-test.js b/test/unit/general/deviceService-test.js index ebf65bce9..2c355c627 100644 --- a/test/unit/general/deviceService-test.js +++ b/test/unit/general/deviceService-test.js @@ -20,199 +20,197 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; -/* jshint camelcase: false */ +/* eslint-disable no-unused-vars */ -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - nock = require('nock'), - request = require('request'), - logger = require('logops'), - async = require('async'), - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const nock = require('nock'); +const request = require('request'); +const logger = require('logops'); +const async = require('async'); +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'BrokenLight': { - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'Termometer': { - type: 'Termometer', - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ] - }, - 'Humidity': { - type: 'Humidity', - cbHost: 'http://192.168.1.1:3024', - commands: [], - lazy: [], - active: [ - { - name: 'humidity', - type: 'percentage' - } - ] - }, - 'Motion': { - type: 'Motion', - commands: [], - lazy: [], - staticAttributes: [ - { - 'name': 'location', - 'type': 'Vector', - 'value': '(123,523)' - } - ], - active: [ - { - name: 'humidity', - type: 'percentage' - } - ] - } + BrokenLight: { + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - iotManager: { - host: 'localhost', - port: 8082, - path: '/protocols', - protocol: 'MQTT_UL', - description: 'MQTT Ultralight 2.0 IoT Agent (Node.js version)' + Termometer: { + type: 'Termometer', + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [] }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }, - groupCreation = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/services', - method: 'POST', - json: { - services: [ + Humidity: { + type: 'Humidity', + cbHost: 'http://192.168.1.1:3024', + commands: [], + lazy: [], + active: [ { - resource: '', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', - entity_type: 'TheLightType', - trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', - cbHost: 'http://unexistentHost:1026', - commands: [], - lazy: [], - attributes: [ - { - name: 'status', - type: 'Boolean' - } - ], - static_attributes: [] + name: 'humidity', + type: 'percentage' } ] }, - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' + Motion: { + type: 'Motion', + commands: [], + lazy: [], + staticAttributes: [ + { + name: 'location', + type: 'Vector', + value: '(123,523)' + } + ], + active: [ + { + name: 'humidity', + type: 'percentage' + } + ] } }, - deviceCreation = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json'), - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - } + iotManager: { + host: 'localhost', + port: 8082, + path: '/protocols', + protocol: 'MQTT_UL', + description: 'MQTT Ultralight 2.0 IoT Agent (Node.js version)' }, - contextBrokerMock, - iotamMock; - + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; +const groupCreation = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/services', + method: 'POST', + json: { + services: [ + { + resource: '', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', + entity_type: 'TheLightType', + trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', + cbHost: 'http://unexistentHost:1026', + commands: [], + lazy: [], + attributes: [ + { + name: 'status', + type: 'Boolean' + } + ], + static_attributes: [] + } + ] + }, + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } +}; +const deviceCreation = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json'), + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } +}; +let contextBrokerMock; +let iotamMock; /* jshint camelcase: false */ -describe('NGSI-v1 - Device Service: utils', function() { - beforeEach(function(done) { +describe('NGSI-v1 - Device Service: utils', function () { + beforeEach(function (done) { nock.cleanAll(); logger.setLevel('FATAL'); - iotamMock = nock('http://localhost:8082') - .post('/protocols') - .reply(200, {}); + iotamMock = nock('http://localhost:8082').post('/protocols').reply(200, {}); iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { + afterEach(function (done) { nock.cleanAll(); - async.series([ - iotAgentLib.clearAll, - iotAgentLib.deactivate - ], done); + async.series([iotAgentLib.clearAll, iotAgentLib.deactivate], done); }); - describe('When an existing device tries to be retrieved with retrieveOrCreate()', function() { - beforeEach(function(done) { + describe('When an existing device tries to be retrieved with retrieveOrCreate()', function () { + beforeEach(function (done) { contextBrokerMock = nock('http://unexistentHost:1026') .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') .post('/NGSI9/registerContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); - async.series([ - request.bind(request, groupCreation), - request.bind(request, deviceCreation) - ], function(error, results) { + async.series([request.bind(request, groupCreation), request.bind(request, deviceCreation)], function ( + error, + results + ) { done(); }); }); - it('should return the existing device', function(done) { - iotAgentLib.retrieveDevice('Light1', '801230BJKL23Y9090DSFL123HJK09H324HV8732', function(error, device) { + it('should return the existing device', function (done) { + iotAgentLib.retrieveDevice('Light1', '801230BJKL23Y9090DSFL123HJK09H324HV8732', function (error, device) { should.not.exist(error); should.exist(device); @@ -222,52 +220,60 @@ describe('NGSI-v1 - Device Service: utils', function() { }); }); - describe('When an unexisting device tries to be retrieved for an existing APIKey', function() { - beforeEach(function(done) { + describe('When an unexisting device tries to be retrieved for an existing APIKey', function () { + beforeEach(function (done) { contextBrokerMock = nock('http://unexistentHost:1026') .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') .post('/NGSI9/registerContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); - async.series([ - request.bind(request, groupCreation) - ], function(error, results) { + async.series([request.bind(request, groupCreation)], function (error, results) { done(); }); }); - it('should register the device and return it', function(done) { - iotAgentLib.retrieveDevice('UNEXISTENT_DEV', '801230BJKL23Y9090DSFL123HJK09H324HV8732', - function(error, device) { - should.not.exist(error); - should.exist(device); + it('should register the device and return it', function (done) { + iotAgentLib.retrieveDevice('UNEXISTENT_DEV', '801230BJKL23Y9090DSFL123HJK09H324HV8732', function ( + error, + device + ) { + should.not.exist(error); + should.exist(device); - device.id.should.equal('UNEXISTENT_DEV'); - should.exist(device.protocol); - device.protocol.should.equal('MQTT_UL'); - done(); - }); + device.id.should.equal('UNEXISTENT_DEV'); + should.exist(device.protocol); + device.protocol.should.equal('MQTT_UL'); + done(); + }); }); }); - describe('When an unexisting device tries to be retrieved for an unexisting APIKey', function() { - it('should raise an error', function(done) { - iotAgentLib.retrieveDevice('UNEXISTENT_DEV_AND_GROUP', 'H2332Y909DSF3H346yh20JK092', - function(error, device) { - should.exist(error); - error.name.should.equal('DEVICE_GROUP_NOT_FOUND'); - should.not.exist(device); - done(); - }); + describe('When an unexisting device tries to be retrieved for an unexisting APIKey', function () { + it('should raise an error', function (done) { + iotAgentLib.retrieveDevice('UNEXISTENT_DEV_AND_GROUP', 'H2332Y909DSF3H346yh20JK092', function ( + error, + device + ) { + should.exist(error); + error.name.should.equal('DEVICE_GROUP_NOT_FOUND'); + should.not.exist(device); + done(); + }); }); }); }); diff --git a/test/unit/general/https-support-test.js b/test/unit/general/https-support-test.js index 0de605597..d2fd6242d 100644 --- a/test/unit/general/https-support-test.js +++ b/test/unit/general/https-support-test.js @@ -23,129 +23,126 @@ * Modified by: Federico M. Facca - Martel Innovate * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; -/* jshint camelcase: false */ +/* eslint-disable no-unused-vars */ -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - request = require('request'), - nock = require('nock'), - utils = require('../../tools/utils'), - groupRegistryMemory = require('../../../lib/services/groups/groupRegistryMemory'), - should = require('should'), - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - url: 'https://192.168.1.1:1026' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ], - service: 'smartGondor', - subservice: 'gardens' - }, - 'Termometer': { - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ], - service: 'smartGondor', - subservice: 'gardens' - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M', - iotManager: { - url: 'https://mockediotam.com:9876', - path: '/protocols', - protocol: 'GENERIC_PROTOCOL', - description: 'A generic protocol', - agentPath: '/iot' - }, - defaultResource: '/iot/d' +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const request = require('request'); +const nock = require('nock'); +const utils = require('../../tools/utils'); +const groupRegistryMemory = require('../../../lib/services/groups/groupRegistryMemory'); +const should = require('should'); +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + url: 'https://192.168.1.1:1026' }, - groupCreation = { - service: 'theService', - subservice: 'theSubService', - resource: '/deviceTest', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', - type: 'SensorMachine', - trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', - commands: [ - { - name: 'wheel1', - type: 'Wheel' - } - ], - lazy: [ - { - name: 'luminescence', - type: 'Lumens' - } - ], - attributes: [ - { - name: 'status', - type: 'Boolean' - } - ] + server: { + port: 4041 }, - device1 = { - id: 'light1', - type: 'Light', - service: 'smartGondor', - subservice: 'gardens' + types: { + Light: { + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ], + service: 'smartGondor', + subservice: 'gardens' + }, + Termometer: { + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [], + service: 'smartGondor', + subservice: 'gardens' + } }, - contextBrokerMock, - iotamMock; - - -describe('NGSI-v1 - HTTPS support tests IOTAM', function() { + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M', + iotManager: { + url: 'https://mockediotam.com:9876', + path: '/protocols', + protocol: 'GENERIC_PROTOCOL', + description: 'A generic protocol', + agentPath: '/iot' + }, + defaultResource: '/iot/d' +}; +const groupCreation = { + service: 'theService', + subservice: 'theSubService', + resource: '/deviceTest', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', + type: 'SensorMachine', + trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', + commands: [ + { + name: 'wheel1', + type: 'Wheel' + } + ], + lazy: [ + { + name: 'luminescence', + type: 'Lumens' + } + ], + attributes: [ + { + name: 'status', + type: 'Boolean' + } + ] +}; +const device1 = { + id: 'light1', + type: 'Light', + service: 'smartGondor', + subservice: 'gardens' +}; +let contextBrokerMock; +let iotamMock; - describe('When the IoT Agents is started with https "iotManager" config', function() { - beforeEach(function(done) { +describe('NGSI-v1 - HTTPS support tests IOTAM', function () { + describe('When the IoT Agents is started with https "iotManager" config', function () { + beforeEach(function (done) { nock.cleanAll(); iotamMock = nock('https://mockediotam.com:9876') - .post('/protocols', - utils.readExampleFile('./test/unit/examples/iotamRequests/registrationWithGroupsWithoutCB.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); + .post( + '/protocols', + utils.readExampleFile('./test/unit/examples/iotamRequests/registrationWithGroupsWithoutCB.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); groupRegistryMemory.create(groupCreation, done); }); - afterEach(function(done) { + afterEach(function (done) { nock.cleanAll(); - groupRegistryMemory.clear(function() { + groupRegistryMemory.clear(function () { iotAgentLib.deactivate(done); }); }); - it('should register without errors to the IoT Manager', function(done) { - iotAgentLib.activate(iotAgentConfig, function(error) { + it('should register without errors to the IoT Manager', function (done) { + iotAgentLib.activate(iotAgentConfig, function (error) { should.not.exist(error); iotamMock.done(); done(); @@ -154,15 +151,15 @@ describe('NGSI-v1 - HTTPS support tests IOTAM', function() { }); }); -describe('NGSI-v1 - HTTPS support tests', function() { - - describe('When subscription is sent to HTTPS context broker', function() { - beforeEach(function(done) { - var optionsProvision = { +describe('NGSI-v1 - HTTPS support tests', function () { + describe('When subscription is sent to HTTPS context broker', function () { + beforeEach(function (done) { + const optionsProvision = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), + './test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json' + ), headers: { 'fiware-service': 'smartGondor', 'fiware-servicepath': '/gardens' @@ -173,46 +170,58 @@ describe('NGSI-v1 - HTTPS support tests', function() { nock.cleanAll(); - iotAgentLib.activate(iotAgentConfig, function() { + iotAgentLib.activate(iotAgentConfig, function () { contextBrokerMock = nock('https://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/updateContext', + .post( + '/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/createMinimumProvisionedDevice.json')) - .reply(200, + './test/unit/examples/contextRequests/createMinimumProvisionedDevice.json' + ) + ) + .reply( + 200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock = nock('https://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/subscribeContext', + .post( + '/v1/subscribeContext', utils.readExampleFile( - './test/unit/examples/subscriptionRequests/simpleSubscriptionRequest.json')) - .reply(200, + './test/unit/examples/subscriptionRequests/simpleSubscriptionRequest.json' + ) + ) + .reply( + 200, utils.readExampleFile( - './test/unit/examples/subscriptionResponses/simpleSubscriptionSuccess.json')); + './test/unit/examples/subscriptionResponses/simpleSubscriptionSuccess.json' + ) + ); - iotAgentLib.clearAll(function() { - request(optionsProvision, function(error, result, body) { + iotAgentLib.clearAll(function () { + request(optionsProvision, function (error, result, body) { done(); }); }); }); }); - afterEach(function(done) { + afterEach(function (done) { nock.cleanAll(); iotAgentLib.setNotificationHandler(); - iotAgentLib.clearAll(function() { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - it('should send the appropriate request to the Context Broker', function(done) { - iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function(error, device) { - iotAgentLib.subscribe(device, ['attr_name'], null, function(error) { + it('should send the appropriate request to the Context Broker', function (done) { + iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function (error, device) { + iotAgentLib.subscribe(device, ['attr_name'], null, function (error) { should.not.exist(error); contextBrokerMock.done(); @@ -223,8 +232,8 @@ describe('NGSI-v1 - HTTPS support tests', function() { }); }); - describe('When a new device is connected to the IoT Agent', function() { - beforeEach(function(done) { + describe('When a new device is connected to the IoT Agent', function () { + beforeEach(function (done) { nock.cleanAll(); iotAgentConfig.iotManager = {}; @@ -232,39 +241,46 @@ describe('NGSI-v1 - HTTPS support tests', function() { contextBrokerMock = nock('https://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); - iotAgentLib.activate(iotAgentConfig, function(error) { + iotAgentLib.activate(iotAgentConfig, function (error) { iotAgentLib.clearAll(done); }); }); - it('should register as ContextProvider using HTTPS', function(done) { - iotAgentLib.register(device1, function(error) { - should.not.exist(error); - contextBrokerMock.done(); - done(); + it('should register as ContextProvider using HTTPS', function (done) { + iotAgentLib.register(device1, function (error) { + should.not.exist(error); + contextBrokerMock.done(); + done(); }); }); - afterEach(function(done) { - nock.cleanAll(); - iotAgentLib.clearAll(function() { - // We need to remove the registrationId so that the library does not consider next operatios as updates. - delete device1.registrationId; - iotAgentLib.deactivate(done); - }); + afterEach(function (done) { + nock.cleanAll(); + iotAgentLib.clearAll(function () { + // We need to remove the registrationId so that the library does not consider next operatios as updates. + delete device1.registrationId; + iotAgentLib.deactivate(done); + }); }); - }); }); diff --git a/test/unit/general/iotam-autoregistration-test.js b/test/unit/general/iotam-autoregistration-test.js index ce87bb577..99f8e43e9 100644 --- a/test/unit/general/iotam-autoregistration-test.js +++ b/test/unit/general/iotam-autoregistration-test.js @@ -20,190 +20,187 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; - -/* jshint camelcase: false */ - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - request = require('request'), - nock = require('nock'), - utils = require('../../tools/utils'), - groupRegistryMemory = require('../../../lib/services/groups/groupRegistryMemory'), - should = require('should'), - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - type: 'Light', + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const request = require('request'); +const nock = require('nock'); +const utils = require('../../tools/utils'); +const groupRegistryMemory = require('../../../lib/services/groups/groupRegistryMemory'); +const should = require('should'); +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + attributes: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] + } + }, + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M', + iotManager: { + host: 'mockediotam.com', + port: 9876, + path: '/protocols', + protocol: 'GENERIC_PROTOCOL', + description: 'A generic protocol', + agentPath: '/iot' + }, + defaultResource: '/iot/d' +}; +const groupCreation = { + service: 'theService', + subservice: 'theSubService', + resource: '/deviceTest', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', + type: 'SensorMachine', + trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', + cbHost: 'http://unexistentHost:1026', + commands: [ + { + name: 'wheel1', + type: 'Wheel' + } + ], + lazy: [ + { + name: 'luminescence', + type: 'Lumens' + } + ], + attributes: [ + { + name: 'status', + type: 'Boolean' + } + ] +}; +const optionsCreation = { + url: 'http://localhost:4041/iot/services', + method: 'POST', + json: { + services: [ + { + resource: '/deviceTest', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', + entity_type: 'SensorMachine', + trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', + cbHost: 'http://unexistentHost:1026', + commands: [ + { + name: 'wheel1', + type: 'Wheel' + } + ], lazy: [ { - name: 'temperature', - type: 'centigrades' + name: 'luminescence', + type: 'Lumens' } ], attributes: [ { - name: 'pressure', - type: 'Hgmm' + name: 'status', + type: 'Boolean' } ] } - }, - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M', - iotManager: { - host: 'mockediotam.com', - port: 9876, - path: '/protocols', - protocol: 'GENERIC_PROTOCOL', - description: 'A generic protocol', - agentPath: '/iot' - }, - defaultResource: '/iot/d' + ] }, - groupCreation = { - service: 'theService', - subservice: 'theSubService', - resource: '/deviceTest', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', - type: 'SensorMachine', - trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', - cbHost: 'http://unexistentHost:1026', - commands: [ - { - name: 'wheel1', - type: 'Wheel' - } - ], - lazy: [ - { - name: 'luminescence', - type: 'Lumens' - } - ], - attributes: [ + headers: { + 'fiware-service': 'theService', + 'fiware-servicepath': 'theSubService' + } +}; +const optionsCreationStatic = { + url: 'http://localhost:4041/iot/services', + method: 'POST', + json: { + services: [ { - name: 'status', - type: 'Boolean' + resource: '/deviceTest', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', + entity_type: 'SensorMachine', + trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', + cbHost: 'http://unexistentHost:1026', + commands: [ + { + name: 'wheel1', + type: 'Wheel' + } + ], + static_attributes: [ + { + name: 'position', + type: 'location', + values: '123,12' + } + ], + attributes: [ + { + name: 'status', + type: 'Boolean' + } + ] } ] }, - optionsCreation = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: { - services: [ - { - resource: '/deviceTest', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', - entity_type: 'SensorMachine', - trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', - cbHost: 'http://unexistentHost:1026', - commands: [ - { - name: 'wheel1', - type: 'Wheel' - } - ], - lazy: [ - { - name: 'luminescence', - type: 'Lumens' - } - ], - attributes: [ - { - name: 'status', - type: 'Boolean' - } - ] - } - ] - }, - headers: { - 'fiware-service': 'theService', - 'fiware-servicepath': 'theSubService' - } + headers: { + 'fiware-service': 'theService', + 'fiware-servicepath': 'theSubService' + } +}; +const optionsDelete = { + url: 'http://localhost:4041/iot/services', + method: 'DELETE', + json: {}, + headers: { + 'fiware-service': 'theService', + 'fiware-servicepath': 'theSubService' }, - optionsCreationStatic = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: { - services: [ - { - resource: '/deviceTest', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', - entity_type: 'SensorMachine', - trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', - cbHost: 'http://unexistentHost:1026', - commands: [ - { - name: 'wheel1', - type: 'Wheel' - } - ], - static_attributes: [ - { - name: 'position', - type: 'location', - values: '123,12' - } - ], - attributes: [ - { - name: 'status', - type: 'Boolean' - } - ] - } - ] - }, - headers: { - 'fiware-service': 'theService', - 'fiware-servicepath': 'theSubService' - } - }, - optionsDelete = { - url: 'http://localhost:4041/iot/services', - method: 'DELETE', - json: {}, - headers: { - 'fiware-service': 'theService', - 'fiware-servicepath': 'theSubService' - }, - qs: { - resource: '/deviceTest', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732' - } - }, - iotamMock; - -describe('NGSI-v1 - IoT Manager autoregistration', function() { - describe('When the IoT Agent is started without a "iotManager" config parameter and empty services', function() { - beforeEach(function() { + qs: { + resource: '/deviceTest', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732' + } +}; +let iotamMock; + +describe('NGSI-v1 - IoT Manager autoregistration', function () { + describe('When the IoT Agent is started without a "iotManager" config parameter and empty services', function () { + beforeEach(function () { nock.cleanAll(); iotamMock = nock('http://mockediotam.com:9876') - .post('/protocols', - utils.readExampleFile('./test/unit/examples/iotamRequests/registrationEmpty.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); + .post('/protocols', utils.readExampleFile('./test/unit/examples/iotamRequests/registrationEmpty.json')) + .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); }); - it('should register itself to the provided IoT Manager URL', function(done) { - iotAgentLib.activate(iotAgentConfig, function(error) { + it('should register itself to the provided IoT Manager URL', function (done) { + iotAgentLib.activate(iotAgentConfig, function (error) { should.not.exist(error); iotamMock.done(); done(); @@ -211,25 +208,23 @@ describe('NGSI-v1 - IoT Manager autoregistration', function() { }); }); - describe('When the IoT Agents is started with "iotManager" config with missing attributes', function() { - beforeEach(function() { + describe('When the IoT Agents is started with "iotManager" config with missing attributes', function () { + beforeEach(function () { nock.cleanAll(); delete iotAgentConfig.providerUrl; iotamMock = nock('http://mockediotam.com:9876') - .post('/protocols', - utils.readExampleFile('./test/unit/examples/iotamRequests/registrationEmpty.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); + .post('/protocols', utils.readExampleFile('./test/unit/examples/iotamRequests/registrationEmpty.json')) + .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); }); - afterEach(function() { + afterEach(function () { iotAgentConfig.providerUrl = 'http://smartGondor.com'; }); - it('should fail with a MISSING_CONFIG_PARAMS error', function(done) { - iotAgentLib.activate(iotAgentConfig, function(error) { + it('should fail with a MISSING_CONFIG_PARAMS error', function (done) { + iotAgentLib.activate(iotAgentConfig, function (error) { should.exist(error); error.name.should.equal('MISSING_CONFIG_PARAMS'); done(); @@ -237,27 +232,28 @@ describe('NGSI-v1 - IoT Manager autoregistration', function() { }); }); - describe('When the IoT Agents is started with "iotManager" config and multiple services', function() { - beforeEach(function(done) { + describe('When the IoT Agents is started with "iotManager" config and multiple services', function () { + beforeEach(function (done) { nock.cleanAll(); iotamMock = nock('http://mockediotam.com:9876') - .post('/protocols', - utils.readExampleFile('./test/unit/examples/iotamRequests/registrationWithGroups.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); + .post( + '/protocols', + utils.readExampleFile('./test/unit/examples/iotamRequests/registrationWithGroups.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); groupRegistryMemory.create(groupCreation, done); }); - afterEach(function(done) { - groupRegistryMemory.clear(function() { + afterEach(function (done) { + groupRegistryMemory.clear(function () { iotAgentLib.deactivate(done); }); }); - it('should send all the service information to the IoT Manager in the registration', function(done) { - iotAgentLib.activate(iotAgentConfig, function(error) { + it('should send all the service information to the IoT Manager in the registration', function (done) { + iotAgentLib.activate(iotAgentConfig, function (error) { should.not.exist(error); iotamMock.done(); done(); @@ -265,35 +261,34 @@ describe('NGSI-v1 - IoT Manager autoregistration', function() { }); }); - describe('When a new service is created in the IoT Agent', function() { - beforeEach(function(done) { + describe('When a new service is created in the IoT Agent', function () { + beforeEach(function (done) { nock.cleanAll(); iotamMock = nock('http://mockediotam.com:9876') - .post('/protocols', - utils.readExampleFile('./test/unit/examples/iotamRequests/registrationEmpty.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); + .post('/protocols', utils.readExampleFile('./test/unit/examples/iotamRequests/registrationEmpty.json')) + .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); iotamMock - .post('/protocols', - utils.readExampleFile('./test/unit/examples/iotamRequests/registrationWithGroups.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); + .post( + '/protocols', + utils.readExampleFile('./test/unit/examples/iotamRequests/registrationWithGroups.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); - iotAgentLib.activate(iotAgentConfig, function(error) { + iotAgentLib.activate(iotAgentConfig, function (error) { done(); }); }); - afterEach(function(done) { - groupRegistryMemory.clear(function() { + afterEach(function (done) { + groupRegistryMemory.clear(function () { iotAgentLib.deactivate(done); }); }); - it('should update the registration in the IoT Manager', function(done) { - request(optionsCreation, function(error, result, body) { + it('should update the registration in the IoT Manager', function (done) { + request(optionsCreation, function (error, result, body) { should.not.exist(error); iotamMock.done(); done(); @@ -301,35 +296,34 @@ describe('NGSI-v1 - IoT Manager autoregistration', function() { }); }); - describe('When a service is removed from the IoT Agent', function() { - beforeEach(function(done) { + describe('When a service is removed from the IoT Agent', function () { + beforeEach(function (done) { nock.cleanAll(); iotamMock = nock('http://mockediotam.com:9876') - .post('/protocols', - utils.readExampleFile('./test/unit/examples/iotamRequests/registrationWithGroups.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); + .post( + '/protocols', + utils.readExampleFile('./test/unit/examples/iotamRequests/registrationWithGroups.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); iotamMock - .post('/protocols', - utils.readExampleFile('./test/unit/examples/iotamRequests/registrationEmpty.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); + .post('/protocols', utils.readExampleFile('./test/unit/examples/iotamRequests/registrationEmpty.json')) + .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); - groupRegistryMemory.create(groupCreation, function() { + groupRegistryMemory.create(groupCreation, function () { iotAgentLib.activate(iotAgentConfig, done); }); }); - afterEach(function(done) { - groupRegistryMemory.clear(function() { + afterEach(function (done) { + groupRegistryMemory.clear(function () { iotAgentLib.deactivate(done); }); }); - it('should update the registration in the IoT Manager', function(done) { - request(optionsDelete, function(error, result, body) { + it('should update the registration in the IoT Manager', function (done) { + request(optionsDelete, function (error, result, body) { should.not.exist(error); iotamMock.done(); done(); @@ -337,35 +331,34 @@ describe('NGSI-v1 - IoT Manager autoregistration', function() { }); }); - describe('When a new service with static attributes is created in the IoT Agent', function() { - beforeEach(function(done) { + describe('When a new service with static attributes is created in the IoT Agent', function () { + beforeEach(function (done) { nock.cleanAll(); iotamMock = nock('http://mockediotam.com:9876') - .post('/protocols', - utils.readExampleFile('./test/unit/examples/iotamRequests/registrationEmpty.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); + .post('/protocols', utils.readExampleFile('./test/unit/examples/iotamRequests/registrationEmpty.json')) + .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); iotamMock - .post('/protocols', - utils.readExampleFile('./test/unit/examples/iotamRequests/registrationWithStaticGroups.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); + .post( + '/protocols', + utils.readExampleFile('./test/unit/examples/iotamRequests/registrationWithStaticGroups.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); - iotAgentLib.activate(iotAgentConfig, function(error) { + iotAgentLib.activate(iotAgentConfig, function (error) { done(); }); }); - afterEach(function(done) { - groupRegistryMemory.clear(function() { + afterEach(function (done) { + groupRegistryMemory.clear(function () { iotAgentLib.deactivate(done); }); }); - it('should update the registration in the IoT Manager', function(done) { - request(optionsCreationStatic, function(error, result, body) { + it('should update the registration in the IoT Manager', function (done) { + request(optionsCreationStatic, function (error, result, body) { should.not.exist(error); iotamMock.done(); done(); diff --git a/test/unit/general/loglevel-api_test.js b/test/unit/general/loglevel-api_test.js index ce4311411..651d05631 100644 --- a/test/unit/general/loglevel-api_test.js +++ b/test/unit/general/loglevel-api_test.js @@ -20,59 +20,58 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[iot_support@tid.es] */ -'use strict'; - -/* jshint camelcase: false */ - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - should = require('should'), - logger = require('logops'), - request = require('request'), - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - object_id: 't', - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm' - }, - { - object_id: 'l', - name: 'luminance', - type: 'lumens' - } - ] - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }; - -describe('Log level API', function() { - beforeEach(function(done) { + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const should = require('should'); +const logger = require('logops'); +const request = require('request'); +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + object_id: 't', + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm' + }, + { + object_id: 'l', + name: 'luminance', + type: 'lumens' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; + +describe('Log level API', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.attributeAlias.update); iotAgentLib.addQueryMiddleware(iotAgentLib.dataPlugins.attributeAlias.query); done(); @@ -80,27 +79,27 @@ describe('Log level API', function() { }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When a new valid log level request comes to the API', function() { - var options = { + describe('When a new valid log level request comes to the API', function () { + const options = { uri: 'http://localhost:' + iotAgentConfig.server.port + '/admin/log', method: 'PUT', headers: { 'Content-Type': 'application/json', - 'Accept': 'application/json' + Accept: 'application/json' }, qs: { level: 'ERROR' } }; - it('the real log level should be changed', function(done) { - request(options, function(error, response, body) { + it('the real log level should be changed', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(200); @@ -109,18 +108,18 @@ describe('Log level API', function() { }); }); - describe('When the current log level is requested', function() { - var options = { + describe('When the current log level is requested', function () { + const options = { uri: 'http://localhost:' + iotAgentConfig.server.port + '/admin/log', method: 'GET', headers: { 'Content-Type': 'application/json', - 'Accept': 'application/json' + Accept: 'application/json' } }; - it('should return a 200 OK', function(done) { - request(options, function(error, response, body) { + it('should return a 200 OK', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(200); @@ -128,9 +127,9 @@ describe('Log level API', function() { }); }); - it('should return the current log level', function(done) { - request(options, function(error, response, body) { - var parsedBody = JSON.parse(body); + it('should return the current log level', function (done) { + request(options, function (error, response, body) { + const parsedBody = JSON.parse(body); should.exist(parsedBody.level); parsedBody.level.should.equal('FATAL'); @@ -140,28 +139,26 @@ describe('Log level API', function() { }); }); - describe('When a new log level request comes to the API with an invalid level', function() { - var options = { + describe('When a new log level request comes to the API with an invalid level', function () { + const options = { uri: 'http://localhost:' + iotAgentConfig.server.port + '/admin/log', method: 'PUT', headers: { 'Content-Type': 'application/json', - 'Accept': 'application/json' + Accept: 'application/json' }, qs: { level: 'ALLRIGHT' } }; - it('should return a 400 error indicating the log level is not valid', function(done) { - request(options, function(error, response, body) { - var parsedBody; - + it('should return a 400 error indicating the log level is not valid', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(400); should.exist(body); - parsedBody = JSON.parse(body); + const parsedBody = JSON.parse(body); parsedBody.error.should.equal('invalid log level'); @@ -170,25 +167,23 @@ describe('Log level API', function() { }); }); - describe('When a new log level request comes to the API without a log level', function() { - var options = { + describe('When a new log level request comes to the API without a log level', function () { + const options = { uri: 'http://localhost:' + iotAgentConfig.server.port + '/admin/log', method: 'PUT', headers: { 'Content-Type': 'application/json', - 'Accept': 'application/json' + Accept: 'application/json' } }; - it('should return a 400 error indicating the log level is missing', function(done) { - request(options, function(error, response, body) { - var parsedBody; - + it('should return a 400 error indicating the log level is missing', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(400); should.exist(body); - parsedBody = JSON.parse(body); + const parsedBody = JSON.parse(body); parsedBody.error.should.equal('log level missing'); diff --git a/test/unit/general/migration-test.js b/test/unit/general/migration-test.js index 3a3843016..03e04e57b 100644 --- a/test/unit/general/migration-test.js +++ b/test/unit/general/migration-test.js @@ -20,44 +20,46 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; -/* jshint camelcase: false */ +/* eslint-disable no-unused-vars */ -var migration = require('../../../lib/command/migration'), - mongo = require('mongodb').MongoClient, - mongoUtils = require('../mongodb/mongoDBUtils'), - utils = require('../../tools/utils'), - logger = require('logops'), - async = require('async'), - apply = async.apply, - should = require('should'), - deviceCollection = utils.readExampleFile('./test/unit/examples/mongoCollections/devices.json'), - configurationCollection = utils.readExampleFile('./test/unit/examples/mongoCollections/configurations.json'), - originDb, - targetDb; +const migration = require('../../../lib/command/migration'); +const mongo = require('mongodb').MongoClient; +const mongoUtils = require('../mongodb/mongoDBUtils'); +const utils = require('../../tools/utils'); +const logger = require('logops'); +const async = require('async'); +const apply = async.apply; +const should = require('should'); +const deviceCollection = utils.readExampleFile('./test/unit/examples/mongoCollections/devices.json'); +const configurationCollection = utils.readExampleFile('./test/unit/examples/mongoCollections/configurations.json'); +let originDb; +let targetDb; -describe('MongoDB migration', function() { - beforeEach(function(done) { +describe('MongoDB migration', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - mongo.connect('mongodb://localhost:27017/iotOrigin', { useNewUrlParser: true }, function(err, client) { + mongo.connect('mongodb://localhost:27017/iotOrigin', { useNewUrlParser: true }, function (err, client) { originDb = client; - mongo.connect('mongodb://localhost:27017/iotTarget', { useNewUrlParser: true }, function(err, client) { + mongo.connect('mongodb://localhost:27017/iotTarget', { useNewUrlParser: true }, function (err, client) { targetDb = client; - async.series([ - apply(mongoUtils.populate, 'localhost', 'iotOrigin', deviceCollection, 'DEVICE'), - apply(mongoUtils.populate, 'localhost', 'iotOrigin', configurationCollection, 'SERVICE') - ], done); + async.series( + [ + apply(mongoUtils.populate, 'localhost', 'iotOrigin', deviceCollection, 'DEVICE'), + apply(mongoUtils.populate, 'localhost', 'iotOrigin', configurationCollection, 'SERVICE') + ], + done + ); }); }); }); - afterEach(function(done) { - mongoUtils.cleanDb('localhost', 'iotTarget', function(error) { - mongoUtils.cleanDb('localhost', 'iotOrigin', function(error) { - originDb.close(function(error) { - targetDb.close(function(error) { + afterEach(function (done) { + mongoUtils.cleanDb('localhost', 'iotTarget', function (error) { + mongoUtils.cleanDb('localhost', 'iotOrigin', function (error) { + originDb.close(function (error) { + targetDb.close(function (error) { done(); }); }); @@ -65,138 +67,170 @@ describe('MongoDB migration', function() { }); }); - describe('When the full migration command is executed for two databases', function() { - var config = { + describe('When the full migration command is executed for two databases', function () { + const config = { host: 'localhost', port: '27017' }; - it('should migrate all the services', function(done) { - migration.migrate(config, 'iotOrigin', 'iotTarget', null, null, function() { - targetDb.db().collection('groups').find({}).toArray(function(err, docs) { - should.not.exist(err); - docs.length.should.equal(3); - done(); - }); + it('should migrate all the services', function (done) { + migration.migrate(config, 'iotOrigin', 'iotTarget', null, null, function () { + targetDb + .db() + .collection('groups') + .find({}) + .toArray(function (err, docs) { + should.not.exist(err); + docs.length.should.equal(3); + done(); + }); }); }); - it('should migrate all the devices', function(done) { - migration.migrate(config, 'iotOrigin', 'iotTarget', null, null, function() { - targetDb.db().collection('devices').find({}).toArray(function(err, docs) { - should.not.exist(err); - docs.length.should.equal(4); - done(); - }); + it('should migrate all the devices', function (done) { + migration.migrate(config, 'iotOrigin', 'iotTarget', null, null, function () { + targetDb + .db() + .collection('devices') + .find({}) + .toArray(function (err, docs) { + should.not.exist(err); + docs.length.should.equal(4); + done(); + }); }); }); - it('should migrate all the fields for each device', function(done) { - migration.migrate(config, 'iotOrigin', 'iotTarget', null, null, function() { - targetDb.db().collection('groups').find({ - service: 'dumb_mordor' - }).toArray(function(err, docs) { - should.not.exist(err); - docs.length.should.equal(1); - should.exist(docs[0].apikey); - should.exist(docs[0].cbHost); - should.exist(docs[0].resource); - should.exist(docs[0].service); - should.exist(docs[0].subservice); - should.exist(docs[0].type); - should.exist(docs[0].staticAttributes); - done(); - }); + it('should migrate all the fields for each device', function (done) { + migration.migrate(config, 'iotOrigin', 'iotTarget', null, null, function () { + targetDb + .db() + .collection('groups') + .find({ + service: 'dumb_mordor' + }) + .toArray(function (err, docs) { + should.not.exist(err); + docs.length.should.equal(1); + should.exist(docs[0].apikey); + should.exist(docs[0].cbHost); + should.exist(docs[0].resource); + should.exist(docs[0].service); + should.exist(docs[0].subservice); + should.exist(docs[0].type); + should.exist(docs[0].staticAttributes); + done(); + }); }); }); - it('should migrate all the fields for each service', function(done) { - migration.migrate(config, 'iotOrigin', 'iotTarget', null, null, function() { - targetDb.db().collection('devices').find({ - id: 'gk20' - }).toArray(function(err, docs) { - should.not.exist(err); - docs.length.should.equal(1); - should.exist(docs[0].id); - should.exist(docs[0].name); - should.exist(docs[0].protocol); - should.exist(docs[0].service); - should.exist(docs[0].subservice); - should.exist(docs[0].type); - should.exist(docs[0].active); - should.exist(docs[0].staticAttributes); - docs[0].id = 'gk20'; - docs[0].name = 'The GK20 Entity'; - docs[0].protocol = 'PDI-IoTA-UltraLight'; - docs[0].service = 'smart_gondor'; - docs[0].subservice = '/gardens'; - docs[0].type = 'acme.lights.sensor'; - done(); - }); + it('should migrate all the fields for each service', function (done) { + migration.migrate(config, 'iotOrigin', 'iotTarget', null, null, function () { + targetDb + .db() + .collection('devices') + .find({ + id: 'gk20' + }) + .toArray(function (err, docs) { + should.not.exist(err); + docs.length.should.equal(1); + should.exist(docs[0].id); + should.exist(docs[0].name); + should.exist(docs[0].protocol); + should.exist(docs[0].service); + should.exist(docs[0].subservice); + should.exist(docs[0].type); + should.exist(docs[0].active); + should.exist(docs[0].staticAttributes); + docs[0].id = 'gk20'; + docs[0].name = 'The GK20 Entity'; + docs[0].protocol = 'PDI-IoTA-UltraLight'; + docs[0].service = 'smart_gondor'; + docs[0].subservice = '/gardens'; + docs[0].type = 'acme.lights.sensor'; + done(); + }); }); }); }); - describe('When a service migration command is executed', function() { - var config = { + describe('When a service migration command is executed', function () { + const config = { host: 'localhost', port: '27017' }; - it('should migrate just the service\'s configurations', function(done) { - migration.migrate(config, 'iotOrigin', 'iotTarget', 'smart_gondor', null, function() { - targetDb.db().collection('groups').find({}).toArray(function(err, docs) { - should.not.exist(err); - docs.length.should.equal(1); - done(); - }); + it("should migrate just the service's configurations", function (done) { + migration.migrate(config, 'iotOrigin', 'iotTarget', 'smart_gondor', null, function () { + targetDb + .db() + .collection('groups') + .find({}) + .toArray(function (err, docs) { + should.not.exist(err); + docs.length.should.equal(1); + done(); + }); }); }); - it('should migrate just the service\'s devices', function(done) { - migration.migrate(config, 'iotOrigin', 'iotTarget', 'smart_gondor', null, function() { - targetDb.db().collection('devices').find({}).toArray(function(err, docs) { - should.not.exist(err); - docs.length.should.equal(3); - done(); - }); + it("should migrate just the service's devices", function (done) { + migration.migrate(config, 'iotOrigin', 'iotTarget', 'smart_gondor', null, function () { + targetDb + .db() + .collection('devices') + .find({}) + .toArray(function (err, docs) { + should.not.exist(err); + docs.length.should.equal(3); + done(); + }); }); }); }); - describe('When a device has an empty string in its name', function() { - var config = { + describe('When a device has an empty string in its name', function () { + const config = { host: 'localhost', port: '27017' }; - it('should set the name as undefined', function(done) { - migration.migrate(config, 'iotOrigin', 'iotTarget', 'dumb_mordor', null, function() { - targetDb.db().collection('devices').find({}).toArray(function(err, docs) { - docs.length.should.equal(1); - should.exist(docs[0].name); - docs[0].name.should.equal(docs[0].type + ':' + docs[0].id); - done(); - }); + it('should set the name as undefined', function (done) { + migration.migrate(config, 'iotOrigin', 'iotTarget', 'dumb_mordor', null, function () { + targetDb + .db() + .collection('devices') + .find({}) + .toArray(function (err, docs) { + docs.length.should.equal(1); + should.exist(docs[0].name); + docs[0].name.should.equal(docs[0].type + ':' + docs[0].id); + done(); + }); }); }); }); - describe('When a subservice migration command is executed', function() { - var config = { + describe('When a subservice migration command is executed', function () { + const config = { host: 'localhost', port: '27017' }; - it('should migrate just the subservice\'s devices', function(done) { - migration.migrate(config, 'iotOrigin', 'iotTarget', 'smart_gondor', '/gardens', function() { - targetDb.db().collection('devices').find({}).toArray(function(err, docs) { - should.not.exist(err); - docs.length.should.equal(1); - done(); - }); + it("should migrate just the subservice's devices", function (done) { + migration.migrate(config, 'iotOrigin', 'iotTarget', 'smart_gondor', '/gardens', function () { + targetDb + .db() + .collection('devices') + .find({}) + .toArray(function (err, docs) { + should.not.exist(err); + docs.length.should.equal(1); + done(); + }); }); }); }); - describe('When a subservice migration configuration has a protocol translation table', function() { - var config = { + describe('When a subservice migration configuration has a protocol translation table', function () { + const config = { host: 'localhost', port: '27017', protocols: { @@ -204,14 +238,18 @@ describe('MongoDB migration', function() { } }; - it('should change the protocol to the translated one', function(done) { - migration.migrate(config, 'iotOrigin', 'iotTarget', 'smart_gondor', '/gardens', function() { - targetDb.db().collection('devices').find({}).toArray(function(err, docs) { - should.not.exist(err); - docs.length.should.equal(1); - docs[0].protocol.should.equal('NODE-Ultralight'); - done(); - }); + it('should change the protocol to the translated one', function (done) { + migration.migrate(config, 'iotOrigin', 'iotTarget', 'smart_gondor', '/gardens', function () { + targetDb + .db() + .collection('devices') + .find({}) + .toArray(function (err, docs) { + should.not.exist(err); + docs.length.should.equal(1); + docs[0].protocol.should.equal('NODE-Ultralight'); + done(); + }); }); }); }); diff --git a/test/unit/general/startup-test.js b/test/unit/general/startup-test.js index 7b896cb37..c9867da85 100644 --- a/test/unit/general/startup-test.js +++ b/test/unit/general/startup-test.js @@ -20,56 +20,58 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - should = require('should'), - nock = require('nock'), - utils = require('../../tools/utils'), - config = require('../../../lib/commonConfig'), - _ = require('underscore'), - iotAgentConfig = { - logLevel: 'ERROR', - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - attributes: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - } - }, - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' +/* eslint-disable no-unused-vars */ +/* eslint-disable no-unused-expressions */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const should = require('should'); +const nock = require('nock'); +const utils = require('../../tools/utils'); +const config = require('../../../lib/commonConfig'); +const _ = require('underscore'); +const iotAgentConfig = { + logLevel: 'ERROR', + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + attributes: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] + } }, - iotAgentConfigNoUrl = _.clone(iotAgentConfig), - iotAgentConfigNoTypes = _.clone(iotAgentConfig), - iotamMock; + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; +const iotAgentConfigNoUrl = _.clone(iotAgentConfig); +const iotAgentConfigNoTypes = _.clone(iotAgentConfig); +let iotamMock; -describe('NGSI-v1 - Startup tests', function() { - describe('When the IoT Agent is started without a "providerUrl" config parameter', function() { - beforeEach(function() { +describe('NGSI-v1 - Startup tests', function () { + describe('When the IoT Agent is started without a "providerUrl" config parameter', function () { + beforeEach(function () { delete iotAgentConfigNoUrl.providerUrl; }); - it('should not start and raise a MISSING_CONFIG_PARAMS error', function(done) { - iotAgentLib.activate(iotAgentConfigNoUrl, function(error) { + it('should not start and raise a MISSING_CONFIG_PARAMS error', function (done) { + iotAgentLib.activate(iotAgentConfigNoUrl, function (error) { should.exist(error); should.exist(error.name); error.name.should.equal('MISSING_CONFIG_PARAMS'); @@ -77,13 +79,13 @@ describe('NGSI-v1 - Startup tests', function() { }); }); }); - describe('When the IoT Agent is started without a "types" attribute', function() { - beforeEach(function() { + describe('When the IoT Agent is started without a "types" attribute', function () { + beforeEach(function () { delete iotAgentConfigNoTypes.types; }); - it('should not start and raise a MISSING_CONFIG_PARAMS error', function(done) { - iotAgentLib.activate(iotAgentConfigNoTypes, function(error) { + it('should not start and raise a MISSING_CONFIG_PARAMS error', function (done) { + iotAgentLib.activate(iotAgentConfigNoTypes, function (error) { should.exist(error); should.exist(error.name); error.name.should.equal('MISSING_CONFIG_PARAMS'); @@ -91,8 +93,8 @@ describe('NGSI-v1 - Startup tests', function() { }); }); }); - describe('When the IoT Agent is started with environment variables', function() { - beforeEach(function() { + describe('When the IoT Agent is started with environment variables', function () { + beforeEach(function () { process.env.IOTA_CB_HOST = 'cbhost'; process.env.IOTA_CB_PORT = '1111'; process.env.IOTA_NORTH_HOST = 'localhost'; @@ -119,7 +121,7 @@ describe('NGSI-v1 - Startup tests', function() { .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); }); - afterEach(function() { + afterEach(function () { delete process.env.IOTA_CB_HOST; delete process.env.IOTA_CB_PORT; delete process.env.IOTA_NORTH_HOST; @@ -140,12 +142,12 @@ describe('NGSI-v1 - Startup tests', function() { delete process.env.IOTA_DEFAULT_RESOURCE; }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); }); - it('should not start and raise a MISSING_CONFIG_PARAMS error', function(done) { - iotAgentLib.activate(iotAgentConfig, function(error) { + it('should not start and raise a MISSING_CONFIG_PARAMS error', function (done) { + iotAgentLib.activate(iotAgentConfig, function (error) { config.getConfig().contextBroker.url.should.equal('http://cbhost:1111'); config.getConfig().server.host.should.equal('localhost'); config.getConfig().server.port.should.equal('2222'); @@ -167,8 +169,8 @@ describe('NGSI-v1 - Startup tests', function() { }); }); - describe('When the IoT Agent is started with mongodb params', function() { - beforeEach(function() { + describe('When the IoT Agent is started with mongodb params', function () { + beforeEach(function () { process.env.IOTA_MONGO_HOST = 'mongohost'; process.env.IOTA_MONGO_PORT = '5555'; process.env.IOTA_MONGO_DB = 'themongodb'; @@ -186,7 +188,7 @@ describe('NGSI-v1 - Startup tests', function() { .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); }); - afterEach(function() { + afterEach(function () { delete process.env.IOTA_MONGO_HOST; delete process.env.IOTA_MONGO_PORT; delete process.env.IOTA_MONGO_DB; @@ -200,11 +202,11 @@ describe('NGSI-v1 - Startup tests', function() { delete process.env.IOTA_MONGO_EXTRAARGS; }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); }); - ['true', 'True', 'TRUE'].forEach(function(t) { + ['true', 'True', 'TRUE'].forEach(function (t) { it('should load ssl=ture with ssl=' + t, function (done) { process.env.IOTA_MONGO_SSL = t; @@ -225,7 +227,7 @@ describe('NGSI-v1 - Startup tests', function() { }); }); - ['false', 'False', 'FALSE', 'invalid'].forEach(function(t) { + ['false', 'False', 'FALSE', 'invalid'].forEach(function (t) { it('should load ssl=false with ssl=' + t, function (done) { process.env.IOTA_MONGO_SSL = t; @@ -246,7 +248,7 @@ describe('NGSI-v1 - Startup tests', function() { }); }); - ['', 'undefined'].forEach(function(t) { + ['', 'undefined'].forEach(function (t) { it('should load no ssl parameter with ssl=' + t, function (done) { if (t !== 'undefined') { process.env.IOTA_MONGO_SSL = t; @@ -270,11 +272,14 @@ describe('NGSI-v1 - Startup tests', function() { }); [ - {in: '{"a": "b"}', expect: {a: 'b'}}, - {in: '{"a": "b", "c": "d"}', expect: {a: 'b', c: 'd'}}, - {in: '{"a": "b", "c": [1, 2], "d": -5, "e": {"f": "g"}}', expect: {a: 'b', c: [1, 2], d: -5, e: {f: 'g'}}}, - {in: '{}', expect: {}} - ].forEach(function(param) { + { in: '{"a": "b"}', expect: { a: 'b' } }, + { in: '{"a": "b", "c": "d"}', expect: { a: 'b', c: 'd' } }, + { + in: '{"a": "b", "c": [1, 2], "d": -5, "e": {"f": "g"}}', + expect: { a: 'b', c: [1, 2], d: -5, e: { f: 'g' } } + }, + { in: '{}', expect: {} } + ].forEach(function (param) { it('should load estraArgs with param=' + param.in, function (done) { process.env.IOTA_MONGO_EXTRAARGS = param.in; @@ -295,7 +300,7 @@ describe('NGSI-v1 - Startup tests', function() { }); }); - ['', 'str', '[]'].forEach(function(param) { + ['', 'str', '[]'].forEach(function (param) { it('should not load estraArgs with param=' + param, function (done) { process.env.IOTA_MONGO_EXTRAARGS = param; diff --git a/test/unit/general/statistics-persistence_test.js b/test/unit/general/statistics-persistence_test.js index 819ea948c..947a6e899 100644 --- a/test/unit/general/statistics-persistence_test.js +++ b/test/unit/general/statistics-persistence_test.js @@ -20,92 +20,98 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; -var statsService = require('../../../lib/services/stats/statsRegistry'), - commonConfig = require('../../../lib/commonConfig'), - iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - should = require('should'), - async = require('async'), - mongoUtils = require('../mongodb/mongoDBUtils'), - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041, - baseRoot: '/' - }, - stats: { - interval: 50, - persistence: true - }, - mongodb: { - host: 'localhost', - port: '27017', - db: 'iotagent' - }, - types: {}, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }, - iotAgentDb, - oldConfig; +/* eslint-disable no-unused-vars */ -describe('Statistics persistence service', function() { +const statsService = require('../../../lib/services/stats/statsRegistry'); +const commonConfig = require('../../../lib/commonConfig'); +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const should = require('should'); +const async = require('async'); +const mongoUtils = require('../mongodb/mongoDBUtils'); +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041, + baseRoot: '/' + }, + stats: { + interval: 50, + persistence: true + }, + mongodb: { + host: 'localhost', + port: '27017', + db: 'iotagent' + }, + types: {}, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; +let iotAgentDb; +let oldConfig; +describe('Statistics persistence service', function () { function insertDummy(n, callback) { - iotAgentDb.collection('tests').insertOne({test: 'test'}, function() { + iotAgentDb.collection('tests').insertOne({ test: 'test' }, function () { callback(); }); } - beforeEach(function(done) { + beforeEach(function (done) { oldConfig = commonConfig.getConfig(); - iotAgentLib.activate(iotAgentConfig, function(error) { - statsService.globalLoad({}, function() { + iotAgentLib.activate(iotAgentConfig, function (error) { + statsService.globalLoad({}, function () { iotAgentDb = require('../../../lib/model/dbConn').db; - async.times(10, insertDummy, function() { + async.times(10, insertDummy, function () { done(); }); }); }); }); - afterEach(function(done) { - iotAgentLib.deactivate(function(error) { + afterEach(function (done) { + iotAgentLib.deactivate(function (error) { commonConfig.setConfig(oldConfig); - statsService.globalLoad({}, function() { + statsService.globalLoad({}, function () { mongoUtils.cleanDbs(done); }); }); }); - describe('When a periodic persitence action is set', function() { - beforeEach(function(done) { - statsService.globalLoad({ - stat1: 10 - }, function() { - statsService.add('stat1', 5, done); - }); + describe('When a periodic persitence action is set', function () { + beforeEach(function (done) { + statsService.globalLoad( + { + stat1: 10 + }, + function () { + statsService.add('stat1', 5, done); + } + ); }); - it('should store all the records in the database', function(done) { - statsService.addTimerAction(statsService.mongodbPersistence, function() { - setTimeout(function() { - statsService.clearTimers(function() { - iotAgentDb.collection('kpis').find({}).toArray(function(err, docs) { - should.not.exist(err); - should.exist(docs); - docs.length.should.be.above(2); - done(); - }); + it('should store all the records in the database', function (done) { + statsService.addTimerAction(statsService.mongodbPersistence, function () { + setTimeout(function () { + statsService.clearTimers(function () { + iotAgentDb + .collection('kpis') + .find({}) + .toArray(function (err, docs) { + should.not.exist(err); + should.exist(docs); + docs.length.should.be.above(2); + done(); + }); }); }, 200); }); diff --git a/test/unit/general/statistics-service_test.js b/test/unit/general/statistics-service_test.js index f29c3670d..d6c6d2d30 100644 --- a/test/unit/general/statistics-service_test.js +++ b/test/unit/general/statistics-service_test.js @@ -20,60 +20,62 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; -var statsService = require('../../../lib/services/stats/statsRegistry'), - should = require('should'), - commonConfig = require('../../../lib/commonConfig'), - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041, - baseRoot: '/' - }, - stats: { - interval: 100 - }, - types: {}, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' +const statsService = require('../../../lib/services/stats/statsRegistry'); +const should = require('should'); +const commonConfig = require('../../../lib/commonConfig'); +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026' }, - oldConfig; + server: { + port: 4041, + baseRoot: '/' + }, + stats: { + interval: 100 + }, + types: {}, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; +let oldConfig; -describe('Statistics service', function() { - beforeEach(function(done) { +describe('Statistics service', function () { + beforeEach(function (done) { oldConfig = commonConfig.getConfig(); commonConfig.setConfig(iotAgentConfig); - statsService.globalLoad({}, function() { + statsService.globalLoad({}, function () { statsService.clearTimers(done); }); }); - afterEach(function(done) { + afterEach(function (done) { commonConfig.setConfig(oldConfig); statsService.globalLoad({}, done); }); - describe('When a new statistic is updated with add()', function() { - var statName = 'fakeStat', - statValue = 2; + describe('When a new statistic is updated with add()', function () { + const statName = 'fakeStat'; + const statValue = 2; - beforeEach(function(done) { - statsService.globalLoad({ - fakeStat: 30 - }, done); + beforeEach(function (done) { + statsService.globalLoad( + { + fakeStat: 30 + }, + done + ); }); - it('should appear the modified value in the getCurrent() statistics', function(done) { - statsService.add(statName, statValue, function() { - statsService.getCurrent(statName, function(error, value) { + it('should appear the modified value in the getCurrent() statistics', function (done) { + statsService.add(statName, statValue, function () { + statsService.getCurrent(statName, function (error, value) { should.not.exist(error); should.exist(value); value.should.equal(statValue); @@ -81,9 +83,9 @@ describe('Statistics service', function() { }); }); }); - it('should add the value to the global values', function(done) { - statsService.add(statName, statValue, function() { - statsService.getGlobal(statName, function(error, value) { + it('should add the value to the global values', function (done) { + statsService.add(statName, statValue, function () { + statsService.getGlobal(statName, function (error, value) { should.not.exist(error); should.exist(value); value.should.equal(30 + statValue); @@ -92,16 +94,19 @@ describe('Statistics service', function() { }); }); }); - describe('When the global statistics are requested', function() { - beforeEach(function(done) { - statsService.globalLoad({ - stat1: 82, - stat2: 38789 - }, done); + describe('When the global statistics are requested', function () { + beforeEach(function (done) { + statsService.globalLoad( + { + stat1: 82, + stat2: 38789 + }, + done + ); }); - it('should return all the statistics that were created', function(done) { - statsService.getAllGlobal(function(error, stats) { + it('should return all the statistics that were created', function (done) { + statsService.getAllGlobal(function (error, stats) { should.not.exist(error); should.exist(stats); should.exist(stats.stat1); @@ -113,18 +118,18 @@ describe('Statistics service', function() { }); }); }); - describe('When the current statistics are reset', function() { - beforeEach(function(done) { - statsService.add('statA', 42, function() { + describe('When the current statistics are reset', function () { + beforeEach(function (done) { + statsService.add('statA', 42, function () { statsService.add('statB', 52, done); }); }); - it('should return a value of zero for any of the individual statistics', function(done) { - statsService.resetCurrent(function(error) { + it('should return a value of zero for any of the individual statistics', function (done) { + statsService.resetCurrent(function (error) { should.not.exist(error); - statsService.getAllCurrent(function(error, data) { + statsService.getAllCurrent(function (error, data) { should.exist(data); should.exist(data.statA); should.exist(data.statB); @@ -135,17 +140,20 @@ describe('Statistics service', function() { }); }); }); - describe('When a new periodic stats action is set', function() { - var valueCurrent = 0, - valueGlobal = 0, - times = 0; + describe('When a new periodic stats action is set', function () { + let valueCurrent = 0; + let valueGlobal = 0; + let times = 0; - beforeEach(function(done) { - statsService.globalLoad({ - stat1: 10 - }, function() { - statsService.add('stat1', 5, done); - }); + beforeEach(function (done) { + statsService.globalLoad( + { + stat1: 10 + }, + function () { + statsService.add('stat1', 5, done); + } + ); }); function mockedAction(current, global, callback) { @@ -155,10 +163,10 @@ describe('Statistics service', function() { callback(); } - it('should be triggered with the periodicity stated in the config.stats.interval parameter', function(done) { - statsService.addTimerAction(mockedAction, function() { - setTimeout(function() { - statsService.clearTimers(function() { + it('should be triggered with the periodicity stated in the config.stats.interval parameter', function (done) { + statsService.addTimerAction(mockedAction, function () { + setTimeout(function () { + statsService.clearTimers(function () { valueCurrent.should.equal(5); valueGlobal.should.equal(15); times.should.equal(4); diff --git a/test/unit/lazyAndCommands/active-devices-attribute-update-test.js b/test/unit/lazyAndCommands/active-devices-attribute-update-test.js index 65cc544b2..8b9a20b21 100644 --- a/test/unit/lazyAndCommands/active-devices-attribute-update-test.js +++ b/test/unit/lazyAndCommands/active-devices-attribute-update-test.js @@ -20,51 +20,51 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - mongoUtils = require('../mongodb/mongoDBUtils'), - request = require('request'), - contextBrokerMock, - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - // commands are not defined - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }, - device = { - id: 'somelight', - type: 'Light', - service: 'smartGondor', - subservice: 'gardens' - }; +/* eslint-disable no-unused-vars */ -describe('NGSI-v1 - Update attribute functionalities', function() { +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +const mongoUtils = require('../mongodb/mongoDBUtils'); +const request = require('request'); +let contextBrokerMock; +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + // commands are not defined + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; +const device = { + id: 'somelight', + type: 'Light', + service: 'smartGondor', + subservice: 'gardens' +}; - beforeEach(function(done) { +describe('NGSI-v1 - Update attribute functionalities', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); nock.cleanAll(); @@ -73,23 +73,27 @@ describe('NGSI-v1 - Update attribute functionalities', function() { .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/NGSI9/registerContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json') + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { - iotAgentLib.deactivate(function() { - mongoUtils.cleanDbs(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { + iotAgentLib.deactivate(function () { + mongoUtils.cleanDbs(function () { nock.cleanAll(); iotAgentLib.setDataUpdateHandler(); iotAgentLib.setCommandHandler(); @@ -99,8 +103,8 @@ describe('NGSI-v1 - Update attribute functionalities', function() { }); }); - describe('When a attribute update arrives to the IoT Agent as Context Provider', function() { - var options = { + describe('When a attribute update arrives to the IoT Agent as Context Provider', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/updateContext', method: 'POST', json: { @@ -126,8 +130,8 @@ describe('NGSI-v1 - Update attribute functionalities', function() { } }; - beforeEach(function(done) { - iotAgentLib.register(device, function(error) { + beforeEach(function (done) { + iotAgentLib.register(device, function (error) { if (error) { done('Device registration failed'); } @@ -135,10 +139,10 @@ describe('NGSI-v1 - Update attribute functionalities', function() { }); }); - it('should call the client handler with correct values, even if commands are not defined', function(done) { - var handlerCalled = false; + it('should call the client handler with correct values, even if commands are not defined', function (done) { + let handlerCalled = false; - iotAgentLib.setDataUpdateHandler(function(id, type, service, subservice, attributes, callback) { + iotAgentLib.setDataUpdateHandler(function (id, type, service, subservice, attributes, callback) { id.should.equal('Light:somelight'); type.should.equal('Light'); should.exist(attributes); @@ -148,14 +152,13 @@ describe('NGSI-v1 - Update attribute functionalities', function() { handlerCalled = true; callback(null, { - id: id, - type: type, - attributes: attributes + id, + type, + attributes }); }); - - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); handlerCalled.should.equal(true); done(); diff --git a/test/unit/lazyAndCommands/command-test.js b/test/unit/lazyAndCommands/command-test.js index ea5473100..998a12377 100644 --- a/test/unit/lazyAndCommands/command-test.js +++ b/test/unit/lazyAndCommands/command-test.js @@ -20,95 +20,95 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - mongoUtils = require('../mongodb/mongoDBUtils'), - request = require('request'), - contextBrokerMock, - statusAttributeMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +const mongoUtils = require('../mongodb/mongoDBUtils'); +const request = require('request'); +let contextBrokerMock; +let statusAttributeMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - server: { - port: 4041 + Termometer: { + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [] }, - types: { - 'Light': { - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'Termometer': { - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ] - }, - 'Motion': { - commands: [], - lazy: [ - { - name: 'moving', - type: 'Boolean' - } - ], - staticAttributes: [ - { - 'name': 'location', - 'type': 'Vector', - 'value': '(123,523)' - } - ], - active: [] - }, - 'Robot': { - commands: [ - { - name: 'position', - type: 'Array' - } - ], - lazy: [], - staticAttributes: [], - active: [] - } + Motion: { + commands: [], + lazy: [ + { + name: 'moving', + type: 'Boolean' + } + ], + staticAttributes: [ + { + name: 'location', + type: 'Vector', + value: '(123,523)' + } + ], + active: [] }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' + Robot: { + commands: [ + { + name: 'position', + type: 'Array' + } + ], + lazy: [], + staticAttributes: [], + active: [] + } }, - device3 = { - id: 'r2d2', - type: 'Robot', - service: 'smartGondor', - subservice: 'gardens' - }; + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; +const device3 = { + id: 'r2d2', + type: 'Robot', + service: 'smartGondor', + subservice: 'gardens' +}; -describe('NGSI-v1 - Command functionalities', function() { - beforeEach(function(done) { +describe('NGSI-v1 - Command functionalities', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); nock.cleanAll(); @@ -116,27 +116,32 @@ describe('NGSI-v1 - Command functionalities', function() { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/NGSI9/registerContext', - utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgentCommands.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgentCommands.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json') + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { - delete(device3.registrationId); - iotAgentLib.clearAll(function() { - iotAgentLib.deactivate(function() { - mongoUtils.cleanDbs(function() { + afterEach(function (done) { + delete device3.registrationId; + iotAgentLib.clearAll(function () { + iotAgentLib.deactivate(function () { + mongoUtils.cleanDbs(function () { nock.cleanAll(); iotAgentLib.setDataUpdateHandler(); iotAgentLib.setCommandHandler(); @@ -146,17 +151,17 @@ describe('NGSI-v1 - Command functionalities', function() { }); }); - describe('When a device is preregistered with commands', function() { - it('should register as Context Provider of the commands', function(done) { - iotAgentLib.register(device3, function(error) { + describe('When a device is preregistered with commands', function () { + it('should register as Context Provider of the commands', function (done) { + iotAgentLib.register(device3, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - describe('When a command update arrives to the IoT Agent as Context Provider', function() { - var options = { + describe('When a command update arrives to the IoT Agent as Context Provider', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/updateContext', method: 'POST', json: { @@ -182,32 +187,38 @@ describe('NGSI-v1 - Command functionalities', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { statusAttributeMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContextCommandStatus.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContextCommandStatusSuccess.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextCommandStatus.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextCommandStatusSuccess.json' + ) + ); - iotAgentLib.register(device3, function(error) { + iotAgentLib.register(device3, function (error) { done(); }); }); - it('should call the client handler', function(done) { - var handlerCalled = false; + it('should call the client handler', function (done) { + let handlerCalled = false; - iotAgentLib.setCommandHandler(function(id, type, service, subservice, attributes, callback) { + iotAgentLib.setCommandHandler(function (id, type, service, subservice, attributes, callback) { id.should.equal(device3.type + ':' + device3.id); type.should.equal(device3.type); attributes[0].name.should.equal('position'); attributes[0].value.should.equal('[28, -104, 23]'); handlerCalled = true; callback(null, { - id: id, - type: type, + id, + type, attributes: [ { name: 'position', @@ -218,17 +229,17 @@ describe('NGSI-v1 - Command functionalities', function() { }); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); handlerCalled.should.equal(true); done(); }); }); - it('should create the attribute with the "_status" prefix in the Context Broker', function(done) { - iotAgentLib.setCommandHandler(function(id, type, service, subservice, attributes, callback) { + it('should create the attribute with the "_status" prefix in the Context Broker', function (done) { + iotAgentLib.setCommandHandler(function (id, type, service, subservice, attributes, callback) { callback(null, { - id: id, - type: type, + id, + type, attributes: [ { name: 'position', @@ -239,20 +250,20 @@ describe('NGSI-v1 - Command functionalities', function() { }); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); statusAttributeMock.done(); done(); }); }); - it('should create the attribute with the "_status" prefix in the Context Broker', function(done) { - var serviceAndSubservice = false; + it('should create the attribute with the "_status" prefix in the Context Broker', function (done) { + let serviceAndSubservice = false; - iotAgentLib.setCommandHandler(function(id, type, service, subservice, attributes, callback) { + iotAgentLib.setCommandHandler(function (id, type, service, subservice, attributes, callback) { serviceAndSubservice = service === 'smartGondor' && subservice === 'gardens'; callback(null, { - id: id, - type: type, + id, + type, attributes: [ { name: 'position', @@ -263,58 +274,68 @@ describe('NGSI-v1 - Command functionalities', function() { }); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { serviceAndSubservice.should.equal(true); done(); }); }); }); - describe('When an update arrives from the south bound for a registered command', function() { - beforeEach(function(done) { + describe('When an update arrives from the south bound for a registered command', function () { + beforeEach(function (done) { statusAttributeMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContextCommandFinish.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContextCommandFinishSuccess.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextCommandFinish.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextCommandFinishSuccess.json' + ) + ); - iotAgentLib.register(device3, function(error) { + iotAgentLib.register(device3, function (error) { done(); }); }); - it('should update its value and status in the Context Broker', function(done) { - iotAgentLib.setCommandResult('r2d2', 'Robot', '', 'position', '[72, 368, 1]', 'FINISHED', - function(error) { - should.not.exist(error); - statusAttributeMock.done(); - done(); - }); + it('should update its value and status in the Context Broker', function (done) { + iotAgentLib.setCommandResult('r2d2', 'Robot', '', 'position', '[72, 368, 1]', 'FINISHED', function (error) { + should.not.exist(error); + statusAttributeMock.done(); + done(); + }); }); }); - describe('When an error command arrives from the south bound for a registered command', function() { - beforeEach(function(done) { + describe('When an error command arrives from the south bound for a registered command', function () { + beforeEach(function (done) { statusAttributeMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContextCommandError.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContextCommandStatusSuccess.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextCommandError.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextCommandStatusSuccess.json' + ) + ); - iotAgentLib.register(device3, function(error) { + iotAgentLib.register(device3, function (error) { done(); }); }); - it('should update its status in the Context Broker', function(done) { - iotAgentLib.setCommandResult('r2d2', 'Robot', '', 'position', 'Stalled', 'ERROR', - function(error) { - should.not.exist(error); - statusAttributeMock.done(); - done(); - }); + it('should update its status in the Context Broker', function (done) { + iotAgentLib.setCommandResult('r2d2', 'Robot', '', 'position', 'Stalled', 'ERROR', function (error) { + should.not.exist(error); + statusAttributeMock.done(); + done(); + }); }); }); }); diff --git a/test/unit/lazyAndCommands/commandRegistry_test.js b/test/unit/lazyAndCommands/commandRegistry_test.js index 57594f076..434ea0527 100644 --- a/test/unit/lazyAndCommands/commandRegistry_test.js +++ b/test/unit/lazyAndCommands/commandRegistry_test.js @@ -20,69 +20,70 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - async = require('async'), - should = require('should'), - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - name: 'testAgent', - port: 4041, - baseRoot: '/' - }, - types: {}, - deviceRegistry: { - type: 'memory' - }, - mongodb: { - host: 'localhost', - port: '27017', - db: 'iotagent' - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M', - pollingExpiration: 800, - pollingDaemonFrequency: 20 - }; + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const async = require('async'); +const should = require('should'); +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + name: 'testAgent', + port: 4041, + baseRoot: '/' + }, + types: {}, + deviceRegistry: { + type: 'memory' + }, + mongodb: { + host: 'localhost', + port: '27017', + db: 'iotagent' + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M', + pollingExpiration: 800, + pollingDaemonFrequency: 20 +}; function testRegistry(registryType) { - describe('Command registries test [' + registryType + ']', function() { - var commandTemplate = { + describe('Command registries test [' + registryType + ']', function () { + const commandTemplate = { name: 'commandName', type: 'commandType', value: 'commandValue' }; - beforeEach(function(done) { + beforeEach(function (done) { iotAgentConfig.deviceRegistry.type = registryType; iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When a new command is created in the command registry', function() { - it('should not cause any error', function(done) { - iotAgentLib.addCommand('smartGondor', 'gardens', 'devId', commandTemplate, function(error) { + describe('When a new command is created in the command registry', function () { + it('should not cause any error', function (done) { + iotAgentLib.addCommand('smartGondor', 'gardens', 'devId', commandTemplate, function (error) { should.not.exist(error); done(); }); }); - it('should appear in the listings', function(done) { - iotAgentLib.addCommand('smartGondor', 'gardens', 'devId', commandTemplate, function(error) { - iotAgentLib.commandQueue('smartGondor', 'gardens', 'devId', function(error, commandList) { + it('should appear in the listings', function (done) { + iotAgentLib.addCommand('smartGondor', 'gardens', 'devId', commandTemplate, function (error) { + iotAgentLib.commandQueue('smartGondor', 'gardens', 'devId', function (error, commandList) { commandList.count.should.equal(1); commandList.commands[0].name.should.equal('commandName'); commandList.commands[0].type.should.equal('commandType'); @@ -93,11 +94,11 @@ function testRegistry(registryType) { }); }); - describe('When a new command has expired from the registry', function() { - it('should not appear in the listings', function(done) { - iotAgentLib.addCommand('smartGondor', 'gardens', 'devId', commandTemplate, function(error) { - setTimeout(function() { - iotAgentLib.commandQueue('smartGondor', 'gardens', 'devId', function(error, commandList) { + describe('When a new command has expired from the registry', function () { + it('should not appear in the listings', function (done) { + iotAgentLib.addCommand('smartGondor', 'gardens', 'devId', commandTemplate, function (error) { + setTimeout(function () { + iotAgentLib.commandQueue('smartGondor', 'gardens', 'devId', function (error, commandList) { commandList.count.should.equal(0); done(); }); @@ -106,27 +107,27 @@ function testRegistry(registryType) { }); }); - describe('When an already existing command arrives to the registry', function() { - var updatedCommand = { + describe('When an already existing command arrives to the registry', function () { + const updatedCommand = { name: 'commandName', type: 'commandType', value: 'newValueForTheCommand' }; - beforeEach(function(done) { + beforeEach(function (done) { iotAgentLib.addCommand('smartGondor', 'gardens', 'devId', commandTemplate, done); }); - it('should not give any error', function(done) { - iotAgentLib.addCommand('smartGondor', 'gardens', 'devId', updatedCommand, function(error) { + it('should not give any error', function (done) { + iotAgentLib.addCommand('smartGondor', 'gardens', 'devId', updatedCommand, function (error) { should.not.exist(error); done(); }); }); - it('should override the old value, and change the expiration time', function(done) { - iotAgentLib.addCommand('smartGondor', 'gardens', 'devId', updatedCommand, function(error) { - iotAgentLib.commandQueue('smartGondor', 'gardens', 'devId', function(error, list) { + it('should override the old value, and change the expiration time', function (done) { + iotAgentLib.addCommand('smartGondor', 'gardens', 'devId', updatedCommand, function (error) { + iotAgentLib.commandQueue('smartGondor', 'gardens', 'devId', function (error, list) { list.count.should.equal(1); list.commands[0].value.should.equal('newValueForTheCommand'); done(); @@ -135,40 +136,34 @@ function testRegistry(registryType) { }); }); - describe('When a command listing is requested for a device', function() { - beforeEach(function(done) { - var commands = []; + describe('When a command listing is requested for a device', function () { + beforeEach(function (done) { + const commands = []; - for (var i = 0; i < 3; i++) { - for (var j = 0; j < 5; j++) { - var newCommand = { + for (let i = 0; i < 3; i++) { + for (let j = 0; j < 5; j++) { + const newCommand = { name: commandTemplate.name + j, type: commandTemplate.type + j, value: commandTemplate.value + j }; commands.push( - async.apply( - iotAgentLib.addCommand, - 'smartGondor', - 'gardens', - 'devId' + i, - newCommand - ) + async.apply(iotAgentLib.addCommand, 'smartGondor', 'gardens', 'devId' + i, newCommand) ); } } - async.series(commands, function(error) { + async.series(commands, function (error) { done(); }); }); - it('should not return any command for other devices', function(done) { - iotAgentLib.commandQueue('smartGondor', 'gardens', 'devId1', function(error, commandList) { + it('should not return any command for other devices', function (done) { + iotAgentLib.commandQueue('smartGondor', 'gardens', 'devId1', function (error, commandList) { commandList.count.should.equal(5); - for (var i = 0; i < 5; i++) { + for (let i = 0; i < 5; i++) { commandList.commands[i].deviceId.should.equal('devId1'); } @@ -176,11 +171,11 @@ function testRegistry(registryType) { }); }); - it('should return all the fields for each command', function(done) { - iotAgentLib.commandQueue('smartGondor', 'gardens', 'devId1', function(error, commandList) { + it('should return all the fields for each command', function (done) { + iotAgentLib.commandQueue('smartGondor', 'gardens', 'devId1', function (error, commandList) { commandList.count.should.equal(5); - for (var i = 0; i < 5; i++) { + for (let i = 0; i < 5; i++) { commandList.commands[i].name.should.equal('commandName' + i); commandList.commands[i].type.should.equal('commandType' + i); commandList.commands[i].value.should.equal('commandValue' + i); @@ -195,39 +190,31 @@ function testRegistry(registryType) { }); }); - describe('When a command is removed from the queue', function() { - beforeEach(function(done) { - var commands = []; + describe('When a command is removed from the queue', function () { + beforeEach(function (done) { + const commands = []; - for (var j = 0; j < 5; j++) { - var newCommand = { + for (let j = 0; j < 5; j++) { + const newCommand = { name: commandTemplate.name + j, type: commandTemplate.type + j, value: commandTemplate.value + j }; - commands.push( - async.apply( - iotAgentLib.addCommand, - 'smartGondor', - 'gardens', - 'devId', - newCommand - ) - ); + commands.push(async.apply(iotAgentLib.addCommand, 'smartGondor', 'gardens', 'devId', newCommand)); } - async.series(commands, function(error) { + async.series(commands, function (error) { done(); }); }); - it('should not appear in the listings', function(done) { - iotAgentLib.removeCommand('smartGondor', 'gardens', 'devId', 'commandName2', function(error) { - iotAgentLib.commandQueue('smartGondor', 'gardens', 'devId', function(error, commandList) { + it('should not appear in the listings', function (done) { + iotAgentLib.removeCommand('smartGondor', 'gardens', 'devId', 'commandName2', function (error) { + iotAgentLib.commandQueue('smartGondor', 'gardens', 'devId', function (error, commandList) { commandList.commands.length.should.equal(4); - for (var i = 0; i < commandList.commands.length; i++) { + for (let i = 0; i < commandList.commands.length; i++) { commandList.commands[i].name.should.not.equal('commandName2'); } diff --git a/test/unit/lazyAndCommands/lazy-devices-test.js b/test/unit/lazyAndCommands/lazy-devices-test.js index c21a19583..50f24cba4 100644 --- a/test/unit/lazyAndCommands/lazy-devices-test.js +++ b/test/unit/lazyAndCommands/lazy-devices-test.js @@ -20,143 +20,143 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - async = require('async'), - apply = async.apply, - should = require('should'), - logger = require('logops'), - nock = require('nock'), - mongoUtils = require('../mongodb/mongoDBUtils'), - request = require('request'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const async = require('async'); +const apply = async.apply; +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +const mongoUtils = require('../mongodb/mongoDBUtils'); +const request = require('request'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - server: { - port: 4041 + Termometer: { + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [] }, - types: { - 'Light': { - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'Termometer': { - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ] - }, - 'Motion': { - commands: [], - lazy: [ - { - name: 'moving', - type: 'Boolean' - } - ], - staticAttributes: [ - { - 'name': 'location', - 'type': 'Vector', - 'value': '(123,523)' - } - ], - active: [] - }, - 'RobotPre': { - commands: [], - lazy: [ - { - name: 'moving', - type: 'Boolean' - } - ], - staticAttributes: [], - attributes: [], - internalAttributes: { - lwm2mResourceMapping: { - position: { - objectType: 9090, - objectInstance: 0, - objectResource: 0 - } + Motion: { + commands: [], + lazy: [ + { + name: 'moving', + type: 'Boolean' + } + ], + staticAttributes: [ + { + name: 'location', + type: 'Vector', + value: '(123,523)' + } + ], + active: [] + }, + RobotPre: { + commands: [], + lazy: [ + { + name: 'moving', + type: 'Boolean' + } + ], + staticAttributes: [], + attributes: [], + internalAttributes: { + lwm2mResourceMapping: { + position: { + objectType: 9090, + objectInstance: 0, + objectResource: 0 } } } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }, - device1 = { - id: 'light1', - type: 'Light', - service: 'smartGondor', - subservice: 'gardens' - }, - device2 = { - id: 'motion1', - type: 'Motion', - service: 'smartGondor', - subservice: 'gardens' + } }, - device3 = { - id: 'TestRobotPre', - type: 'RobotPre', - service: 'smartGondor', - subservice: 'gardens', - internalAttributes: { - lwm2mResourceMapping: { - position: { - objectType: 6789, - objectInstance: 0, - objectResource: 17 - } + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; +const device1 = { + id: 'light1', + type: 'Light', + service: 'smartGondor', + subservice: 'gardens' +}; +const device2 = { + id: 'motion1', + type: 'Motion', + service: 'smartGondor', + subservice: 'gardens' +}; +const device3 = { + id: 'TestRobotPre', + type: 'RobotPre', + service: 'smartGondor', + subservice: 'gardens', + internalAttributes: { + lwm2mResourceMapping: { + position: { + objectType: 6789, + objectInstance: 0, + objectResource: 17 } } - }; + } +}; -describe('NGSI-v1 - IoT Agent Lazy Devices', function() { - beforeEach(function(done) { +describe('NGSI-v1 - IoT Agent Lazy Devices', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); mongoUtils.cleanDbs(done); iotAgentLib.setDataQueryHandler(null); }); - afterEach(function(done) { - delete(device1.registrationId); - iotAgentLib.clearAll(function() { - iotAgentLib.deactivate(function() { + afterEach(function (done) { + delete device1.registrationId; + iotAgentLib.clearAll(function () { + iotAgentLib.deactivate(function () { mongoUtils.cleanDbs(done); }); }); }); - describe('When the IoT Agent receives an update on the device data in JSON format', function() { - var options = { + describe('When the IoT Agent receives an update on the device data in JSON format', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/updateContext', method: 'POST', json: { @@ -182,43 +182,48 @@ describe('NGSI-v1 - IoT Agent Lazy Devices', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/NGSI9/registerContext', - utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); - - async.series([ - apply(iotAgentLib.activate, iotAgentConfig), - apply(iotAgentLib.register, device1) - ], done); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); + + async.series([apply(iotAgentLib.activate, iotAgentConfig), apply(iotAgentLib.register, device1)], done); }); - it('should call the device handler with the received data', function(done) { - var expectedResponse = utils - .readExampleFile('./test/unit/examples/contextProviderResponses/updateInformationResponse.json'); + it('should call the device handler with the received data', function (done) { + const expectedResponse = utils.readExampleFile( + './test/unit/examples/contextProviderResponses/updateInformationResponse.json' + ); - iotAgentLib.setDataUpdateHandler(function(id, type, service, subservice, attributes, callback) { + iotAgentLib.setDataUpdateHandler(function (id, type, service, subservice, attributes, callback) { id.should.equal(device1.type + ':' + device1.id); type.should.equal(device1.type); attributes[0].value.should.equal('12'); callback(null); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); body.should.eql(expectedResponse); done(); @@ -226,82 +231,86 @@ describe('NGSI-v1 - IoT Agent Lazy Devices', function() { }); }); - describe('When a IoT Agent receives an update on multiple contexts', function() { + describe('When a IoT Agent receives an update on multiple contexts', function () { it('should call the device handler for each of the contexts'); }); - describe('When a context query arrives to the IoT Agent', function() { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/queryContext', - method: 'POST', - json: { - entities: [ - { - type: 'Light', - isPattern: 'false', - id: 'Light:light1' - } - ], - attributes: [ - 'dimming' - ] - }, - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': 'gardens' - } + describe('When a context query arrives to the IoT Agent', function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/queryContext', + method: 'POST', + json: { + entities: [ + { + type: 'Light', + isPattern: 'false', + id: 'Light:light1' + } + ], + attributes: ['dimming'] }, - sensorData = [ - { - id: 'Light:light1', - isPattern: false, - type: 'Light', - attributes: [ - { - name: 'dimming', - type: 'Percentage', - value: '19' - } - ] - } - ]; + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': 'gardens' + } + }; + const sensorData = [ + { + id: 'Light:light1', + isPattern: false, + type: 'Light', + attributes: [ + { + name: 'dimming', + type: 'Percentage', + value: '19' + } + ] + } + ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); - async.series([ - apply(iotAgentLib.activate, iotAgentConfig), - apply(iotAgentLib.register, device1) - ], done); + async.series([apply(iotAgentLib.activate, iotAgentConfig), apply(iotAgentLib.register, device1)], done); }); - it('should return the information querying the underlying devices', function(done) { - var expectedResponse = utils - .readExampleFile('./test/unit/examples/contextProviderResponses/queryInformationResponse.json'); + it('should return the information querying the underlying devices', function (done) { + const expectedResponse = utils.readExampleFile( + './test/unit/examples/contextProviderResponses/queryInformationResponse.json' + ); - iotAgentLib.setDataQueryHandler(function(id, type, service, subservice, attributes, callback) { + iotAgentLib.setDataQueryHandler(function (id, type, service, subservice, attributes, callback) { id.should.equal(device1.type + ':' + device1.id); type.should.equal(device1.type); attributes[0].should.equal('dimming'); callback(null, sensorData[0]); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); body.should.eql(expectedResponse); done(); @@ -309,65 +318,69 @@ describe('NGSI-v1 - IoT Agent Lazy Devices', function() { }); }); - describe('When a context query arrives to the IoT Agent and no handler is set', function() { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/queryContext', - method: 'POST', - json: { - entities: [ - { - type: 'Light', - isPattern: 'false', - id: 'Light:light1' - } - ], - attributes: [ - 'dimming' - ] - }, - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': 'gardens' - } - }; + describe('When a context query arrives to the IoT Agent and no handler is set', function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/queryContext', + method: 'POST', + json: { + entities: [ + { + type: 'Light', + isPattern: 'false', + id: 'Light:light1' + } + ], + attributes: ['dimming'] + }, + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': 'gardens' + } + }; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); - - async.series([ - apply(iotAgentLib.activate, iotAgentConfig), - apply(iotAgentLib.register, device1) - ], function(error) { + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); + + async.series([apply(iotAgentLib.activate, iotAgentConfig), apply(iotAgentLib.register, device1)], function ( + error + ) { done(); }); }); - it('should not give any error', function(done) { - request(options, function(error, response, body) { + it('should not give any error', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(200); done(); }); }); - it('should return the empty value', function(done) { - request(options, function(error, response, body) { + it('should return the empty value', function (done) { + request(options, function (error, response, body) { body.contextResponses[0].contextElement.attributes[0].name.should.equal('dimming'); body.contextResponses[0].contextElement.attributes[0].value.should.equal(''); done(); @@ -375,75 +388,81 @@ describe('NGSI-v1 - IoT Agent Lazy Devices', function() { }); }); - describe('When a query arrives to the IoT Agent without any attributes', function() { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/queryContext', - method: 'POST', - json: { - entities: [ - { - type: 'Light', - isPattern: 'false', - id: 'Light:light1' - } - ] - }, - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': 'gardens' - } + describe('When a query arrives to the IoT Agent without any attributes', function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/queryContext', + method: 'POST', + json: { + entities: [ + { + type: 'Light', + isPattern: 'false', + id: 'Light:light1' + } + ] }, - sensorData = [ - { - id: 'Light:light1', - isPattern: false, - type: 'Light', - attributes: [ - { - name: 'temperature', - type: 'centigrades', - value: '19' - } - ] - } - ]; + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': 'gardens' + } + }; + const sensorData = [ + { + id: 'Light:light1', + isPattern: false, + type: 'Light', + attributes: [ + { + name: 'temperature', + type: 'centigrades', + value: '19' + } + ] + } + ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); - async.series([ - apply(iotAgentLib.activate, iotAgentConfig), - apply(iotAgentLib.register, device1) - ], done); + async.series([apply(iotAgentLib.activate, iotAgentConfig), apply(iotAgentLib.register, device1)], done); }); - it('should return the information of all the attributes', function(done) { - var expectedResponse = utils.readExampleFile( - './test/unit/examples/contextProviderResponses/queryInformationResponseEmptyAttributes.json'); + it('should return the information of all the attributes', function (done) { + const expectedResponse = utils.readExampleFile( + './test/unit/examples/contextProviderResponses/queryInformationResponseEmptyAttributes.json' + ); - iotAgentLib.setDataQueryHandler(function(id, type, service, subservice, attributes, callback) { + iotAgentLib.setDataQueryHandler(function (id, type, service, subservice, attributes, callback) { should.exist(attributes); attributes.length.should.equal(1); attributes[0].should.equal('temperature'); callback(null, sensorData[0]); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); body.should.eql(expectedResponse); done(); @@ -451,76 +470,82 @@ describe('NGSI-v1 - IoT Agent Lazy Devices', function() { }); }); - describe('When a query arrives to the IoT Agent with an empty attributes array', function() { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/queryContext', - method: 'POST', - json: { - entities: [ - { - type: 'Light', - isPattern: 'false', - id: 'Light:light1' - } - ], - attributes: [] - }, - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': 'gardens' - } + describe('When a query arrives to the IoT Agent with an empty attributes array', function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/queryContext', + method: 'POST', + json: { + entities: [ + { + type: 'Light', + isPattern: 'false', + id: 'Light:light1' + } + ], + attributes: [] }, - sensorData = [ - { - id: 'Light:light1', - isPattern: false, - type: 'Light', - attributes: [ - { - name: 'temperature', - type: 'centigrades', - value: '19' - } - ] - } - ]; + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': 'gardens' + } + }; + const sensorData = [ + { + id: 'Light:light1', + isPattern: false, + type: 'Light', + attributes: [ + { + name: 'temperature', + type: 'centigrades', + value: '19' + } + ] + } + ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); - async.series([ - apply(iotAgentLib.activate, iotAgentConfig), - apply(iotAgentLib.register, device1) - ], done); + async.series([apply(iotAgentLib.activate, iotAgentConfig), apply(iotAgentLib.register, device1)], done); }); - it('should return the information of all the attributes', function(done) { - var expectedResponse = utils.readExampleFile( - './test/unit/examples/contextProviderResponses/queryInformationResponseEmptyAttributes.json'); + it('should return the information of all the attributes', function (done) { + const expectedResponse = utils.readExampleFile( + './test/unit/examples/contextProviderResponses/queryInformationResponseEmptyAttributes.json' + ); - iotAgentLib.setDataQueryHandler(function(id, type, service, subservice, attributes, callback) { + iotAgentLib.setDataQueryHandler(function (id, type, service, subservice, attributes, callback) { should.exist(attributes); attributes.length.should.equal(1); attributes[0].should.equal('temperature'); callback(null, sensorData[0]); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); body.should.eql(expectedResponse); done(); @@ -528,71 +553,74 @@ describe('NGSI-v1 - IoT Agent Lazy Devices', function() { }); }); - describe('When a context query arrives to the IoT Agent for a type with static attributes', function() { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/queryContext', - method: 'POST', - json: { - entities: [ - { - type: 'Motion', - isPattern: 'false', - id: 'Motion:motion1' - } - ], - attributes: [ - 'moving', - 'location' - ] - }, - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': 'gardens' - } + describe('When a context query arrives to the IoT Agent for a type with static attributes', function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/queryContext', + method: 'POST', + json: { + entities: [ + { + type: 'Motion', + isPattern: 'false', + id: 'Motion:motion1' + } + ], + attributes: ['moving', 'location'] }, - sensorData = [ - { - id: 'Motion:motion1', - type: 'Motion', - attributes: [ - { - name: 'moving', - type: 'Boolean', - value: 'true' - } - ] - } - ]; + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': 'gardens' + } + }; + const sensorData = [ + { + id: 'Motion:motion1', + type: 'Motion', + attributes: [ + { + name: 'moving', + type: 'Boolean', + value: 'true' + } + ] + } + ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerIoTAgent2.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent2.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); - async.series([ - apply(iotAgentLib.activate, iotAgentConfig), - apply(iotAgentLib.register, device2) - ], done); + async.series([apply(iotAgentLib.activate, iotAgentConfig), apply(iotAgentLib.register, device2)], done); }); - it('should return the information adding the static attributes', function(done) { - var expectedResponse = utils.readExampleFile( - './test/unit/examples/contextProviderResponses/queryInformationStaticAttributesResponse.json'); + it('should return the information adding the static attributes', function (done) { + const expectedResponse = utils.readExampleFile( + './test/unit/examples/contextProviderResponses/queryInformationStaticAttributesResponse.json' + ); - iotAgentLib.setDataQueryHandler(function(id, type, service, subservice, attributes, callback) { + iotAgentLib.setDataQueryHandler(function (id, type, service, subservice, attributes, callback) { id.should.equal('Motion:motion1'); type.should.equal('Motion'); attributes[0].should.equal('moving'); @@ -600,7 +628,7 @@ describe('NGSI-v1 - IoT Agent Lazy Devices', function() { callback(null, sensorData[0]); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); body.should.eql(expectedResponse); done(); @@ -608,61 +636,69 @@ describe('NGSI-v1 - IoT Agent Lazy Devices', function() { }); }); - describe('When a context query arrives to the IoT Agent with a payload that is not JSON', function() { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/queryContext', - method: 'POST', - body: 'This is a body in text format', - headers: { - 'Content-Type': 'text/plain', - 'fiware-service': 'smartGondor', - 'fiware-servicepath': 'gardens' - } - }, - sensorData = [ - { - id: 'Light:light1', - type: 'Light', - attributes: [ - { - name: 'dimming', - type: 'Percentage', - value: '19' - } - ] - } - ]; + describe('When a context query arrives to the IoT Agent with a payload that is not JSON', function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/queryContext', + method: 'POST', + body: 'This is a body in text format', + headers: { + 'Content-Type': 'text/plain', + 'fiware-service': 'smartGondor', + 'fiware-servicepath': 'gardens' + } + }; + const sensorData = [ + { + id: 'Light:light1', + type: 'Light', + attributes: [ + { + name: 'dimming', + type: 'Percentage', + value: '19' + } + ] + } + ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); iotAgentLib.activate(iotAgentConfig, done); }); - it('should fail with a 400 error', function(done) { - var handlerCalled = false; + it('should fail with a 400 error', function (done) { + let handlerCalled = false; - iotAgentLib.setDataQueryHandler(function(id, type, service, subservice, attributes, callback) { + iotAgentLib.setDataQueryHandler(function (id, type, service, subservice, attributes, callback) { handlerCalled = true; callback(null, sensorData); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(400); handlerCalled.should.equal(false); @@ -670,16 +706,16 @@ describe('NGSI-v1 - IoT Agent Lazy Devices', function() { }); }); - it('should return an NGSI compliant payload', function(done) { - var handlerCalled = false; + it('should return an NGSI compliant payload', function (done) { + let handlerCalled = false; - iotAgentLib.setDataQueryHandler(function(id, type, service, subservice, attributes, callback) { + iotAgentLib.setDataQueryHandler(function (id, type, service, subservice, attributes, callback) { handlerCalled = true; callback(null, sensorData); }); - request(options, function(error, response, body) { - var parsedBody = JSON.parse(body); + request(options, function (error, response, body) { + const parsedBody = JSON.parse(body); should.exist(parsedBody.errorCode); parsedBody.errorCode.code.should.equal(400); parsedBody.errorCode.details.should.equal('Unsuported content type in the context request: text/plain'); @@ -690,56 +726,64 @@ describe('NGSI-v1 - IoT Agent Lazy Devices', function() { }); }); - describe('When a context query arrives to the IoT Agent with an invalid body', function() { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/queryContext', - method: 'POST', - json: {} - }, - sensorData = [ - { - id: 'Light:light1', - type: 'Light', - attributes: [ - { - name: 'dimming', - type: 'Percentage', - value: '19' - } - ] - } - ]; + describe('When a context query arrives to the IoT Agent with an invalid body', function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/queryContext', + method: 'POST', + json: {} + }; + const sensorData = [ + { + id: 'Light:light1', + type: 'Light', + attributes: [ + { + name: 'dimming', + type: 'Percentage', + value: '19' + } + ] + } + ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); iotAgentLib.activate(iotAgentConfig, done); }); - it('should fail with a 400 error', function(done) { - var handlerCalled = false; + it('should fail with a 400 error', function (done) { + let handlerCalled = false; - iotAgentLib.setDataQueryHandler(function(id, type, service, subservice, attributes, callback) { + iotAgentLib.setDataQueryHandler(function (id, type, service, subservice, attributes, callback) { handlerCalled = true; callback(null, sensorData); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(400); handlerCalled.should.equal(false); @@ -748,76 +792,85 @@ describe('NGSI-v1 - IoT Agent Lazy Devices', function() { }); }); - describe('When the IoT Agent receives an update on the device data in JSON format for a type with' + - 'internalAttributes', function() { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/updateContext', - method: 'POST', - json: { - contextElements: [ - { - type: 'RobotPre', - isPattern: 'false', - id: 'RobotPre:TestRobotPre', - attributes: [ - { - name: 'moving', - type: 'Boolean', - value: 'True' - } - ] - } - ], - updateAction: 'APPEND' - }, - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': 'gardens' - } - }; - - beforeEach(function(done) { - nock.cleanAll(); - - contextBrokerMock = nock('http://192.168.1.1:1026') - .matchHeader('fiware-service', 'smartGondor') - .matchHeader('fiware-servicepath', 'gardens') - .post('/NGSI9/registerContext', - utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent4.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); - - contextBrokerMock - .matchHeader('fiware-service', 'smartGondor') - .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); - - async.series([ - apply(iotAgentLib.activate, iotAgentConfig), - apply(iotAgentLib.register, device3) - ], done); - }); - - it('should call the device handler with the received data', function(done) { - var expectedResponse = utils - .readExampleFile('./test/unit/examples/contextProviderResponses/updateInformationResponse2.json'); + describe( + 'When the IoT Agent receives an update on the device data in JSON format for a type with' + + 'internalAttributes', + function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/updateContext', + method: 'POST', + json: { + contextElements: [ + { + type: 'RobotPre', + isPattern: 'false', + id: 'RobotPre:TestRobotPre', + attributes: [ + { + name: 'moving', + type: 'Boolean', + value: 'True' + } + ] + } + ], + updateAction: 'APPEND' + }, + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': 'gardens' + } + }; - iotAgentLib.setDataUpdateHandler(function(id, type, service, subservice, attributes, callback) { - id.should.equal(device3.type + ':' + device3.id); - type.should.equal(device3.type); - attributes[0].value.should.equal('True'); - callback(null); + beforeEach(function (done) { + nock.cleanAll(); + + contextBrokerMock = nock('http://192.168.1.1:1026') + .matchHeader('fiware-service', 'smartGondor') + .matchHeader('fiware-servicepath', 'gardens') + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent4.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json' + ) + ); + + contextBrokerMock + .matchHeader('fiware-service', 'smartGondor') + .matchHeader('fiware-servicepath', 'gardens') + .post('/v1/updateContext') + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json' + ) + ); + + async.series([apply(iotAgentLib.activate, iotAgentConfig), apply(iotAgentLib.register, device3)], done); }); - request(options, function(error, response, body) { - should.not.exist(error); - body.should.eql(expectedResponse); - done(); + it('should call the device handler with the received data', function (done) { + const expectedResponse = utils.readExampleFile( + './test/unit/examples/contextProviderResponses/updateInformationResponse2.json' + ); + + iotAgentLib.setDataUpdateHandler(function (id, type, service, subservice, attributes, callback) { + id.should.equal(device3.type + ':' + device3.id); + type.should.equal(device3.type); + attributes[0].value.should.equal('True'); + callback(null); + }); + + request(options, function (error, response, body) { + should.not.exist(error); + body.should.eql(expectedResponse); + done(); + }); }); - }); - }); - + } + ); }); diff --git a/test/unit/lazyAndCommands/polling-commands-test.js b/test/unit/lazyAndCommands/polling-commands-test.js index b138432dc..d596e81c5 100644 --- a/test/unit/lazyAndCommands/polling-commands-test.js +++ b/test/unit/lazyAndCommands/polling-commands-test.js @@ -20,107 +20,107 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - mongoUtils = require('../mongodb/mongoDBUtils'), - request = require('request'), - contextBrokerMock, - statusAttributeMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +const mongoUtils = require('../mongodb/mongoDBUtils'); +const request = require('request'); +let contextBrokerMock; +let statusAttributeMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - server: { - port: 4041 + Termometer: { + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [] }, - types: { - 'Light': { - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'Termometer': { - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ] - }, - 'Motion': { - commands: [], - lazy: [ - { - name: 'moving', - type: 'Boolean' - } - ], - staticAttributes: [ - { - 'name': 'location', - 'type': 'Vector', - 'value': '(123,523)' - } - ], - active: [] - }, - 'Robot': { - commands: [ - { - name: 'position', - type: 'Array' - } - ], - lazy: [], - staticAttributes: [], - active: [] - } - }, - deviceRegistry: { - type: 'mongodb' + Motion: { + commands: [], + lazy: [ + { + name: 'moving', + type: 'Boolean' + } + ], + staticAttributes: [ + { + name: 'location', + type: 'Vector', + value: '(123,523)' + } + ], + active: [] }, + Robot: { + commands: [ + { + name: 'position', + type: 'Array' + } + ], + lazy: [], + staticAttributes: [], + active: [] + } + }, + deviceRegistry: { + type: 'mongodb' + }, - mongodb: { - host: 'localhost', - port: '27017', - db: 'iotagent' - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M', - pollingExpiration: 200, - pollingDaemonFrequency: 20 + mongodb: { + host: 'localhost', + port: '27017', + db: 'iotagent' }, - device3 = { - id: 'r2d2', - type: 'Robot', - service: 'smartGondor', - subservice: 'gardens', - polling: true - }; - -describe('NGSI-v1 - Polling commands', function() { - beforeEach(function(done) { + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M', + pollingExpiration: 200, + pollingDaemonFrequency: 20 +}; +const device3 = { + id: 'r2d2', + type: 'Robot', + service: 'smartGondor', + subservice: 'gardens', + polling: true +}; + +describe('NGSI-v1 - Polling commands', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); nock.cleanAll(); @@ -128,30 +128,32 @@ describe('NGSI-v1 - Polling commands', function() { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/NGSI9/registerContext', - utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerIoTAgentCommands.json')) - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgentCommands.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json') + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); - + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { - delete(device3.registrationId); - iotAgentLib.clearAll(function() { - iotAgentLib.deactivate(function() { - mongoUtils.cleanDbs(function() { + afterEach(function (done) { + delete device3.registrationId; + iotAgentLib.clearAll(function () { + iotAgentLib.deactivate(function () { + mongoUtils.cleanDbs(function () { nock.cleanAll(); iotAgentLib.setDataUpdateHandler(); iotAgentLib.setCommandHandler(); @@ -161,8 +163,8 @@ describe('NGSI-v1 - Polling commands', function() { }); }); - describe('When a command update arrives to the IoT Agent for a device with polling', function() { - var options = { + describe('When a command update arrives to the IoT Agent for a device with polling', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/updateContext', method: 'POST', json: { @@ -188,29 +190,34 @@ describe('NGSI-v1 - Polling commands', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { statusAttributeMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContextCommandStatus.json')) - .reply(200, + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextCommandStatus.json') + ) + .reply( + 200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextCommandStatusSuccess.json')); + './test/unit/examples/contextResponses/updateContextCommandStatusSuccess.json' + ) + ); - iotAgentLib.register(device3, function(error) { + iotAgentLib.register(device3, function (error) { done(); }); }); - it('should not call the client handler', function(done) { - var handlerCalled = false; + it('should not call the client handler', function (done) { + let handlerCalled = false; - iotAgentLib.setCommandHandler(function(id, type, service, subservice, attributes, callback) { + iotAgentLib.setCommandHandler(function (id, type, service, subservice, attributes, callback) { handlerCalled = true; callback(null, { - id: id, - type: type, + id, + type, attributes: [ { name: 'position', @@ -221,30 +228,30 @@ describe('NGSI-v1 - Polling commands', function() { }); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); handlerCalled.should.equal(false); done(); }); }); - it('should create the attribute with the "_status" prefix in the Context Broker', function(done) { - iotAgentLib.setCommandHandler(function(id, type, service, subservice, attributes, callback) { + it('should create the attribute with the "_status" prefix in the Context Broker', function (done) { + iotAgentLib.setCommandHandler(function (id, type, service, subservice, attributes, callback) { callback(null); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); statusAttributeMock.done(); done(); }); }); - it('should store the commands in the queue', function(done) { - iotAgentLib.setCommandHandler(function(id, type, service, subservice, attributes, callback) { + it('should store the commands in the queue', function (done) { + iotAgentLib.setCommandHandler(function (id, type, service, subservice, attributes, callback) { callback(null); }); - request(options, function(error, response, body) { - iotAgentLib.commandQueue('smartGondor', 'gardens', 'r2d2', function(error, listCommands) { + request(options, function (error, response, body) { + iotAgentLib.commandQueue('smartGondor', 'gardens', 'r2d2', function (error, listCommands) { should.not.exist(error); listCommands.count.should.equal(1); listCommands.commands[0].name.should.equal('position'); @@ -256,8 +263,8 @@ describe('NGSI-v1 - Polling commands', function() { }); }); - describe('When a command arrives with multiple values in the value field', function() { - var options = { + describe('When a command arrives with multiple values in the value field', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/updateContext', method: 'POST', json: { @@ -286,27 +293,32 @@ describe('NGSI-v1 - Polling commands', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { statusAttributeMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContextCommandStatus.json')) - .reply(200, + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextCommandStatus.json') + ) + .reply( + 200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextCommandStatusSuccess.json')); + './test/unit/examples/contextResponses/updateContextCommandStatusSuccess.json' + ) + ); - iotAgentLib.register(device3, function(error) { + iotAgentLib.register(device3, function (error) { done(); }); }); - it('should return a 200 OK both in HTTP and in the status code', function(done) { - iotAgentLib.setCommandHandler(function(id, type, service, subservice, attributes, callback) { + it('should return a 200 OK both in HTTP and in the status code', function (done) { + iotAgentLib.setCommandHandler(function (id, type, service, subservice, attributes, callback) { callback(null); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(200); @@ -316,8 +328,8 @@ describe('NGSI-v1 - Polling commands', function() { }); }); - describe('When a polling command expires', function() { - var options = { + describe('When a polling command expires', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/v1/updateContext', method: 'POST', json: { @@ -343,38 +355,48 @@ describe('NGSI-v1 - Polling commands', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { statusAttributeMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContextCommandStatus.json')) - .reply(200, + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextCommandStatus.json') + ) + .reply( + 200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextCommandStatusSuccess.json')); + './test/unit/examples/contextResponses/updateContextCommandStatusSuccess.json' + ) + ); statusAttributeMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContextCommandExpired.json')) - .reply(200, + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextCommandExpired.json') + ) + .reply( + 200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextCommandStatusSuccess.json')); + './test/unit/examples/contextResponses/updateContextCommandStatusSuccess.json' + ) + ); - iotAgentLib.register(device3, function(error) { + iotAgentLib.register(device3, function (error) { done(); }); }); - it('should remove it from the queue', function(done) { - iotAgentLib.setCommandHandler(function(id, type, service, subservice, attributes, callback) { + it('should remove it from the queue', function (done) { + iotAgentLib.setCommandHandler(function (id, type, service, subservice, attributes, callback) { callback(null); }); - request(options, function(error, response, body) { - setTimeout(function() { - iotAgentLib.commandQueue('smartGondor', 'gardens', 'r2d2', function(error, listCommands) { + request(options, function (error, response, body) { + setTimeout(function () { + iotAgentLib.commandQueue('smartGondor', 'gardens', 'r2d2', function (error, listCommands) { should.not.exist(error); listCommands.count.should.equal(0); done(); @@ -383,14 +405,14 @@ describe('NGSI-v1 - Polling commands', function() { }); }); - it('should mark it as ERROR in the Context Broker', function(done) { - iotAgentLib.setCommandHandler(function(id, type, service, subservice, attributes, callback) { + it('should mark it as ERROR in the Context Broker', function (done) { + iotAgentLib.setCommandHandler(function (id, type, service, subservice, attributes, callback) { callback(null); }); - request(options, function(error, response, body) { - setTimeout(function() { - iotAgentLib.commandQueue('smartGondor', 'gardens', 'r2d2', function(error, listCommands) { + request(options, function (error, response, body) { + setTimeout(function () { + iotAgentLib.commandQueue('smartGondor', 'gardens', 'r2d2', function (error, listCommands) { statusAttributeMock.done(); done(); }); diff --git a/test/unit/memoryRegistry/deviceRegistryMemory_test.js b/test/unit/memoryRegistry/deviceRegistryMemory_test.js index 6d0e1a322..a3724c012 100644 --- a/test/unit/memoryRegistry/deviceRegistryMemory_test.js +++ b/test/unit/memoryRegistry/deviceRegistryMemory_test.js @@ -20,58 +20,60 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - async = require('async'), - should = require('should'), - nock = require('nock'), - utils = require('../../tools/utils'), - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - name: 'testAgent', - port: 4041, - baseRoot: '/' - }, - types: {}, - deviceRegistry: { - type: 'memory' - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const async = require('async'); +const should = require('should'); +const nock = require('nock'); +const utils = require('../../tools/utils'); +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + name: 'testAgent', + port: 4041, + baseRoot: '/' + }, + types: {}, + deviceRegistry: { + type: 'memory' }, - contextBrokerMock; + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; +let contextBrokerMock; -describe('In memory device registry', function() { - beforeEach(function(done) { +describe('In memory device registry', function () { + beforeEach(function (done) { iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); }); - describe('When a the registry is queried for a device using an arbitrary attribute', function() { - beforeEach(function(done) { + describe('When a the registry is queried for a device using an arbitrary attribute', function () { + beforeEach(function (done) { contextBrokerMock = nock('http://192.168.1.1:1026') .post('/v1/updateContext') .times(10) .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); - var devices = []; + const devices = []; - for (var i = 0; i < 10; i++) { + for (let i = 0; i < 10; i++) { devices.push({ id: 'id' + i, type: 'Light' + i, @@ -88,42 +90,45 @@ describe('In memory device registry', function() { }); } - async.map(devices, iotAgentLib.register, function(error, results) { + async.map(devices, iotAgentLib.register, function (error, results) { done(); }); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.clearRegistry(done); }); - it('should return the appropriate device', function(done) { - iotAgentLib.getDevicesByAttribute('internalId', 'internal3', 'smartGondor', 'gardens', - function(error, devices) { - should.not.exist(error); - should.exist(devices); - devices.length.should.equal(1); - devices[0].id.should.equal('id3'); - done(); - }); + it('should return the appropriate device', function (done) { + iotAgentLib.getDevicesByAttribute('internalId', 'internal3', 'smartGondor', 'gardens', function ( + error, + devices + ) { + should.not.exist(error); + should.exist(devices); + devices.length.should.equal(1); + devices[0].id.should.equal('id3'); + done(); + }); }); }); - describe('When a the registry is queried for devices in multiple services', function() { - beforeEach(function(done) { + describe('When a the registry is queried for devices in multiple services', function () { + beforeEach(function (done) { contextBrokerMock = nock('http://192.168.1.1:1026') .post('/v1/updateContext') .times(10) - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); - var devices = []; + const devices = []; - for (var i = 0; i < 10; i++) { + for (let i = 0; i < 10; i++) { devices.push({ id: 'id' + i, - type: 'Light' + i % 2, + type: 'Light' + (i % 2), internalId: 'internal' + i, - service: 'smartGondor' + i % 3, + service: 'smartGondor' + (i % 3), subservice: 'gardens', active: [ { @@ -135,41 +140,41 @@ describe('In memory device registry', function() { }); } - async.map(devices, iotAgentLib.register, function(error, results) { + async.map(devices, iotAgentLib.register, function (error, results) { done(); }); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.clearRegistry(done); }); - it('should return all the matching devices', function(done) { - iotAgentLib.getDevicesByAttribute('type', 'Light0', undefined, 'gardens', - function(error, devices) { - should.not.exist(error); - should.exist(devices); - devices.length.should.equal(5); - done(); - }); + it('should return all the matching devices', function (done) { + iotAgentLib.getDevicesByAttribute('type', 'Light0', undefined, 'gardens', function (error, devices) { + should.not.exist(error); + should.exist(devices); + devices.length.should.equal(5); + done(); + }); }); }); - describe('When a the registry is queried for devices in a particular service', function() { - beforeEach(function(done) { + describe('When a the registry is queried for devices in a particular service', function () { + beforeEach(function (done) { contextBrokerMock = nock('http://192.168.1.1:1026') .post('/v1/updateContext') .times(10) - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); - var devices = []; + const devices = []; - for (var i = 0; i < 10; i++) { + for (let i = 0; i < 10; i++) { devices.push({ id: 'id' + i, type: 'Light', internalId: 'internal' + i, - service: 'smartGondor' + i % 3, + service: 'smartGondor' + (i % 3), subservice: 'gardens', active: [ { @@ -181,21 +186,20 @@ describe('In memory device registry', function() { }); } - async.map(devices, iotAgentLib.register, function(error, results) { + async.map(devices, iotAgentLib.register, function (error, results) { done(); }); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.clearRegistry(done); }); - it('should return all the matching devices in that service', function(done) { - iotAgentLib.getDevicesByAttribute('type', 'Light', 'smartGondor0', 'gardens', - function(error, devices) { - should.not.exist(error); - should.exist(devices); - devices.length.should.equal(4); - done(); - }); + it('should return all the matching devices in that service', function (done) { + iotAgentLib.getDevicesByAttribute('type', 'Light', 'smartGondor0', 'gardens', function (error, devices) { + should.not.exist(error); + should.exist(devices); + devices.length.should.equal(4); + done(); + }); }); }); }); diff --git a/test/unit/mongodb/mongoDBUtils.js b/test/unit/mongodb/mongoDBUtils.js index 66cd1fb6a..d40be5567 100644 --- a/test/unit/mongodb/mongoDBUtils.js +++ b/test/unit/mongodb/mongoDBUtils.js @@ -20,40 +20,40 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; -var MongoClient = require('mongodb').MongoClient, - async = require('async'); +/* eslint-disable no-unused-vars */ + +const MongoClient = require('mongodb').MongoClient; +const async = require('async'); function cleanDb(host, name, callback) { - var url = 'mongodb://' + host + ':27017/' + name; + const url = 'mongodb://' + host + ':27017/' + name; - MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { + MongoClient.connect(url, { useNewUrlParser: true }, function (err, db) { if (db && db.db()) { - db.db().dropDatabase( function (err, result) { + db.db().dropDatabase(function (err, result) { db.close(); callback(); }); - } }); } function cleanDbs(callback) { - async.series([ - async.apply(cleanDb, 'localhost', 'iotagent') - ], callback); + async.series([async.apply(cleanDb, 'localhost', 'iotagent')], callback); } function populate(host, dbName, entityList, collectionName, callback) { - var url = 'mongodb://' + host + ':27017/' + dbName; + const url = 'mongodb://' + host + ':27017/' + dbName; - MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { + MongoClient.connect(url, { useNewUrlParser: true }, function (err, db) { if (db) { - db.db().collection(collectionName).insertMany(entityList, function(err, r) { - db.close(); - callback(err); - }); + db.db() + .collection(collectionName) + .insertMany(entityList, function (err, r) { + db.close(); + callback(err); + }); } else { callback(); } diff --git a/test/unit/mongodb/mongodb-connectionoptions-test.js b/test/unit/mongodb/mongodb-connectionoptions-test.js index 4466b8bdc..94f285cb6 100644 --- a/test/unit/mongodb/mongodb-connectionoptions-test.js +++ b/test/unit/mongodb/mongodb-connectionoptions-test.js @@ -22,337 +22,347 @@ * * Modified by: Nobuyuki Matsui - TIS Inc. */ -'use strict'; -var dbConn = require('../../../lib/model/dbConn'), - config = require('../../../lib/commonConfig'), - mongoose = require('mongoose'), - sinon = require('sinon'), - should = require('should'), - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041, - baseRoot: '/' - }, - stats: { - interval: 50, - persistence: true - }, - types: {}, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }, - oldConfig; +/* eslint-disable no-unused-vars */ -describe('dbConn.configureDb', function() { - var stub; +const dbConn = require('../../../lib/model/dbConn'); +const config = require('../../../lib/commonConfig'); +const mongoose = require('mongoose'); +const sinon = require('sinon'); +const should = require('should'); +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041, + baseRoot: '/' + }, + stats: { + interval: 50, + persistence: true + }, + types: {}, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; +let oldConfig; - beforeEach(function() { - oldConfig = config.getConfig(); - }); +describe('dbConn.configureDb', function () { + let stub; - afterEach(function() { - config.setConfig(oldConfig); - if (stub) { - stub.restore(); - } - }); + beforeEach(function () { + oldConfig = config.getConfig(); + }); - describe('When set mongodb options, it should call mongoose.createCOnnection by using below params', function() { - var tests = [ - { - mongodb: { - host: 'example.com' - }, - expected: { - url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME, - options: { - useNewUrlParser: true - } - } - }, - { - mongodb: { - host: 'example.com', - port: '98765' - }, - expected: { - url: 'mongodb://example.com:98765/' + dbConn.DEFAULT_DB_NAME, - options: { - useNewUrlParser: true - } + afterEach(function () { + config.setConfig(oldConfig); + if (stub) { + stub.restore(); } - }, - { - mongodb: { - host: 'example.com', - db: 'examples' - }, - expected: { - url: 'mongodb://example.com:27017/examples', - options: { - useNewUrlParser: true - } - } - }, - { - mongodb: { - host: 'example.com', - replicaSet: 'rs0' - }, - expected: { - url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME, - options: { - replicaSet: 'rs0', - useNewUrlParser: true - } - } - }, - { - mongodb: { - host: 'example.com', - user: 'user01' - }, - expected: { - url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME, - options: { - useNewUrlParser: true - } - } - }, - { - mongodb: { - host: 'example.com', - password: 'pass01' - }, - expected: { - url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME, - options: { - useNewUrlParser: true - } - } - }, - { - mongodb: { - host: 'example.com', - user: 'user01', - password: 'pass01' - }, - expected: { - url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME, - options: { - auth: { - user: 'user01', - password: 'pass01' + }); + + describe('When set mongodb options, it should call mongoose.createCOnnection by using below params', function () { + const tests = [ + { + mongodb: { + host: 'example.com' + }, + expected: { + url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME, + options: { + useNewUrlParser: true + } + } }, - useNewUrlParser: true - } - } - }, - { - mongodb: { - host: 'example.com', - authSource: 'admin' - }, - expected: { - url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME, - options: { - authSource: 'admin', - useNewUrlParser: true - } - } - }, - { - mongodb: { - host: 'example.com', - port: '98765', - db: 'examples', - replicaSet: 'rs0', - user: 'user01', - password: 'pass01', - authSource: 'admin' - }, - expected: { - url: 'mongodb://example.com:98765/examples', - options: { - replicaSet: 'rs0', - auth: { - user: 'user01', - password: 'pass01' + { + mongodb: { + host: 'example.com', + port: '98765' + }, + expected: { + url: 'mongodb://example.com:98765/' + dbConn.DEFAULT_DB_NAME, + options: { + useNewUrlParser: true + } + } }, - authSource: 'admin', - useNewUrlParser: true - } - } - }, - { - mongodb: { - host: 'example.com', - ssl: true - }, - expected: { - url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME, - options: { - ssl: true, - useNewUrlParser: true - } - } - }, - { - mongodb: { - host: 'example.com', - extraArgs: { - retryWrites: true - } - }, - expected: { - url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME + '?retryWrites=true', - options: { - useNewUrlParser: true - } - } - }, - { - mongodb: { - host: 'example.com', - extraArgs: { - retryWrites: true, - readPreference: 'nearest' - } - }, - expected: { - url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME + '?retryWrites=true&readPreference=nearest', - options: { - useNewUrlParser: true - } - } - }, - { - mongodb: { - host: 'example.com', - extraArgs: {} - }, - expected: { - url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME, - options: { - useNewUrlParser: true - } - } - }, - { - mongodb: { - host: 'example.com', - extraArgs: [] - }, - expected: { - url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME, - options: { - useNewUrlParser: true - } - } - }, - { - mongodb: { - host: 'example.com', - extraArgs: null - }, - expected: { - url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME, - options: { - useNewUrlParser: true - } - } - }, - { - mongodb: { - host: 'example.com', - port: '98765', - db: 'examples', - replicaSet: 'rs0', - user: 'user01', - password: 'pass01', - authSource: 'admin', - ssl: true, - extraArgs: { - retryWrites: true, - readPreference: 'nearest', - w: 'majority' - }, - unknownparam: 'unknown' - }, - expected: { - url: 'mongodb://example.com:98765/examples?retryWrites=true&readPreference=nearest&w=majority', - options: { - replicaSet: 'rs0', - auth: { - user: 'user01', - password: 'pass01' + { + mongodb: { + host: 'example.com', + db: 'examples' + }, + expected: { + url: 'mongodb://example.com:27017/examples', + options: { + useNewUrlParser: true + } + } }, - authSource: 'admin', - ssl: true, - useNewUrlParser: true - } - } - } - ]; - tests.forEach(function (params) { - it('mongodb options = ' + JSON.stringify(params.mongodb) + ', ' + - 'expected = ' + JSON.stringify(params.expected), function(done) { - var cfg = Object.assign({}, iotAgentConfig, { - mongodb: params.mongodb - }); - stub = sinon.stub(mongoose, 'createConnection').callsFake(function(url, options, fn) { - url.should.be.equal(params.expected.url); - options.should.be.eql(params.expected.options); - done(); - }); - config.setConfig(cfg); - dbConn.configureDb(function(error) { - if (error) { - should.fail(); - } + { + mongodb: { + host: 'example.com', + replicaSet: 'rs0' + }, + expected: { + url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME, + options: { + replicaSet: 'rs0', + useNewUrlParser: true + } + } + }, + { + mongodb: { + host: 'example.com', + user: 'user01' + }, + expected: { + url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME, + options: { + useNewUrlParser: true + } + } + }, + { + mongodb: { + host: 'example.com', + password: 'pass01' + }, + expected: { + url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME, + options: { + useNewUrlParser: true + } + } + }, + { + mongodb: { + host: 'example.com', + user: 'user01', + password: 'pass01' + }, + expected: { + url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME, + options: { + auth: { + user: 'user01', + password: 'pass01' + }, + useNewUrlParser: true + } + } + }, + { + mongodb: { + host: 'example.com', + authSource: 'admin' + }, + expected: { + url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME, + options: { + authSource: 'admin', + useNewUrlParser: true + } + } + }, + { + mongodb: { + host: 'example.com', + port: '98765', + db: 'examples', + replicaSet: 'rs0', + user: 'user01', + password: 'pass01', + authSource: 'admin' + }, + expected: { + url: 'mongodb://example.com:98765/examples', + options: { + replicaSet: 'rs0', + auth: { + user: 'user01', + password: 'pass01' + }, + authSource: 'admin', + useNewUrlParser: true + } + } + }, + { + mongodb: { + host: 'example.com', + ssl: true + }, + expected: { + url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME, + options: { + ssl: true, + useNewUrlParser: true + } + } + }, + { + mongodb: { + host: 'example.com', + extraArgs: { + retryWrites: true + } + }, + expected: { + url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME + '?retryWrites=true', + options: { + useNewUrlParser: true + } + } + }, + { + mongodb: { + host: 'example.com', + extraArgs: { + retryWrites: true, + readPreference: 'nearest' + } + }, + expected: { + url: + 'mongodb://example.com:27017/' + + dbConn.DEFAULT_DB_NAME + + '?retryWrites=true&readPreference=nearest', + options: { + useNewUrlParser: true + } + } + }, + { + mongodb: { + host: 'example.com', + extraArgs: {} + }, + expected: { + url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME, + options: { + useNewUrlParser: true + } + } + }, + { + mongodb: { + host: 'example.com', + extraArgs: [] + }, + expected: { + url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME, + options: { + useNewUrlParser: true + } + } + }, + { + mongodb: { + host: 'example.com', + extraArgs: null + }, + expected: { + url: 'mongodb://example.com:27017/' + dbConn.DEFAULT_DB_NAME, + options: { + useNewUrlParser: true + } + } + }, + { + mongodb: { + host: 'example.com', + port: '98765', + db: 'examples', + replicaSet: 'rs0', + user: 'user01', + password: 'pass01', + authSource: 'admin', + ssl: true, + extraArgs: { + retryWrites: true, + readPreference: 'nearest', + w: 'majority' + }, + unknownparam: 'unknown' + }, + expected: { + url: 'mongodb://example.com:98765/examples?retryWrites=true&readPreference=nearest&w=majority', + options: { + replicaSet: 'rs0', + auth: { + user: 'user01', + password: 'pass01' + }, + authSource: 'admin', + ssl: true, + useNewUrlParser: true + } + } + } + ]; + tests.forEach(function (params) { + it( + 'mongodb options = ' + + JSON.stringify(params.mongodb) + + ', ' + + 'expected = ' + + JSON.stringify(params.expected), + function (done) { + const cfg = Object.assign({}, iotAgentConfig, { + mongodb: params.mongodb + }); + stub = sinon.stub(mongoose, 'createConnection').callsFake(function (url, options, fn) { + url.should.be.equal(params.expected.url); + options.should.be.eql(params.expected.options); + done(); + }); + config.setConfig(cfg); + dbConn.configureDb(function (error) { + if (error) { + should.fail(); + } + }); + } + ); }); - }); }); - }); - describe('When no mongodb options or "host" is empty, it should returns an error callback', function() { - var tests = [ - { - mongodb: undefined - }, - { - mongodb: {} - }, - { - mongodb: { - port: '27017' - } - } - ]; - tests.forEach(function (params) { - it('mongodb options = ' + JSON.stringify(params.mongodb), function(done){ - var cfg = Object.assign({}, iotAgentConfig, { - mongodb: params.mongodb - }); - stub = sinon.stub(mongoose, 'createConnection').callsFake(function (url, options, fn) { - should.fail(); - }); - config.setConfig(cfg); - dbConn.configureDb(function (error) { - if (!error) { - should.fail(); - } - done(); + describe('When no mongodb options or "host" is empty, it should returns an error callback', function () { + const tests = [ + { + mongodb: undefined + }, + { + mongodb: {} + }, + { + mongodb: { + port: '27017' + } + } + ]; + tests.forEach(function (params) { + it('mongodb options = ' + JSON.stringify(params.mongodb), function (done) { + const cfg = Object.assign({}, iotAgentConfig, { + mongodb: params.mongodb + }); + stub = sinon.stub(mongoose, 'createConnection').callsFake(function (url, options, fn) { + should.fail(); + }); + config.setConfig(cfg); + dbConn.configureDb(function (error) { + if (!error) { + should.fail(); + } + done(); + }); + }); }); - }); }); - }); -}); \ No newline at end of file +}); diff --git a/test/unit/mongodb/mongodb-group-registry-test.js b/test/unit/mongodb/mongodb-group-registry-test.js index cf057ea3e..d3e921199 100644 --- a/test/unit/mongodb/mongodb-group-registry-test.js +++ b/test/unit/mongodb/mongodb-group-registry-test.js @@ -22,221 +22,226 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; -/*jshint camelcase:false */ - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - _ = require('underscore'), - utils = require('../../tools/utils'), - async = require('async'), - request = require('request'), - should = require('should'), - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - name: 'testAgent', - port: 4041, - baseRoot: '/' - }, - types: {}, - deviceRegistry: { - type: 'mongodb' - }, - mongodb: { - host: 'localhost', - port: '27017', - db: 'iotagent' - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const _ = require('underscore'); +const utils = require('../../tools/utils'); +const async = require('async'); +const request = require('request'); +const should = require('should'); +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026' }, - mongo = require('mongodb').MongoClient, - mongoUtils = require('./mongoDBUtils'), - optionsCreation = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: { - services: [ - { - resource: '/deviceTest', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', - entity_type: 'Light', - trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', - cbHost: 'http://unexistentHost:1026', - commands: [ - { - name: 'wheel1', - type: 'Wheel' - } - ], - lazy: [ - { - name: 'luminescence', - type: 'Lumens' - } - ], - attributes: [ - { - name: 'status', - type: 'Boolean' - } - ], - internal_attributes: [ - { - customField: 'customValue' - } - ] - } - ] - }, - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - } + server: { + name: 'testAgent', + port: 4041, + baseRoot: '/' }, - optionsDelete = { - url: 'http://localhost:4041/iot/services', - method: 'DELETE', - json: {}, - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - }, - qs: { - resource: '/deviceTest', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732' - } + types: {}, + deviceRegistry: { + type: 'mongodb' }, - optionsList = { - url: 'http://localhost:4041/iot/services', - method: 'GET', - json: {}, - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/*' - } + mongodb: { + host: 'localhost', + port: '27017', + db: 'iotagent' }, - optionsUpdate = { - url: 'http://localhost:4041/iot/services', - method: 'PUT', - json: { - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', - trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', - cbHost: 'http://anotherUnexistentHost:1026', - commands: [ - { - name: 'wheel1', - type: 'Wheel' - } - ], - lazy: [ - { - name: 'luminescence', - type: 'Lumens' - } - ], - attributes: [ - { - name: 'status', - type: 'Boolean' - } - ], - static_attributes: [ - { - name: 'bootstrapServer', - type: 'Address', - value: '127.0.0.1' - } - ] - }, - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - }, - qs: { - resource: '/deviceTest', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732' - } + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; +const mongo = require('mongodb').MongoClient; +const mongoUtils = require('./mongoDBUtils'); +const optionsCreation = { + url: 'http://localhost:4041/iot/services', + method: 'POST', + json: { + services: [ + { + resource: '/deviceTest', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', + entity_type: 'Light', + trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', + cbHost: 'http://unexistentHost:1026', + commands: [ + { + name: 'wheel1', + type: 'Wheel' + } + ], + lazy: [ + { + name: 'luminescence', + type: 'Lumens' + } + ], + attributes: [ + { + name: 'status', + type: 'Boolean' + } + ], + internal_attributes: [ + { + customField: 'customValue' + } + ] + } + ] }, - optionsGet = { - url: 'http://localhost:4041/iot/services', - method: 'GET', - json: {}, - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - } + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } +}; +const optionsDelete = { + url: 'http://localhost:4041/iot/services', + method: 'DELETE', + json: {}, + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' }, - iotAgentDb; - -describe('MongoDB Group Registry test', function() { - - beforeEach(function(done) { - mongoUtils.cleanDbs(function() { - iotAgentLib.activate(iotAgentConfig, function() { - mongo.connect('mongodb://localhost:27017/iotagent', { useNewUrlParser: true }, function(err, db) { + qs: { + resource: '/deviceTest', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732' + } +}; +const optionsList = { + url: 'http://localhost:4041/iot/services', + method: 'GET', + json: {}, + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/*' + } +}; +const optionsUpdate = { + url: 'http://localhost:4041/iot/services', + method: 'PUT', + json: { + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', + trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', + cbHost: 'http://anotherUnexistentHost:1026', + commands: [ + { + name: 'wheel1', + type: 'Wheel' + } + ], + lazy: [ + { + name: 'luminescence', + type: 'Lumens' + } + ], + attributes: [ + { + name: 'status', + type: 'Boolean' + } + ], + static_attributes: [ + { + name: 'bootstrapServer', + type: 'Address', + value: '127.0.0.1' + } + ] + }, + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + }, + qs: { + resource: '/deviceTest', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732' + } +}; +const optionsGet = { + url: 'http://localhost:4041/iot/services', + method: 'GET', + json: {}, + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } +}; +let iotAgentDb; + +describe('MongoDB Group Registry test', function () { + beforeEach(function (done) { + mongoUtils.cleanDbs(function () { + iotAgentLib.activate(iotAgentConfig, function () { + mongo.connect('mongodb://localhost:27017/iotagent', { useNewUrlParser: true }, function (err, db) { iotAgentDb = db; done(); }); }); - }); }); - afterEach(function(done) { - iotAgentLib.deactivate(function() { - iotAgentDb.close(function(error) { + afterEach(function (done) { + iotAgentLib.deactivate(function () { + iotAgentDb.close(function (error) { mongoUtils.cleanDbs(done); }); }); }); - describe('When a new device group creation request arrives', function() { - it('should store it in the DB', function(done) { - request(optionsCreation, function(error, response, body) { - iotAgentDb.db().collection('groups').find({}).toArray(function(err, docs) { - should.not.exist(err); - should.exist(docs); - should.exist(docs.length); - docs.length.should.equal(1); - should.exist(docs[0].type); - should.exist(docs[0].internalAttributes); - should.exist(docs[0].attributes); - should.exist(docs[0].apikey); - docs[0].type.should.equal('Light'); - docs[0].apikey.should.equal('801230BJKL23Y9090DSFL123HJK09H324HV8732'); - docs[0].internalAttributes.length.should.equal(1); - docs[0].internalAttributes[0].customField.should.equal('customValue'); - docs[0].attributes.length.should.equal(1); - docs[0].attributes[0].name.should.equal('status'); - done(); - }); + describe('When a new device group creation request arrives', function () { + it('should store it in the DB', function (done) { + request(optionsCreation, function (error, response, body) { + iotAgentDb + .db() + .collection('groups') + .find({}) + .toArray(function (err, docs) { + should.not.exist(err); + should.exist(docs); + should.exist(docs.length); + docs.length.should.equal(1); + should.exist(docs[0].type); + should.exist(docs[0].internalAttributes); + should.exist(docs[0].attributes); + should.exist(docs[0].apikey); + docs[0].type.should.equal('Light'); + docs[0].apikey.should.equal('801230BJKL23Y9090DSFL123HJK09H324HV8732'); + docs[0].internalAttributes.length.should.equal(1); + docs[0].internalAttributes[0].customField.should.equal('customValue'); + docs[0].attributes.length.should.equal(1); + docs[0].attributes[0].name.should.equal('status'); + done(); + }); }); }); - it('should store the service information from the headers into the DB', function(done) { - request(optionsCreation, function(error, response, body) { - iotAgentDb.db().collection('groups').find({}).toArray(function(err, docs) { - should.not.exist(err); - should.exist(docs[0].service); - should.exist(docs[0].subservice); - docs[0].service.should.equal('TestService'); - docs[0].subservice.should.equal('/testingPath'); - done(); - }); + it('should store the service information from the headers into the DB', function (done) { + request(optionsCreation, function (error, response, body) { + iotAgentDb + .db() + .collection('groups') + .find({}) + .toArray(function (err, docs) { + should.not.exist(err); + should.exist(docs[0].service); + should.exist(docs[0].subservice); + docs[0].service.should.equal('TestService'); + docs[0].subservice.should.equal('/testingPath'); + done(); + }); }); }); }); - describe('When a new device group creation request arrives with an existant (apikey, resource) pair', function() { - it('should return a DUPLICATE_GROUP error', function(done) { - request(optionsCreation, function(error, response, body) { - request(optionsCreation, function(error, response, body) { + describe('When a new device group creation request arrives with an existant (apikey, resource) pair', function () { + it('should return a DUPLICATE_GROUP error', function (done) { + request(optionsCreation, function (error, response, body) { + request(optionsCreation, function (error, response, body) { response.statusCode.should.equal(409); body.name.should.equal('DUPLICATE_GROUP'); done(); @@ -245,79 +250,91 @@ describe('MongoDB Group Registry test', function() { }); }); - describe('When a device group removal request arrives', function() { - beforeEach(function(done) { + describe('When a device group removal request arrives', function () { + beforeEach(function (done) { request(optionsCreation, done); }); - it('should remove it from the database', function(done) { - request(optionsDelete, function(error, response, body) { - iotAgentDb.db().collection('groups').find({}).toArray(function(err, docs) { - should.not.exist(err); - should.exist(docs); - should.exist(docs.length); - docs.length.should.equal(0); - done(); - }); + it('should remove it from the database', function (done) { + request(optionsDelete, function (error, response, body) { + iotAgentDb + .db() + .collection('groups') + .find({}) + .toArray(function (err, docs) { + should.not.exist(err); + should.exist(docs); + should.exist(docs.length); + docs.length.should.equal(0); + done(); + }); }); }); - it('should return a 204 OK statusCode', function(done) { - request(optionsDelete, function(error, response, body) { + it('should return a 204 OK statusCode', function (done) { + request(optionsDelete, function (error, response, body) { response.statusCode.should.equal(204); done(); }); }); }); - describe('When a device group update request arrives', function() { - beforeEach(function(done) { + describe('When a device group update request arrives', function () { + beforeEach(function (done) { request(optionsCreation, done); }); - it('should update the values in the database', function(done) { - request(optionsUpdate, function(error, response, body) { - iotAgentDb.db().collection('groups').find({}).toArray(function(err, docs) { - should.not.exist(err); - should.exist(docs); - should.exist(docs[0].cbHost); - docs[0].cbHost.should.equal('http://anotherUnexistentHost:1026'); - should.exist(docs[0].staticAttributes); - docs[0].staticAttributes.length.should.equal(1); - done(); - }); + it('should update the values in the database', function (done) { + request(optionsUpdate, function (error, response, body) { + iotAgentDb + .db() + .collection('groups') + .find({}) + .toArray(function (err, docs) { + should.not.exist(err); + should.exist(docs); + should.exist(docs[0].cbHost); + docs[0].cbHost.should.equal('http://anotherUnexistentHost:1026'); + should.exist(docs[0].staticAttributes); + docs[0].staticAttributes.length.should.equal(1); + done(); + }); }); }); }); - describe('When a multiple device group creation arrives', function() { - var optionsMultipleCreation = _.clone(optionsCreation); + describe('When a multiple device group creation arrives', function () { + const optionsMultipleCreation = _.clone(optionsCreation); - beforeEach(function(done) { + beforeEach(function (done) { optionsMultipleCreation.json = utils.readExampleFile( - './test/unit/examples/groupProvisioningRequests/multipleGroupsCreation.json'); + './test/unit/examples/groupProvisioningRequests/multipleGroupsCreation.json' + ); done(); }); - it('should create the values in the database', function(done) { - request(optionsMultipleCreation, function(error, response, body) { - iotAgentDb.db().collection('groups').find({}).toArray(function(err, docs) { - should.not.exist(err); - should.exist(docs); - docs.length.should.equal(2); - done(); - }); + it('should create the values in the database', function (done) { + request(optionsMultipleCreation, function (error, response, body) { + iotAgentDb + .db() + .collection('groups') + .find({}) + .toArray(function (err, docs) { + should.not.exist(err); + should.exist(docs); + docs.length.should.equal(2); + done(); + }); }); }); }); - describe('When a device group listing request arrives', function() { - beforeEach(function(done) { - var optionsCreation1 = _.clone(optionsCreation), - optionsCreation2 = _.clone(optionsCreation), - optionsCreation3 = _.clone(optionsCreation); - + describe('When a device group listing request arrives', function () { + beforeEach(function (done) { + const optionsCreation1 = _.clone(optionsCreation); + const optionsCreation2 = _.clone(optionsCreation); + const optionsCreation3 = _.clone(optionsCreation); optionsCreation2.json = { services: [] }; optionsCreation3.json = { services: [] }; @@ -328,23 +345,26 @@ describe('MongoDB Group Registry test', function() { optionsCreation2.json.services[0].apikey = 'qwertyuiop'; optionsCreation3.json.services[0].apikey = 'lkjhgfds'; - async.series([ - async.apply(request, optionsCreation1), - async.apply(request, optionsCreation2), - async.apply(request, optionsCreation3) - ], done); + async.series( + [ + async.apply(request, optionsCreation1), + async.apply(request, optionsCreation2), + async.apply(request, optionsCreation3) + ], + done + ); }); - it('should return all the configured device groups from the database', function(done) { - request(optionsList, function(error, response, body) { + it('should return all the configured device groups from the database', function (done) { + request(optionsList, function (error, response, body) { body.count.should.equal(3); done(); }); }); }); - describe('When a device group listing arrives with a limit', function() { - var optionsConstrained = { + describe('When a device group listing arrives with a limit', function () { + const optionsConstrained = { url: 'http://localhost:4041/iot/services', method: 'GET', qs: { @@ -358,11 +378,11 @@ describe('MongoDB Group Registry test', function() { } }; - beforeEach(function(done) { - var optionsCreationList = [], - creationFns = []; + beforeEach(function (done) { + const optionsCreationList = []; + const creationFns = []; - for (var i = 0; i < 10; i++) { + for (let i = 0; i < 10; i++) { optionsCreationList[i] = _.clone(optionsCreation); optionsCreationList[i].json = { services: [] }; optionsCreationList[i].json.services[0] = _.clone(optionsCreation.json.services[0]); @@ -373,23 +393,21 @@ describe('MongoDB Group Registry test', function() { async.series(creationFns, done); }); - it('should return the appropriate count of services', function(done) { - request(optionsConstrained, function(error, response, body) { + it('should return the appropriate count of services', function (done) { + request(optionsConstrained, function (error, response, body) { body.count.should.equal(10); done(); }); }); }); - describe('When a device info request arrives', function() { - beforeEach(function(done) { - async.series([ - async.apply(request, optionsCreation) - ], done); + describe('When a device info request arrives', function () { + beforeEach(function (done) { + async.series([async.apply(request, optionsCreation)], done); }); - it('should return all the configured device groups from the database', function(done) { - request(optionsGet, function(error, response, body) { + it('should return all the configured device groups from the database', function (done) { + request(optionsGet, function (error, response, body) { should.exist(body); should.exist(body.count); body.count.should.equal(1); @@ -402,12 +420,12 @@ describe('MongoDB Group Registry test', function() { }); }); - describe('When a device info request arrives and multiple groups have been created', function() { - beforeEach(function(done) { - var optionsCreationList = [], - creationFns = []; + describe('When a device info request arrives and multiple groups have been created', function () { + beforeEach(function (done) { + const optionsCreationList = []; + const creationFns = []; - for (var i = 0; i < 10; i++) { + for (let i = 0; i < 10; i++) { optionsCreationList[i] = _.clone(optionsCreation); optionsCreationList[i].json = { services: [] }; optionsCreationList[i].json.services[0] = _.clone(optionsCreation.json.services[0]); @@ -418,8 +436,8 @@ describe('MongoDB Group Registry test', function() { async.series(creationFns, done); }); - it('should return all the configured device groups from the database', function(done) { - request(optionsGet, function(error, response, body) { + it('should return all the configured device groups from the database', function (done) { + request(optionsGet, function (error, response, body) { should.exist(body); should.exist(body.count); body.count.should.equal(10); diff --git a/test/unit/mongodb/mongodb-registry-test.js b/test/unit/mongodb/mongodb-registry-test.js index ee9cfda30..0e226dcb3 100644 --- a/test/unit/mongodb/mongodb-registry-test.js +++ b/test/unit/mongodb/mongodb-registry-test.js @@ -20,291 +20,321 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - mongo = require('mongodb').MongoClient, - nock = require('nock'), - async = require('async'), - mongoUtils = require('./mongoDBUtils'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [ - { - name: 'position', - type: 'Array' - } - ], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - attributes: [ - { - name: 'pressure', - type: 'Hgmm' - } - ], - staticAttributes: [ - { - name: 'location', - type: 'Vector' - } - ], - service: 'smartGondor', - subservice: 'gardens', - internalAttributes: { - customAttribute: 'customValue' + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const mongo = require('mongodb').MongoClient; +const nock = require('nock'); +const async = require('async'); +const mongoUtils = require('./mongoDBUtils'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [ + { + name: 'position', + type: 'Array' + } + ], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + attributes: [ + { + name: 'pressure', + type: 'Hgmm' } - }, - 'Termometer': { - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - attributes: [ - ], - service: 'smartGondor', - subservice: 'gardens' + ], + staticAttributes: [ + { + name: 'location', + type: 'Vector' + } + ], + service: 'smartGondor', + subservice: 'gardens', + internalAttributes: { + customAttribute: 'customValue' } }, - deviceRegistry: { - type: 'mongodb' - }, - mongodb: { - host: 'localhost', - port: '27017', - db: 'iotagent' - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }, - device1 = { - id: 'light1', - type: 'Light', - service: 'smartGondor', - subservice: 'gardens', - endpoint: 'http://testEndpoint.com', - transport: 'HTTP', - resource: '/test', - apikey: '2345678ikjhgfr678i', - protocol: 'GENERIC_PROTOCOL', - commands: [ - { - name: 'position', - type: 'Array' - } - ], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ], - staticAttributes: [ - { - name: 'location', - type: 'Vector' - } - ], - internalAttributes: { - customAttribute: 'customValue' + Termometer: { + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + attributes: [], + service: 'smartGondor', + subservice: 'gardens' } }, - device2 = { - id: 'term2', - type: 'Termometer', - service: 'smartGondor', - subservice: 'gardens', - resource: '/', - apikey: 'dsf8yy789iyushu786', - protocol: 'GENERIC_PROTOCOL' + deviceRegistry: { + type: 'mongodb' }, - device3 = { - id: 'light1', - type: 'Light', - service: 'smartMordor', - subservice: 'electricity', - endpoint: 'http://testEndpoint.com', - transport: 'HTTP', - resource: '/test', - apikey: '2345678ikjhgfr678i', - protocol: 'GENERIC_PROTOCOL', - commands: [ - { - name: 'position', - type: 'Array' - } - ], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ], - staticAttributes: [ - { - name: 'location', - type: 'Vector' - } - ], - internalAttributes: { - customAttribute: 'customValue' - } + mongodb: { + host: 'localhost', + port: '27017', + db: 'iotagent' }, - iotAgentDb; - -describe('MongoDB Device Registry', function() { - beforeEach(function(done) { + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; +const device1 = { + id: 'light1', + type: 'Light', + service: 'smartGondor', + subservice: 'gardens', + endpoint: 'http://testEndpoint.com', + transport: 'HTTP', + resource: '/test', + apikey: '2345678ikjhgfr678i', + protocol: 'GENERIC_PROTOCOL', + commands: [ + { + name: 'position', + type: 'Array' + } + ], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ], + staticAttributes: [ + { + name: 'location', + type: 'Vector' + } + ], + internalAttributes: { + customAttribute: 'customValue' + } +}; +const device2 = { + id: 'term2', + type: 'Termometer', + service: 'smartGondor', + subservice: 'gardens', + resource: '/', + apikey: 'dsf8yy789iyushu786', + protocol: 'GENERIC_PROTOCOL' +}; +const device3 = { + id: 'light1', + type: 'Light', + service: 'smartMordor', + subservice: 'electricity', + endpoint: 'http://testEndpoint.com', + transport: 'HTTP', + resource: '/test', + apikey: '2345678ikjhgfr678i', + protocol: 'GENERIC_PROTOCOL', + commands: [ + { + name: 'position', + type: 'Array' + } + ], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ], + staticAttributes: [ + { + name: 'location', + type: 'Vector' + } + ], + internalAttributes: { + customAttribute: 'customValue' + } +}; +let iotAgentDb; + +describe('MongoDB Device Registry', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - mongoUtils.cleanDbs(function() { - mongo.connect('mongodb://localhost:27017/iotagent', { useNewUrlParser: true }, function(err, db) { + mongoUtils.cleanDbs(function () { + mongo.connect('mongodb://localhost:27017/iotagent', { useNewUrlParser: true }, function (err, db) { iotAgentDb = db; done(); }); }); }); - afterEach(function(done) { - delete(device1.registrationId); - iotAgentLib.deactivate(function(error) { - iotAgentDb.db().collection('devices').deleteOne(function(error) { - iotAgentDb.close(function(error) { - mongoUtils.cleanDbs(done); + afterEach(function (done) { + delete device1.registrationId; + iotAgentLib.deactivate(function (error) { + iotAgentDb + .db() + .collection('devices') + .deleteOne(function (error) { + iotAgentDb.close(function (error) { + mongoUtils.cleanDbs(done); + }); }); - }); }); }); - describe('When a new device is connected to the IoT Agent', function() { - beforeEach(function(done) { + describe('When a new device is connected to the IoT Agent', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerIoTAgent3.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent3.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json' + ) + ); contextBrokerMock .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); - iotAgentLib.activate(iotAgentConfig, function(error) { + iotAgentLib.activate(iotAgentConfig, function (error) { done(); }); }); - it('should be registered in mongodb with all its attributes', function(done) { - iotAgentLib.register(device1, function(error) { + it('should be registered in mongodb with all its attributes', function (done) { + iotAgentLib.register(device1, function (error) { should.not.exist(error); - iotAgentDb.db().collection('devices').find({}).toArray(function(err, docs) { - should.not.exist(err); - should.exist(docs); - should.exist(docs.length); - docs.length.should.equal(1); - should.exist(docs[0].internalAttributes); - should.exist(docs[0].staticAttributes); - should.exist(docs[0].internalAttributes.customAttribute); - should.exist(docs[0].active); - should.exist(docs[0].commands); - should.exist(docs[0].resource); - should.exist(docs[0].endpoint); - should.exist(docs[0].transport); - should.exist(docs[0].apikey); - should.exist(docs[0].protocol); - docs[0].active.length.should.equal(1); - docs[0].staticAttributes.length.should.equal(1); - docs[0].staticAttributes[0].name.should.equal('location'); - docs[0].active[0].name.should.equal('pressure'); - docs[0].commands[0].name.should.equal('position'); - docs[0].internalAttributes.customAttribute.should.equal('customValue'); - docs[0].resource.should.equal('/test'); - docs[0].endpoint.should.equal('http://testEndpoint.com'); - docs[0].transport.should.equal('HTTP'); - docs[0].protocol.should.equal('GENERIC_PROTOCOL'); - docs[0].apikey.should.equal('2345678ikjhgfr678i'); - done(); - }); + iotAgentDb + .db() + .collection('devices') + .find({}) + .toArray(function (err, docs) { + should.not.exist(err); + should.exist(docs); + should.exist(docs.length); + docs.length.should.equal(1); + should.exist(docs[0].internalAttributes); + should.exist(docs[0].staticAttributes); + should.exist(docs[0].internalAttributes.customAttribute); + should.exist(docs[0].active); + should.exist(docs[0].commands); + should.exist(docs[0].resource); + should.exist(docs[0].endpoint); + should.exist(docs[0].transport); + should.exist(docs[0].apikey); + should.exist(docs[0].protocol); + docs[0].active.length.should.equal(1); + docs[0].staticAttributes.length.should.equal(1); + docs[0].staticAttributes[0].name.should.equal('location'); + docs[0].active[0].name.should.equal('pressure'); + docs[0].commands[0].name.should.equal('position'); + docs[0].internalAttributes.customAttribute.should.equal('customValue'); + docs[0].resource.should.equal('/test'); + docs[0].endpoint.should.equal('http://testEndpoint.com'); + docs[0].transport.should.equal('HTTP'); + docs[0].protocol.should.equal('GENERIC_PROTOCOL'); + docs[0].apikey.should.equal('2345678ikjhgfr678i'); + done(); + }); }); }); }); - describe('When a device with the same Device ID tries to register to the IOT Agent', function() { - beforeEach(function(done) { + describe('When a device with the same Device ID tries to register to the IOT Agent', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerIoTAgent3.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent3.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json' + ) + ); contextBrokerMock .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerIoTAgent3.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent3.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json' + ) + ); contextBrokerMock .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); - iotAgentLib.activate(iotAgentConfig, function(error) { + iotAgentLib.activate(iotAgentConfig, function (error) { done(); }); }); - it('should be rejected with a DUPLICATE_DEVICE_ID', function(done) { - iotAgentLib.register(device1, function(error) { - iotAgentLib.register(device1, function(error) { + it('should be rejected with a DUPLICATE_DEVICE_ID', function (done) { + iotAgentLib.register(device1, function (error) { + iotAgentLib.register(device1, function (error) { should.exist(error); error.name.should.equal('DUPLICATE_DEVICE_ID'); done(); @@ -313,40 +343,56 @@ describe('MongoDB Device Registry', function() { }); }); - describe('When a device with the same Device ID but different service tries to be registered', function() { - beforeEach(function(done) { + describe('When a device with the same Device ID but different service tries to be registered', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerIoTAgent3.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent3.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json' + ) + ); contextBrokerMock .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); contextBrokerMock - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerIoTAgent3.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent3.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json' + ) + ); contextBrokerMock .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); - iotAgentLib.activate(iotAgentConfig, function(error) { + iotAgentLib.activate(iotAgentConfig, function (error) { done(); }); }); - it('should accept both devices', function(done) { - iotAgentLib.register(device1, function(error) { - iotAgentLib.register(device3, function(error) { + it('should accept both devices', function (done) { + iotAgentLib.register(device1, function (error) { + iotAgentLib.register(device3, function (error) { should.not.exist(error); done(); }); @@ -354,74 +400,94 @@ describe('MongoDB Device Registry', function() { }); }); - describe('When a device is removed from the IoT Agent', function() { - beforeEach(function(done) { - var expectedPayload3 = utils - .readExampleFile('./test/unit/examples/contextAvailabilityRequests/unregisterDevice3.json'); + describe('When a device is removed from the IoT Agent', function () { + beforeEach(function (done) { + const expectedPayload3 = utils.readExampleFile( + './test/unit/examples/contextAvailabilityRequests/unregisterDevice3.json' + ); nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .post('/NGSI9/registerContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerNewDevice1Success.json')); + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerNewDevice1Success.json' + ) + ); contextBrokerMock .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); contextBrokerMock .post('/NGSI9/registerContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerNewDevice2Success.json')); + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerNewDevice2Success.json' + ) + ); contextBrokerMock .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); contextBrokerMock .post('/NGSI9/registerContext', expectedPayload3) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/unregisterDevice1Success.json')); - - iotAgentLib.activate(iotAgentConfig, function(error) { - async.series([ - async.apply(iotAgentLib.register, device1), - async.apply(iotAgentLib.register, device2) - ], done); + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/unregisterDevice1Success.json' + ) + ); + + iotAgentLib.activate(iotAgentConfig, function (error) { + async.series( + [async.apply(iotAgentLib.register, device1), async.apply(iotAgentLib.register, device2)], + done + ); }); }); - it('should be removed from MongoDB', function(done) { - iotAgentLib.unregister(device1.id, 'smartGondor', 'gardens', function(error) { - iotAgentDb.db().collection('devices').find({}).toArray(function(err, docs) { - should.not.exist(err); - should.exist(docs); - should.exist(docs.length); - docs.length.should.equal(1); - done(); - }); + it('should be removed from MongoDB', function (done) { + iotAgentLib.unregister(device1.id, 'smartGondor', 'gardens', function (error) { + iotAgentDb + .db() + .collection('devices') + .find({}) + .toArray(function (err, docs) { + should.not.exist(err); + should.exist(docs); + should.exist(docs.length); + docs.length.should.equal(1); + done(); + }); }); }); }); - describe('When the registry is queried for a device using an arbitrary attribute', function() { - beforeEach(function(done) { + describe('When the registry is queried for a device using an arbitrary attribute', function () { + beforeEach(function (done) { contextBrokerMock = nock('http://192.168.1.1:1026') .post('/v1/updateContext') .times(10) .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); - var devices = []; + const devices = []; - for (var i = 0; i < 10; i++) { + for (let i = 0; i < 10; i++) { devices.push({ id: 'id' + i, type: 'Light' + i, @@ -438,41 +504,44 @@ describe('MongoDB Device Registry', function() { }); } - iotAgentLib.activate(iotAgentConfig, function(error) { - async.map(devices, iotAgentLib.register, function(error, results) { + iotAgentLib.activate(iotAgentConfig, function (error) { + async.map(devices, iotAgentLib.register, function (error, results) { done(); }); }); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.clearRegistry(done); }); - it('should return the appropriate device', function(done) { - iotAgentLib.getDevicesByAttribute('internalId', 'internal3', 'smartGondor', 'gardens', - function(error, devices) { - should.not.exist(error); - should.exist(devices); - devices.length.should.equal(1); - devices[0].id.should.equal('id3'); - done(); - }); + it('should return the appropriate device', function (done) { + iotAgentLib.getDevicesByAttribute('internalId', 'internal3', 'smartGondor', 'gardens', function ( + error, + devices + ) { + should.not.exist(error); + should.exist(devices); + devices.length.should.equal(1); + devices[0].id.should.equal('id3'); + done(); + }); }); }); - describe('When the list of devices is retrieved', function() { - beforeEach(function(done) { + describe('When the list of devices is retrieved', function () { + beforeEach(function (done) { contextBrokerMock = nock('http://192.168.1.1:1026') .post('/v1/updateContext') .times(10) .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); - var devices = []; + const devices = []; - for (var i = 0; i < 10; i++) { + for (let i = 0; i < 10; i++) { devices.push({ id: 'id' + i, type: 'Light' + i, @@ -489,25 +558,25 @@ describe('MongoDB Device Registry', function() { }); } - iotAgentLib.activate(iotAgentConfig, function(error) { - async.map(devices, iotAgentLib.register, function(error, results) { + iotAgentLib.activate(iotAgentConfig, function (error) { + async.map(devices, iotAgentLib.register, function (error, results) { done(); }); }); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.clearRegistry(done); }); - it('should return the limited number of devices', function(done) { - iotAgentLib.listDevices('smartGondor', 'gardens', 3, 2, function(error, result) { + it('should return the limited number of devices', function (done) { + iotAgentLib.listDevices('smartGondor', 'gardens', 3, 2, function (error, result) { should.not.exist(error); should.exist(result.devices); result.devices.length.should.equal(3); done(); }); }); - it('should return the total number of devices', function(done) { - iotAgentLib.listDevices('smartGondor', 'gardens', 3, 2, function(error, result) { + it('should return the total number of devices', function (done) { + iotAgentLib.listDevices('smartGondor', 'gardens', 3, 2, function (error, result) { should.not.exist(error); should.exist(result.count); result.count.should.equal(10); diff --git a/test/unit/ngsiService/active-devices-test.js b/test/unit/ngsiService/active-devices-test.js index 5297d4da1..b34f31dd1 100644 --- a/test/unit/ngsiService/active-devices-test.js +++ b/test/unit/ngsiService/active-devices-test.js @@ -20,106 +20,104 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - timekeeper = require('timekeeper'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const timekeeper = require('timekeeper'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - server: { - port: 4041 + BrokenLight: { + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'BrokenLight': { - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'Termometer': { - type: 'Termometer', - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ] - }, - 'Humidity': { - type: 'Humidity', - cbHost: 'http://192.168.1.1:3024', - commands: [], - lazy: [], - active: [ - { - name: 'humidity', - type: 'percentage' - } - ] - }, - 'Motion': { - type: 'Motion', - commands: [], - lazy: [], - staticAttributes: [ - { - 'name': 'location', - 'type': 'Vector', - 'value': '(123,523)' - } - ], - active: [ - { - name: 'humidity', - type: 'percentage' - } - ] - } + Termometer: { + type: 'Termometer', + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [] }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }; - -describe('NGSI-v1 - Active attributes test', function() { - var values = [ + Humidity: { + type: 'Humidity', + cbHost: 'http://192.168.1.1:3024', + commands: [], + lazy: [], + active: [ + { + name: 'humidity', + type: 'percentage' + } + ] + }, + Motion: { + type: 'Motion', + commands: [], + lazy: [], + staticAttributes: [ + { + name: 'location', + type: 'Vector', + value: '(123,523)' + } + ], + active: [ + { + name: 'humidity', + type: 'percentage' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; + +describe('NGSI-v1 - Active attributes test', function () { + const values = [ { name: 'state', type: 'Boolean', @@ -132,31 +130,32 @@ describe('NGSI-v1 - Active attributes test', function() { } ]; - beforeEach(function() { + beforeEach(function () { logger.setLevel('FATAL'); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); }); - describe('When the IoT Agent receives new information from a device', function() { - beforeEach(function(done) { + describe('When the IoT Agent receives new information from a device', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); iotAgentLib.activate(iotAgentConfig, done); }); - it('should change the value of the corresponding attribute in the context broker', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should change the value of the corresponding attribute in the context broker', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -164,30 +163,31 @@ describe('NGSI-v1 - Active attributes test', function() { }); }); - describe('When the IoT Agent receives new information from a device and the appendMode flag is on', function() { - beforeEach(function(done) { + describe('When the IoT Agent receives new information from a device and the appendMode flag is on', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContextAppendMode.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextAppendMode.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); iotAgentConfig.appendMode = true; iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentConfig.appendMode = false; done(); }); - it('should change the value of the corresponding attribute in the context broker', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should change the value of the corresponding attribute in the context broker', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -195,11 +195,11 @@ describe('NGSI-v1 - Active attributes test', function() { }); }); - describe('When the IoT Agent receives new information and the timestamp flag is on', function() { - var modifiedValues; + describe('When the IoT Agent receives new information and the timestamp flag is on', function () { + let modifiedValues; - beforeEach(function(done) { - var time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 + beforeEach(function (done) { + const time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 modifiedValues = [ { @@ -221,24 +221,25 @@ describe('NGSI-v1 - Active attributes test', function() { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContextTimestamp.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextTimestamp.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); iotAgentConfig.timestamp = true; iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { + afterEach(function (done) { delete iotAgentConfig.timestamp; timekeeper.reset(); done(); }); - it('should add the timestamp to the entity and all the attributes', function(done) { - iotAgentLib.update('light1', 'Light', '', modifiedValues, function(error) { + it('should add the timestamp to the entity and all the attributes', function (done) { + iotAgentLib.update('light1', 'Light', '', modifiedValues, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -246,12 +247,11 @@ describe('NGSI-v1 - Active attributes test', function() { }); }); - describe('When the IoT Agent receives new information, the timestamp flag is on' + - 'and timezone is defined', function() { - var modifiedValues; + describe('When the IoT Agent receives new information, the timestamp flag is onand timezone is defined', function () { + let modifiedValues; - beforeEach(function(done) { - var time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 + beforeEach(function (done) { + const time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 modifiedValues = [ { @@ -273,17 +273,18 @@ describe('NGSI-v1 - Active attributes test', function() { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContextTimestampTimezone.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextTimestampTimezone.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); iotAgentConfig.timestamp = true; iotAgentConfig.types.Light.timezone = 'America/Los_Angeles'; iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { + afterEach(function (done) { delete iotAgentConfig.timestamp; delete iotAgentConfig.types.Light.timezone; timekeeper.reset(); @@ -291,8 +292,8 @@ describe('NGSI-v1 - Active attributes test', function() { done(); }); - it('should add the timestamp to the entity and all the attributes', function(done) { - iotAgentLib.update('light1', 'Light', '', modifiedValues, function(error) { + it('should add the timestamp to the entity and all the attributes', function (done) { + iotAgentLib.update('light1', 'Light', '', modifiedValues, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -300,11 +301,11 @@ describe('NGSI-v1 - Active attributes test', function() { }); }); - describe('When the IoTA gets a set of values with a TimeInstant and the timestamp flag is on', function() { - var modifiedValues; + describe('When the IoTA gets a set of values with a TimeInstant and the timestamp flag is on', function () { + let modifiedValues; - beforeEach(function(done) { - var time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 + beforeEach(function (done) { + const time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 modifiedValues = [ { @@ -326,24 +327,25 @@ describe('NGSI-v1 - Active attributes test', function() { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContextTimestampOverride.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextTimestampOverride.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); iotAgentConfig.timestamp = true; iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { + afterEach(function (done) { delete iotAgentConfig.timestamp; timekeeper.reset(); done(); }); - it('should not override the received instant and should not add metadatas for this request', function(done) { - iotAgentLib.update('light1', 'Light', '', modifiedValues, function(error) { + it('should not override the received instant and should not add metadatas for this request', function (done) { + iotAgentLib.update('light1', 'Light', '', modifiedValues, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -351,11 +353,10 @@ describe('NGSI-v1 - Active attributes test', function() { }); }); - describe('When the IoTA gets a set of values with a TimeInstant which are not in ISO8601 format', function() { - var modifiedValues; - - beforeEach(function(done) { + describe('When the IoTA gets a set of values with a TimeInstant which are not in ISO8601 format', function () { + let modifiedValues; + beforeEach(function (done) { modifiedValues = [ { name: 'state', @@ -375,13 +376,13 @@ describe('NGSI-v1 - Active attributes test', function() { iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { + afterEach(function (done) { delete iotAgentConfig.timestamp; done(); }); - it('should fail with a 400 BAD_TIMESTAMP error', function(done) { - iotAgentLib.update('light1', 'Light', '', modifiedValues, function(error) { + it('should fail with a 400 BAD_TIMESTAMP error', function (done) { + iotAgentLib.update('light1', 'Light', '', modifiedValues, function (error) { should.exist(error); error.code.should.equal(400); error.name.should.equal('BAD_TIMESTAMP'); @@ -390,12 +391,11 @@ describe('NGSI-v1 - Active attributes test', function() { }); }); - describe('When the IoTA gets a set of values with a TimeInstant which are in ISO8601 format ' + - 'without milis', function() { - var modifiedValues; + describe('When the IoTA gets a set of values with a TimeInstant which are in ISO8601 format without milis', function () { + let modifiedValues; - beforeEach(function(done) { - var time = new Date(1666477342000); // 2022-10-22T22:22:22Z + beforeEach(function (done) { + const time = new Date(1666477342000); // 2022-10-22T22:22:22Z modifiedValues = [ { @@ -417,26 +417,28 @@ describe('NGSI-v1 - Active attributes test', function() { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/' + - 'updateContextTimestampOverrideWithoutMilis.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile( + './test/unit/examples/contextRequests/updateContextTimestampOverrideWithoutMilis.json' + ) + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); iotAgentConfig.timestamp = true; iotAgentConfig.types.Light.timezone = 'America/Los_Angeles'; iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { + afterEach(function (done) { delete iotAgentConfig.timestamp; delete iotAgentConfig.types.Light.timezone; timekeeper.reset(); done(); }); - it('should not fail', function(done) { - iotAgentLib.update('light1', 'Light', '', modifiedValues, function(error) { + it('should not fail', function (done) { + iotAgentLib.update('light1', 'Light', '', modifiedValues, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -444,12 +446,11 @@ describe('NGSI-v1 - Active attributes test', function() { }); }); - describe('When the IoTA gets a set of values with a TimeInstant, the timestamp flag is on' + - 'and timezone is defined', function() { - var modifiedValues; + describe('When the IoTA gets a set of values with a TimeInstant, the timestamp flag is onand timezone is defined', function () { + let modifiedValues; - beforeEach(function(done) { - var time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 + beforeEach(function (done) { + const time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 modifiedValues = [ { @@ -471,17 +472,18 @@ describe('NGSI-v1 - Active attributes test', function() { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContextTimestampOverride.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextTimestampOverride.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); iotAgentConfig.timestamp = true; iotAgentConfig.types.Light.timezone = 'America/Los_Angeles'; iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { + afterEach(function (done) { delete iotAgentConfig.timestamp; delete iotAgentConfig.types.Light.timezone; timekeeper.reset(); @@ -489,8 +491,8 @@ describe('NGSI-v1 - Active attributes test', function() { done(); }); - it('should not override the received instant and should not add metadatas for this request', function(done) { - iotAgentLib.update('light1', 'Light', '', modifiedValues, function(error) { + it('should not override the received instant and should not add metadatas for this request', function (done) { + iotAgentLib.update('light1', 'Light', '', modifiedValues, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -498,15 +500,15 @@ describe('NGSI-v1 - Active attributes test', function() { }); }); - describe('When the IoT Agent receives information from a device whose type doesn\'t have a type name', function() { - beforeEach(function(done) { + describe("When the IoT Agent receives information from a device whose type doesn't have a type name", function () { + beforeEach(function (done) { nock.cleanAll(); iotAgentLib.activate(iotAgentConfig, done); }); - it('should fail with a 500 TYPE_NOT_FOUND error', function(done) { - iotAgentLib.update('light1', 'BrokenLight', '', values, function(error) { + it('should fail with a 500 TYPE_NOT_FOUND error', function (done) { + iotAgentLib.update('light1', 'BrokenLight', '', values, function (error) { should.exist(error); error.code.should.equal(500); error.name.should.equal('TYPE_NOT_FOUND'); @@ -515,23 +517,24 @@ describe('NGSI-v1 - Active attributes test', function() { }); }); - describe('When the Context Broker returns an HTTP error code updating an entity', function() { - beforeEach(function(done) { + describe('When the Context Broker returns an HTTP error code updating an entity', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Failed.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Failed.json')); iotAgentLib.activate(iotAgentConfig, done); }); - it('should return ENTITY_GENERIC_ERROR an error to the caller', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should return ENTITY_GENERIC_ERROR an error to the caller', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.exist(error); should.exist(error.name); error.details.code.should.equal('413'); @@ -543,23 +546,24 @@ describe('NGSI-v1 - Active attributes test', function() { }); }); - describe('When the Context Broker returns an application error code updating an entity', function() { - beforeEach(function(done) { + describe('When the Context Broker returns an application error code updating an entity', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext2Failed.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext2Failed.json')); iotAgentLib.activate(iotAgentConfig, done); }); - it('should return ENTITY_GENERIC_ERROR an error to the caller', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should return ENTITY_GENERIC_ERROR an error to the caller', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.exist(error); should.exist(error.name); error.name.should.equal('ENTITY_GENERIC_ERROR'); @@ -568,23 +572,24 @@ describe('NGSI-v1 - Active attributes test', function() { }); }); - describe('When there is a transport error connecting to the Context Broker', function() { - beforeEach(function(done) { + describe('When there is a transport error connecting to the Context Broker', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json')) - .reply(500, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext2Failed.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json') + ) + .reply(500, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext2Failed.json')); iotAgentLib.activate(iotAgentConfig, done); }); - it('should return a ENTITY_GENERIC_ERROR error to the caller', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should return a ENTITY_GENERIC_ERROR error to the caller', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.exist(error); should.exist(error.name); error.name.should.equal('ENTITY_GENERIC_ERROR'); @@ -596,23 +601,24 @@ describe('NGSI-v1 - Active attributes test', function() { }); }); - describe('When the IoT Agent recieves information for a type with a configured Context Broker', function() { - beforeEach(function(done) { + describe('When the IoT Agent recieves information for a type with a configured Context Broker', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:3024') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext2.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext2.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); iotAgentLib.activate(iotAgentConfig, done); }); - it('should use the Context Broker defined by the type', function(done) { - iotAgentLib.update('humSensor', 'Humidity', '', values, function(error) { + it('should use the Context Broker defined by the type', function (done) { + iotAgentLib.update('humSensor', 'Humidity', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -620,8 +626,8 @@ describe('NGSI-v1 - Active attributes test', function() { }); }); - describe('When an IoT Agent receives information for a type with static attributes', function() { - var newValues = [ + describe('When an IoT Agent receives information for a type with static attributes', function () { + const newValues = [ { name: 'moving', type: 'Boolean', @@ -629,21 +635,22 @@ describe('NGSI-v1 - Active attributes test', function() { } ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContextStaticAttributes.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextStaticAttributes.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); iotAgentLib.activate(iotAgentConfig, done); }); - it('should decorate the entity with the static attributes', function(done) { - iotAgentLib.update('motion1', 'Motion', '', newValues, function(error) { + it('should decorate the entity with the static attributes', function (done) { + iotAgentLib.update('motion1', 'Motion', '', newValues, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -651,9 +658,8 @@ describe('NGSI-v1 - Active attributes test', function() { }); }); - describe('When the IoT Agent receives new information from a device and CB' + - 'is defined using environment variables', function() { - beforeEach(function(done) { + describe('When the IoT Agent receives new information from a device and CBis defined using environment variables', function () { + beforeEach(function (done) { process.env.IOTA_CB_HOST = 'cbhost'; nock.cleanAll(); @@ -661,23 +667,24 @@ describe('NGSI-v1 - Active attributes test', function() { contextBrokerMock = nock('http://cbhost:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext1.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); iotAgentLib.activate(iotAgentConfig, done); }); - it('should change the value of the corresponding attribute in the context broker', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should change the value of the corresponding attribute in the context broker', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); - afterEach(function(done) { + afterEach(function (done) { process.env.IOTA_CB_HOST = ''; done(); }); diff --git a/test/unit/ngsiService/queryDeviceInformationInCb-test.js b/test/unit/ngsiService/queryDeviceInformationInCb-test.js index 20380c8b5..4696285a3 100644 --- a/test/unit/ngsiService/queryDeviceInformationInCb-test.js +++ b/test/unit/ngsiService/queryDeviceInformationInCb-test.js @@ -20,135 +20,130 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] + }, + BrokenLight: { + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - server: { - port: 4041 + Termometer: { + type: 'Termometer', + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [] }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'BrokenLight': { - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'Termometer': { - type: 'Termometer', - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ] - }, - 'Humidity': { - type: 'Humidity', - cbHost: 'http://192.168.1.1:3024', - commands: [], - lazy: [], - active: [ - { - name: 'humidity', - type: 'percentage' - } - ] - }, - 'Motion': { - type: 'Motion', - commands: [], - lazy: [], - staticAttributes: [ - { - 'name': 'location', - 'type': 'Vector', - 'value': '(123,523)' - } - ], - active: [ - { - name: 'humidity', - type: 'percentage' - } - ] - } + Humidity: { + type: 'Humidity', + cbHost: 'http://192.168.1.1:3024', + commands: [], + lazy: [], + active: [ + { + name: 'humidity', + type: 'percentage' + } + ] }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }; - -describe('Query device information in the Context Broker', function() { - var attributes = [ - 'state', - 'dimming' - ]; - - beforeEach(function(done) { + Motion: { + type: 'Motion', + commands: [], + lazy: [], + staticAttributes: [ + { + name: 'location', + type: 'Vector', + value: '(123,523)' + } + ], + active: [ + { + name: 'humidity', + type: 'percentage' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; + +describe('Query device information in the Context Broker', function () { + const attributes = ['state', 'dimming']; + + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); }); - describe('When the user requests information about a registered device', function() { - beforeEach(function() { + describe('When the user requests information about a registered device', function () { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/queryContext', - utils.readExampleFile('./test/unit/examples/contextRequests/queryContext1.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/queryContext1Success.json')); + .post( + '/v1/queryContext', + utils.readExampleFile('./test/unit/examples/contextRequests/queryContext1.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/queryContext1Success.json')); }); - it('should return the information about the desired attributes', function(done) { - iotAgentLib.query('light1', 'Light', '', attributes, function(error) { + it('should return the information about the desired attributes', function (done) { + iotAgentLib.query('light1', 'Light', '', attributes, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -156,22 +151,22 @@ describe('Query device information in the Context Broker', function() { }); }); - describe('When the user requests information about a device that it\'s not in the CB', function() { - beforeEach(function() { + describe("When the user requests information about a device that it's not in the CB", function () { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/queryContext', - utils.readExampleFile('./test/unit/examples/contextRequests/queryContext2.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/queryContext2Error.json')); - + .post( + '/v1/queryContext', + utils.readExampleFile('./test/unit/examples/contextRequests/queryContext2.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/queryContext2Error.json')); }); - it('should return a DEVICE_NOT_FOUND_ERROR', function(done) { - iotAgentLib.query('light3', 'Light', '', attributes, function(error) { + it('should return a DEVICE_NOT_FOUND_ERROR', function (done) { + iotAgentLib.query('light3', 'Light', '', attributes, function (error) { should.exist(error); error.name.should.equal('DEVICE_NOT_FOUND'); done(); @@ -179,22 +174,22 @@ describe('Query device information in the Context Broker', function() { }); }); - describe('When the user requests information and there are multiple responses, one of them a failure', function() { - beforeEach(function() { + describe('When the user requests information and there are multiple responses, one of them a failure', function () { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/queryContext', - utils.readExampleFile('./test/unit/examples/contextRequests/queryContext2.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/queryContext3Error.json')); - + .post( + '/v1/queryContext', + utils.readExampleFile('./test/unit/examples/contextRequests/queryContext2.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/queryContext3Error.json')); }); - it('should return a ATTRIBUTE_NOT_FOUND_ERROR', function(done) { - iotAgentLib.query('light3', 'Light', '', attributes, function(error) { + it('should return a ATTRIBUTE_NOT_FOUND_ERROR', function (done) { + iotAgentLib.query('light3', 'Light', '', attributes, function (error) { should.exist(error); error.name.should.equal('ATTRIBUTE_NOT_FOUND'); done(); @@ -202,22 +197,25 @@ describe('Query device information in the Context Broker', function() { }); }); - describe('When the user requests information and there is an unknown errorCode in the response', function() { - beforeEach(function() { + describe('When the user requests information and there is an unknown errorCode in the response', function () { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/queryContext', - utils.readExampleFile('./test/unit/examples/contextRequests/queryContext2.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/queryContext2UnknownError.json')); - + .post( + '/v1/queryContext', + utils.readExampleFile('./test/unit/examples/contextRequests/queryContext2.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/queryContext2UnknownError.json') + ); }); - it('should return a ENTITY_GENERIC_ERROR', function(done) { - iotAgentLib.query('light3', 'Light', '', attributes, function(error) { + it('should return a ENTITY_GENERIC_ERROR', function (done) { + iotAgentLib.query('light3', 'Light', '', attributes, function (error) { should.exist(error); should.exist(error.name); should.exist(error.details.code); @@ -229,5 +227,4 @@ describe('Query device information in the Context Broker', function() { }); }); }); - }); diff --git a/test/unit/ngsiService/staticAttributes-test.js b/test/unit/ngsiService/staticAttributes-test.js index 747f1fe58..52e6b7270 100644 --- a/test/unit/ngsiService/staticAttributes-test.js +++ b/test/unit/ngsiService/staticAttributes-test.js @@ -20,69 +20,69 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - async = require('async'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ], - staticAttributes: [ - { - name: 'attr1', - type: 'type1' - }, - { - name: 'attr2', - type: 'type2' - }, - { - name: 'attr3', - type: 'type3' - }, - { - name: 'attr4', - type: 'type4' - }, - ] - } - }, - timestamp: true, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }; +/* eslint-disable no-unused-vars */ +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const async = require('async'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ], + staticAttributes: [ + { + name: 'attr1', + type: 'type1' + }, + { + name: 'attr2', + type: 'type2' + }, + { + name: 'attr3', + type: 'type3' + }, + { + name: 'attr4', + type: 'type4' + } + ] + } + }, + timestamp: true, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; -describe('NGSI-v1 - Static attributes test', function() { - var values = [ +describe('NGSI-v1 - Static attributes test', function () { + const values = [ { name: 'state', type: 'Boolean', @@ -95,16 +95,16 @@ describe('NGSI-v1 - Static attributes test', function() { } ]; - beforeEach(function() { + beforeEach(function () { logger.setLevel('FATAL'); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); }); - describe('When information from a device with multiple static attributes and metadata is sent', function() { - beforeEach(function(done) { + describe('When information from a device with multiple static attributes and metadata is sent', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') @@ -112,36 +112,37 @@ describe('NGSI-v1 - Static attributes test', function() { .matchHeader('fiware-servicepath', 'gardens') .post('/v1/updateContext') .times(4) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')) - .post('/v1/updateContext', function(body) { - var metadatas = 0; + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')) + .post('/v1/updateContext', function (body) { + let metadatas = 0; - for (var i = 0; i < body.contextElements[0].attributes.length; i++) { + for (let i = 0; i < body.contextElements[0].attributes.length; i++) { if (body.contextElements[0].attributes[i].metadatas) { metadatas += body.contextElements[0].attributes[i].metadatas.length; } } return metadatas === body.contextElements[0].attributes.length - 1; }) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); iotAgentLib.activate(iotAgentConfig, done); }); - it('should send a single TimeInstant per attribute', function(done) { - async.series([ - async.apply(iotAgentLib.update, 'light1', 'Light', '', values), - async.apply(iotAgentLib.update, 'light1', 'Light', '', values), - async.apply(iotAgentLib.update, 'light1', 'Light', '', values), - async.apply(iotAgentLib.update, 'light1', 'Light', '', values), - async.apply(iotAgentLib.update, 'light1', 'Light', '', values) - ], function(error, results) { - should.not.exist(error); - contextBrokerMock.done(); - done(); - }); + it('should send a single TimeInstant per attribute', function (done) { + async.series( + [ + async.apply(iotAgentLib.update, 'light1', 'Light', '', values), + async.apply(iotAgentLib.update, 'light1', 'Light', '', values), + async.apply(iotAgentLib.update, 'light1', 'Light', '', values), + async.apply(iotAgentLib.update, 'light1', 'Light', '', values), + async.apply(iotAgentLib.update, 'light1', 'Light', '', values) + ], + function (error, results) { + should.not.exist(error); + contextBrokerMock.done(); + done(); + } + ); }); }); }); diff --git a/test/unit/ngsiService/subscriptions-test.js b/test/unit/ngsiService/subscriptions-test.js index 0975977cc..793c2ce2c 100644 --- a/test/unit/ngsiService/subscriptions-test.js +++ b/test/unit/ngsiService/subscriptions-test.js @@ -20,33 +20,34 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - request = require('request'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 - }, - types: {}, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }; - -describe('NGSI-v1 - Subscription tests', function() { - beforeEach(function(done) { - var optionsProvision = { + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const request = require('request'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: {}, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; + +describe('NGSI-v1 - Subscription tests', function () { + beforeEach(function (done) { + const optionsProvision = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), @@ -58,43 +59,51 @@ describe('NGSI-v1 - Subscription tests', function() { nock.cleanAll(); - iotAgentLib.activate(iotAgentConfig, function() { + iotAgentLib.activate(iotAgentConfig, function () { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/createMinimumProvisionedDevice.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/createMinimumProvisionedDevice.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/subscribeContext', - utils.readExampleFile('./test/unit/examples/subscriptionRequests/simpleSubscriptionRequest.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/subscriptionResponses/simpleSubscriptionSuccess.json')); - - iotAgentLib.clearAll(function() { - request(optionsProvision, function(error, result, body) { + .post( + '/v1/subscribeContext', + utils.readExampleFile('./test/unit/examples/subscriptionRequests/simpleSubscriptionRequest.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/subscriptionResponses/simpleSubscriptionSuccess.json') + ); + + iotAgentLib.clearAll(function () { + request(optionsProvision, function (error, result, body) { done(); }); }); }); }); - afterEach(function(done) { + afterEach(function (done) { nock.cleanAll(); iotAgentLib.setNotificationHandler(); - iotAgentLib.clearAll(function() { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When a client invokes the subscribe() function for device', function() { - it('should send the appropriate request to the Context Broker', function(done) { - iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function(error, device) { - iotAgentLib.subscribe(device, ['attr_name'], null, function(error) { + describe('When a client invokes the subscribe() function for device', function () { + it('should send the appropriate request to the Context Broker', function (done) { + iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function (error, device) { + iotAgentLib.subscribe(device, ['attr_name'], null, function (error) { should.not.exist(error); contextBrokerMock.done(); @@ -103,10 +112,10 @@ describe('NGSI-v1 - Subscription tests', function() { }); }); }); - it('should store the subscription ID in the Device Registry', function(done) { - iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function(error, device) { - iotAgentLib.subscribe(device, ['attr_name'], null, function(error) { - iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function(error, device) { + it('should store the subscription ID in the Device Registry', function (done) { + iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function (error, device) { + iotAgentLib.subscribe(device, ['attr_name'], null, function (error) { + iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function (error, device) { should.not.exist(error); should.exist(device); should.exist(device.subscriptions); @@ -119,23 +128,27 @@ describe('NGSI-v1 - Subscription tests', function() { }); }); }); - describe('When a client invokes the unsubscribe() function for an entity', function() { - beforeEach(function(done) { + describe('When a client invokes the unsubscribe() function for an entity', function () { + beforeEach(function (done) { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/unsubscribeContext', - utils.readExampleFile('./test/unit/examples/subscriptionRequests/simpleSubscriptionRemove.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/subscriptionResponses/simpleSubscriptionSuccess.json')); + .post( + '/v1/unsubscribeContext', + utils.readExampleFile('./test/unit/examples/subscriptionRequests/simpleSubscriptionRemove.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/subscriptionResponses/simpleSubscriptionSuccess.json') + ); done(); }); - it('should delete the subscription from the CB', function(done) { - iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function(error, device) { - iotAgentLib.subscribe(device, ['attr_name'], null, function(error) { - iotAgentLib.unsubscribe(device, '51c0ac9ed714fb3b37d7d5a8', function(error) { - iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function(error, device) { + it('should delete the subscription from the CB', function (done) { + iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function (error, device) { + iotAgentLib.subscribe(device, ['attr_name'], null, function (error) { + iotAgentLib.unsubscribe(device, '51c0ac9ed714fb3b37d7d5a8', function (error) { + iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function (error, device) { contextBrokerMock.done(); done(); }); @@ -143,11 +156,11 @@ describe('NGSI-v1 - Subscription tests', function() { }); }); }); - it('should remove the id from the subscriptions array', function(done) { - iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function(error, device) { - iotAgentLib.subscribe(device, ['attr_name'], null, function(error) { - iotAgentLib.unsubscribe(device, '51c0ac9ed714fb3b37d7d5a8', function(error) { - iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function(error, device) { + it('should remove the id from the subscriptions array', function (done) { + iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function (error, device) { + iotAgentLib.subscribe(device, ['attr_name'], null, function (error) { + iotAgentLib.unsubscribe(device, '51c0ac9ed714fb3b37d7d5a8', function (error) { + iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function (error, device) { should.not.exist(error); should.exist(device); should.exist(device.subscriptions); @@ -159,23 +172,27 @@ describe('NGSI-v1 - Subscription tests', function() { }); }); }); - describe('When a client removes a device from the registry', function() { - beforeEach(function(done) { + describe('When a client removes a device from the registry', function () { + beforeEach(function (done) { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/unsubscribeContext', - utils.readExampleFile('./test/unit/examples/subscriptionRequests/simpleSubscriptionRemove.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/subscriptionResponses/simpleSubscriptionSuccess.json')); + .post( + '/v1/unsubscribeContext', + utils.readExampleFile('./test/unit/examples/subscriptionRequests/simpleSubscriptionRemove.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/subscriptionResponses/simpleSubscriptionSuccess.json') + ); done(); }); - it('should delete the subscription from the CB', function(done) { - iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function(error, device) { - iotAgentLib.subscribe(device, ['attr_name'], null, function(error) { - iotAgentLib.unregister(device.id, 'smartGondor', '/gardens', function(error) { + it('should delete the subscription from the CB', function (done) { + iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function (error, device) { + iotAgentLib.subscribe(device, ['attr_name'], null, function (error) { + iotAgentLib.unregister(device.id, 'smartGondor', '/gardens', function (error) { contextBrokerMock.done(); done(); }); @@ -183,27 +200,26 @@ describe('NGSI-v1 - Subscription tests', function() { }); }); }); - describe('When a new notification comes to the IoTAgent', function() { - beforeEach(function(done) { - iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function(error, device) { - iotAgentLib.subscribe(device, ['attr_name'], null, function(error) { + describe('When a new notification comes to the IoTAgent', function () { + beforeEach(function (done) { + iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function (error, device) { + iotAgentLib.subscribe(device, ['attr_name'], null, function (error) { done(); }); }); }); - it('should invoke the user defined callback', function(done) { - var notificationOptions = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/subscriptionRequests/simpleNotification.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - - executedHandler = false; + it('should invoke the user defined callback', function (done) { + const notificationOptions = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/subscriptionRequests/simpleNotification.json'), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + let executedHandler = false; function mockedHandler(device, notification, callback) { executedHandler = true; @@ -212,26 +228,26 @@ describe('NGSI-v1 - Subscription tests', function() { iotAgentLib.setNotificationHandler(mockedHandler); - request(notificationOptions, function(error, response, body) { + request(notificationOptions, function (error, response, body) { should.not.exist(error); executedHandler.should.equal(true); done(); }); }); - it('should invoke all the notification middlewares before the user defined callback', function(done) { - var notificationOptions = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/subscriptionRequests/simpleNotification.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - executedMiddlewares = false, - executedHandler = false, - modifiedData = false; + it('should invoke all the notification middlewares before the user defined callback', function (done) { + const notificationOptions = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/subscriptionRequests/simpleNotification.json'), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + let executedMiddlewares = false; + let executedHandler = false; + let modifiedData = false; function mockedHandler(device, notification, callback) { executedHandler = true; @@ -253,7 +269,7 @@ describe('NGSI-v1 - Subscription tests', function() { iotAgentLib.addNotificationMiddleware(mockedMiddleware); iotAgentLib.setNotificationHandler(mockedHandler); - request(notificationOptions, function(error, response, body) { + request(notificationOptions, function (error, response, body) { should.not.exist(error); executedHandler.should.equal(true); executedMiddlewares.should.equal(true); @@ -261,21 +277,27 @@ describe('NGSI-v1 - Subscription tests', function() { done(); }); }); - it('should get the correspondent device information', function(done) { - var notificationOptions = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/subscriptionRequests/simpleNotification.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - rightFields = false; + it('should get the correspondent device information', function (done) { + const notificationOptions = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/subscriptionRequests/simpleNotification.json'), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + let rightFields = false; function mockedHandler(device, data, callback) { - if (device && device.id === 'MicroLight1' && device.name === 'FirstMicroLight' && - data && data.length === 1 && data[0].name === 'attr_name') { + if ( + device && + device.id === 'MicroLight1' && + device.name === 'FirstMicroLight' && + data && + data.length === 1 && + data[0].name === 'attr_name' + ) { rightFields = true; } @@ -284,7 +306,7 @@ describe('NGSI-v1 - Subscription tests', function() { iotAgentLib.setNotificationHandler(mockedHandler); - request(notificationOptions, function(error, response, body) { + request(notificationOptions, function (error, response, body) { should.not.exist(error); rightFields.should.equal(true); @@ -292,19 +314,18 @@ describe('NGSI-v1 - Subscription tests', function() { }); }); }); - describe('When a new notification arrives to the IOTA with a non-200 code', function() { - it('should not call the handler', function(done) { - var notificationOptions = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/subscriptionRequests/errorNotification.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - - executedHandler = false; + describe('When a new notification arrives to the IOTA with a non-200 code', function () { + it('should not call the handler', function (done) { + const notificationOptions = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/subscriptionRequests/errorNotification.json'), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + let executedHandler = false; function mockedHandler(device, notification, callback) { executedHandler = true; @@ -313,7 +334,7 @@ describe('NGSI-v1 - Subscription tests', function() { iotAgentLib.setNotificationHandler(mockedHandler); - request(notificationOptions, function(error, response, body) { + request(notificationOptions, function (error, response, body) { should.not.exist(error); executedHandler.should.equal(false); diff --git a/test/unit/ngsiv2/expressions/expressionBasedTransformations-test.js b/test/unit/ngsiv2/expressions/expressionBasedTransformations-test.js index 52f213fef..1538b01f3 100644 --- a/test/unit/ngsiv2/expressions/expressionBasedTransformations-test.js +++ b/test/unit/ngsiv2/expressions/expressionBasedTransformations-test.js @@ -22,183 +22,181 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -/* jshint camelcase: false */ - -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' + +/* eslint-disable no-useless-concat */ + +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Number' + }, + { + object_id: 'e', + name: 'consumption', + type: 'Number' + }, + { + object_id: 'a', + name: 'alive', + type: 'None' + }, + { + object_id: 'u', + name: 'updated', + type: 'Boolean' + }, + { + object_id: 'm', + name: 'manufacturer', + type: 'Object' + }, + { + object_id: 'r', + name: 'revisions', + type: 'Array' + }, + { + object_id: 'x', + name: 'consumption_x', + type: 'Number', + expression: '${@pressure * 20}' + } + ] }, - server: { - port: 4041 + LightError: { + commands: [], + type: 'Light', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Number', + expression: '${@pressure * / 20}' + } + ] }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Number' - }, - { - object_id: 'e', - name: 'consumption', - type: 'Number' - }, - { - object_id: 'a', - name: 'alive', - type: 'None', - }, - { - object_id: 'u', - name: 'updated', - type: 'Boolean', - }, - { - object_id: 'm', - name: 'manufacturer', - type: 'Object', - }, - { - object_id: 'r', - name: 'revisions', - type: 'Array', - }, - { - object_id: 'x', - name: 'consumption_x', - type: 'Number', - expression: '${@pressure * 20}' - } - ] - }, - 'LightError': { - commands: [], - type: 'Light', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Number', - expression: '${@pressure * / 20}' - } - ] - }, - 'WeatherStation': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Number', - expression: '${@pressure * 20}' - }, - { - object_id: 'e', - name: 'consumption', - type: 'Number', - expression: '${@consumption * 20}' - }, - { - object_id: 'h', - name: 'humidity', - type: 'Percentage' - }, - { - name: 'weather', - type: 'Summary', - expression: 'Humidity ${@humidity / 2} and pressure ${@pressure * 20}' - }, - { - object_id: 'a', - name: 'alive', - type: 'None', - expression: '${@alive * 20}' - }, - { - object_id: 'u', - name: 'updated', - type: 'Boolean', - expression: '${@updated * 20}' - }, - ] - }, - 'WeatherStationMultiple': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - - { - object_id: 'p', - name: 'pressure', - type: 'Number', - expression: '${trim(@pressure)}' - }, - { - object_id: 'p25', - name: 'pressure25', - type: 'Number' - }, - { - object_id: 'e', - name: 'consumption', - type: 'Number', - expression: '${trim(@consumption)}' - }, - { - object_id: 'h', - name: 'humidity12', - type: 'Percentage' - }, - { - name: 'weather', - type: 'Summary', - expression: 'Humidity ${@humidity12 / 2} and pressure ${@pressure25 * 20}' - }, - { - object_id: 'a', - name: 'alive', - type: 'None', - expression: '${trim(@alive)}' - }, - { - object_id: 'u', - name: 'updated', - type: 'Boolean', - expression: '${trim(@updated)}' - }, - ] - } + WeatherStation: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Number', + expression: '${@pressure * 20}' + }, + { + object_id: 'e', + name: 'consumption', + type: 'Number', + expression: '${@consumption * 20}' + }, + { + object_id: 'h', + name: 'humidity', + type: 'Percentage' + }, + { + name: 'weather', + type: 'Summary', + expression: 'Humidity ${@humidity / 2} and pressure ${@pressure * 20}' + }, + { + object_id: 'a', + name: 'alive', + type: 'None', + expression: '${@alive * 20}' + }, + { + object_id: 'u', + name: 'updated', + type: 'Boolean', + expression: '${@updated * 20}' + } + ] }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' - }; - -describe('NGSI-v2 - Expression-based transformations plugin', function() { - beforeEach(function(done) { + WeatherStationMultiple: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Number', + expression: '${trim(@pressure)}' + }, + { + object_id: 'p25', + name: 'pressure25', + type: 'Number' + }, + { + object_id: 'e', + name: 'consumption', + type: 'Number', + expression: '${trim(@consumption)}' + }, + { + object_id: 'h', + name: 'humidity12', + type: 'Percentage' + }, + { + name: 'weather', + type: 'Summary', + expression: 'Humidity ${@humidity12 / 2} and pressure ${@pressure25 * 20}' + }, + { + object_id: 'a', + name: 'alive', + type: 'None', + expression: '${trim(@alive)}' + }, + { + object_id: 'u', + name: 'updated', + type: 'Boolean', + expression: '${trim(@updated)}' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; + +describe('NGSI-v2 - Expression-based transformations plugin', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.attributeAlias.update); iotAgentLib.addQueryMiddleware(iotAgentLib.dataPlugins.attributeAlias.query); iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.expressionTransformation.update); @@ -207,15 +205,15 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When an update comes for expressions with syntax errors', function() { + describe('When an update comes for expressions with syntax errors', function () { // Case: Update for an attribute with bad expression - var values = [ + const values = [ { name: 'p', type: 'centigrades', @@ -223,8 +221,8 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { } ]; - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'LightError', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'LightError', '', values, function (error) { should.exist(error); error.name.should.equal('INVALID_EXPRESSION'); error.code.should.equal(400); @@ -233,9 +231,9 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { }); }); - describe('When there are expression attributes that are just calculated (not sent by the device)', function() { + describe('When there are expression attributes that are just calculated (not sent by the device)', function () { // Case: Expression which results is sent as a new attribute - var values = [ + const values = [ { name: 'p', type: 'Number', @@ -248,20 +246,24 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin2.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin2.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - it('should calculate them and add them to the payload', function(done) { - iotAgentLib.update('ws1', 'WeatherStation', '', values, function(error) { + it('should calculate them and add them to the payload', function (done) { + iotAgentLib.update('ws1', 'WeatherStation', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -269,10 +271,10 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { }); }); - describe('When an expression with multiple variables with numbers arrive', function() { + describe('When an expression with multiple variables with numbers arrive', function () { // Case: Update for integer and string attributes with expression - var values = [ + const values = [ { name: 'p25', type: 'Number', @@ -285,20 +287,24 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin4.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin4.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - it('should calculate it and add it to the payload', function(done) { - iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function(error) { + it('should calculate it and add it to the payload', function (done) { + iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -306,9 +312,9 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { }); }); - describe('When an update comes for attributes without expressions and type integer', function() { + describe('When an update comes for attributes without expressions and type integer', function () { // Case: Update for an integer attribute without expression - var values = [ + const values = [ { name: 'e', type: 'Number', @@ -316,20 +322,24 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin11.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin11.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -337,9 +347,9 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { }); }); - describe('When an update comes for attributes with numeric expressions and type integer', function() { + describe('When an update comes for attributes with numeric expressions and type integer', function () { // Case: Update for an integer attribute with arithmetic expression - var values = [ + const values = [ { name: 'p', type: 'Number', @@ -347,20 +357,24 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin1.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin1.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStation', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStation', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -368,9 +382,9 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { }); }); - describe('When an update comes for attributes with string expression and type integer', function() { + describe('When an update comes for attributes with string expression and type integer', function () { // Case: Update for an integer attribute with string expression - var values = [ + const values = [ { name: 'e', type: 'Number', @@ -378,20 +392,24 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin11.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin11.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -399,10 +417,10 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { }); }); - describe('When an update comes for attributes without expressions and type float', function() { + describe('When an update comes for attributes without expressions and type float', function () { // Case: Update for a Float attribute without expressions - var values = [ + const values = [ { name: 'e', type: 'Number', @@ -410,20 +428,24 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin3.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin3.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -431,10 +453,10 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { }); }); - describe('When an update comes for attributes with numeric expressions and type float', function() { + describe('When an update comes for attributes with numeric expressions and type float', function () { // Case: Update for a Float attribute with arithmetic expression - var values = [ + const values = [ { name: 'e', type: 'Number', @@ -442,20 +464,24 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin8.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin8.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStation', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStation', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -463,10 +489,10 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { }); }); - describe('When an update comes for attributes with string expressions and type float', function() { + describe('When an update comes for attributes with string expressions and type float', function () { // Case: Update for a Float attribute with string expression - var values = [ + const values = [ { name: 'e', type: 'Number', @@ -474,20 +500,24 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin3.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin3.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -495,10 +525,10 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { }); }); - describe('When an update comes for attributes without expressions and NULL type', function() { + describe('When an update comes for attributes without expressions and NULL type', function () { // Case: Update for a Null attribute without expression - var values = [ + const values = [ { name: 'a', type: 'None', @@ -506,20 +536,24 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin5.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin5.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -527,10 +561,10 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { }); }); - describe('When an update comes for attributes with numeric expressions and NULL type', function() { + describe('When an update comes for attributes with numeric expressions and NULL type', function () { // Case: Update for a Null attribute with arithmetic expression - var values = [ + const values = [ { name: 'a', type: 'None', @@ -538,20 +572,24 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin5.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin5.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStation', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStation', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -559,10 +597,10 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { }); }); - describe('When an update comes for attributes with string expressions and NULL type', function() { + describe('When an update comes for attributes with string expressions and NULL type', function () { // Case: Update for a Null attribute with string expression - var values = [ + const values = [ { name: 'a', type: 'None', @@ -570,20 +608,24 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin5.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin5.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -591,10 +633,10 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { }); }); - describe('When an update comes for attributes without expressions and Boolean type', function() { + describe('When an update comes for attributes without expressions and Boolean type', function () { // Case: Update for a Boolean attribute without expression - var values = [ + const values = [ { name: 'u', type: 'Boolean', @@ -602,20 +644,24 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin9.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin9.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -623,10 +669,10 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { }); }); - describe('When an update comes for attributes with numeric expressions and Boolean type', function() { + describe('When an update comes for attributes with numeric expressions and Boolean type', function () { // Case: Update for a Boolean attribute with arithmetic expression - var values = [ + const values = [ { name: 'u', type: 'Boolean', @@ -634,20 +680,24 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin10.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin10.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStation', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStation', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -655,9 +705,9 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { }); }); - describe('When an update comes for attributes with string expressions and Boolean type', function() { + describe('When an update comes for attributes with string expressions and Boolean type', function () { // Case: Update for a Boolean attribute with string expression - var values = [ + const values = [ { name: 'u', type: 'Boolean', @@ -665,20 +715,24 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin9.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin9.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -686,9 +740,9 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { }); }); - describe('When an update comes for attributes without expressions and Object type', function() { + describe('When an update comes for attributes without expressions and Object type', function () { // Case: Update for a JSON document attribute without expression - var values = [ + const values = [ { name: 'm', type: 'Object', @@ -696,20 +750,24 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin6.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin6.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -717,10 +775,10 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { }); }); - describe('When an update comes for attributes without expressions and Object type', function() { + describe('When an update comes for attributes without expressions and Object type', function () { // Case: Update for a JSON array attribute without expression - var values = [ + const values = [ { name: 'r', type: 'Object', @@ -728,20 +786,24 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin7.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin7.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -749,9 +811,8 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { }); }); - describe('When there are expressions including other attributes and they are not updated', function() { - - var values = [ + describe('When there are expressions including other attributes and they are not updated', function () { + const values = [ { name: 'x', type: 'Number', @@ -759,20 +820,24 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin12.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin12.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -780,9 +845,8 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { }); }); - describe('When there are expressions including other attributes and they are updated', function() { - - var values = [ + describe('When there are expressions including other attributes and they are updated', function () { + const values = [ { name: 'p', type: 'Number', @@ -790,20 +854,24 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin13.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin13.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -811,10 +879,8 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { }); }); - describe('When there are expressions including other attributes and they are updated' + - '(overriding situation)', function() { - - var values = [ + describe('When there are expressions including other attributes and they are updated (overriding situation)', function () { + const values = [ { name: 'x', type: 'Number', @@ -827,25 +893,28 @@ describe('NGSI-v2 - Expression-based transformations plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin13.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin13.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - }); diff --git a/test/unit/ngsiv2/expressions/expressionCombinedTransformations-test.js b/test/unit/ngsiv2/expressions/expressionCombinedTransformations-test.js index 212025326..38f7da8a3 100644 --- a/test/unit/ngsiv2/expressions/expressionCombinedTransformations-test.js +++ b/test/unit/ngsiv2/expressions/expressionCombinedTransformations-test.js @@ -22,112 +22,111 @@ * * Developed by: Federico M. Facca - Martel Innovate */ -'use strict'; /* jshint camelcase: false */ -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfigJexl = { - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041 - }, - defaultExpressionLanguage: 'jexl', - types: { - 'WeatherStationLegacy': { - commands: [], - type: 'WeatherStation', - expressionLanguage: 'legacy', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Number', - expression: '${@pressure * 20}' - } - ] - }, - 'WeatherStationJexl': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Number', - expression: 'pressure * 20' - } - ] - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M', - throttling: 'PT5S' +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfigJexl = { + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' }, - iotAgentConfigLegacy = { - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041 + server: { + port: 4041 + }, + defaultExpressionLanguage: 'jexl', + types: { + WeatherStationLegacy: { + commands: [], + type: 'WeatherStation', + expressionLanguage: 'legacy', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Number', + expression: '${@pressure * 20}' + } + ] }, - types: { - 'WeatherStationLegacy': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Number', - expression: '${@pressure * 20}' - } - ] - }, - 'WeatherStationJexl': { - commands: [], - type: 'WeatherStation', - expressionLanguage: 'jexl', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Number', - expression: 'pressure * 20' - } - ] - } + WeatherStationJexl: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Number', + expression: 'pressure * 20' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M', + throttling: 'PT5S' +}; +const iotAgentConfigLegacy = { + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041 + }, + types: { + WeatherStationLegacy: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Number', + expression: '${@pressure * 20}' + } + ] }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M', - throttling: 'PT5S' - }; + WeatherStationJexl: { + commands: [], + type: 'WeatherStation', + expressionLanguage: 'jexl', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Number', + expression: 'pressure * 20' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M', + throttling: 'PT5S' +}; -describe('Combine Jexl and legacy expressions (default JEXL) - NGSI v2', function() { - beforeEach(function(done) { +describe('Combine Jexl and legacy expressions (default JEXL) - NGSI v2', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfigJexl, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfigJexl, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.attributeAlias.update); iotAgentLib.addQueryMiddleware(iotAgentLib.dataPlugins.attributeAlias.query); iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.expressionTransformation.update); @@ -136,35 +135,39 @@ describe('Combine Jexl and legacy expressions (default JEXL) - NGSI v2', functio }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When an update comes for type with expression "legacy"', function() { - var values = [ + describe('When an update comes for type with expression "legacy"', function () { + const values = [ { name: 'p', type: 'Number', value: 52 } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin1.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin1.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - - it('should apply the legacy expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStationLegacy', '', values, function(error) { + + it('should apply the legacy expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStationLegacy', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -172,44 +175,47 @@ describe('Combine Jexl and legacy expressions (default JEXL) - NGSI v2', functio }); }); - describe('When an update comes for type with expression "JEXL" - default', function() { - var values = [ + describe('When an update comes for type with expression "JEXL" - default', function () { + const values = [ { name: 'p', type: 'Number', value: 52 } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws2/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin1.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws2/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin1.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - - it('should apply the default (JEXL) expression before sending the values', function(done) { - iotAgentLib.update('ws2', 'WeatherStationJexl', '', values, function(error) { - should.not.exist(error); - contextBrokerMock.done(); - done(); + + it('should apply the default (JEXL) expression before sending the values', function (done) { + iotAgentLib.update('ws2', 'WeatherStationJexl', '', values, function (error) { + should.not.exist(error); + contextBrokerMock.done(); + done(); }); }); }); - }); -describe('Combine Jexl and legacy expressions (default Legacy) - NGSI v2', function() { - beforeEach(function(done) { +describe('Combine Jexl and legacy expressions (default Legacy) - NGSI v2', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfigLegacy, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfigLegacy, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.attributeAlias.update); iotAgentLib.addQueryMiddleware(iotAgentLib.dataPlugins.attributeAlias.query); iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.expressionTransformation.update); @@ -218,35 +224,39 @@ describe('Combine Jexl and legacy expressions (default Legacy) - NGSI v2', funct }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When an update comes for type with expression "legacy" - default', function() { - var values = [ + describe('When an update comes for type with expression "legacy" - default', function () { + const values = [ { name: 'p', type: 'Number', value: 52 } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws3/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin1.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws3/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin1.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - - it('should apply the legacy expression before sending the values', function(done) { - iotAgentLib.update('ws3', 'WeatherStationLegacy', '', values, function(error) { + + it('should apply the legacy expression before sending the values', function (done) { + iotAgentLib.update('ws3', 'WeatherStationLegacy', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -254,34 +264,37 @@ describe('Combine Jexl and legacy expressions (default Legacy) - NGSI v2', funct }); }); - describe('When an update comes for type with expression "JEXL"', function() { - var values = [ + describe('When an update comes for type with expression "JEXL"', function () { + const values = [ { name: 'p', type: 'Number', value: 52 } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws4/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin1.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws4/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin1.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - - it('should apply the default (JEXL) expression before sending the values', function(done) { - iotAgentLib.update('ws4', 'WeatherStationJexl', '', values, function(error) { - should.not.exist(error); - contextBrokerMock.done(); - done(); + + it('should apply the default (JEXL) expression before sending the values', function (done) { + iotAgentLib.update('ws4', 'WeatherStationJexl', '', values, function (error) { + should.not.exist(error); + contextBrokerMock.done(); + done(); }); }); }); - }); diff --git a/test/unit/ngsiv2/expressions/jexlBasedTransformations-test.js b/test/unit/ngsiv2/expressions/jexlBasedTransformations-test.js index aedf953e4..007f25589 100644 --- a/test/unit/ngsiv2/expressions/jexlBasedTransformations-test.js +++ b/test/unit/ngsiv2/expressions/jexlBasedTransformations-test.js @@ -22,186 +22,184 @@ * * Developed by: Federico M. Facca - Martel Innovate */ -'use strict'; /* jshint camelcase: false */ -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + defaultExpressionLanguage: 'jexl', + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Number' + }, + { + object_id: 'e', + name: 'consumption', + type: 'Number' + }, + { + object_id: 'a', + name: 'alive', + type: 'None' + }, + { + object_id: 'u', + name: 'updated', + type: 'Boolean' + }, + { + object_id: 'm', + name: 'manufacturer', + type: 'Object' + }, + { + object_id: 'r', + name: 'revisions', + type: 'Array' + }, + { + object_id: 'x', + name: 'consumption_x', + type: 'Number', + expression: 'pressure * 20' + } + ] }, - defaultExpressionLanguage: 'jexl', - server: { - port: 4041 + LightError: { + commands: [], + type: 'Light', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Number', + expression: 'pressure * / 20' + } + ] }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Number' - }, - { - object_id: 'e', - name: 'consumption', - type: 'Number' - }, - { - object_id: 'a', - name: 'alive', - type: 'None', - }, - { - object_id: 'u', - name: 'updated', - type: 'Boolean', - }, - { - object_id: 'm', - name: 'manufacturer', - type: 'Object', - }, - { - object_id: 'r', - name: 'revisions', - type: 'Array', - }, - { - object_id: 'x', - name: 'consumption_x', - type: 'Number', - expression: 'pressure * 20' - } - ] - }, - 'LightError': { - commands: [], - type: 'Light', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Number', - expression: 'pressure * / 20' - } - ] - }, - 'WeatherStation': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Number', - expression: 'pressure * 20' - }, - { - object_id: 'e', - name: 'consumption', - type: 'Number', - expression: 'consumption * 20' - }, - { - object_id: 'h', - name: 'humidity', - type: 'Percentage' - }, - { - name: 'weather', - type: 'Summary', - expression: '"Humidity " + (humidity / 2) + " and pressure " + (pressure * 20)' - }, - { - object_id: 'a', - name: 'alive', - type: 'None', - expression: 'alive * 20' - }, - { - object_id: 'u', - name: 'updated', - type: 'Boolean', - expression: 'updated * 20' - }, - ] - }, - 'WeatherStationMultiple': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - - { - object_id: 'p', - name: 'pressure', - type: 'Number', - expression: 'pressure|trim' - }, - { - object_id: 'p25', - name: 'pressure25', - type: 'Number' - }, - { - object_id: 'e', - name: 'consumption', - type: 'Number', - expression: 'consumption|trim' - }, - { - object_id: 'h', - name: 'humidity12', - type: 'Percentage' - }, - { - name: 'weather', - type: 'Summary', - expression: '"Humidity " + (humidity12 / 2) + " and pressure " + (pressure25 * 20)' - }, - { - object_id: 'a', - name: 'alive', - type: 'None', - expression: 'alive|trim' - }, - { - object_id: 'u', - name: 'updated', - type: 'Boolean', - expression: 'updated|trim' - }, - ] - } + WeatherStation: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Number', + expression: 'pressure * 20' + }, + { + object_id: 'e', + name: 'consumption', + type: 'Number', + expression: 'consumption * 20' + }, + { + object_id: 'h', + name: 'humidity', + type: 'Percentage' + }, + { + name: 'weather', + type: 'Summary', + expression: '"Humidity " + (humidity / 2) + " and pressure " + (pressure * 20)' + }, + { + object_id: 'a', + name: 'alive', + type: 'None', + expression: 'alive * 20' + }, + { + object_id: 'u', + name: 'updated', + type: 'Boolean', + expression: 'updated * 20' + } + ] }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M', - throttling: 'PT5S' - }; - -describe('Java expression language (JEXL) based transformations plugin', function() { - beforeEach(function(done) { + WeatherStationMultiple: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Number', + expression: 'pressure|trim' + }, + { + object_id: 'p25', + name: 'pressure25', + type: 'Number' + }, + { + object_id: 'e', + name: 'consumption', + type: 'Number', + expression: 'consumption|trim' + }, + { + object_id: 'h', + name: 'humidity12', + type: 'Percentage' + }, + { + name: 'weather', + type: 'Summary', + expression: '"Humidity " + (humidity12 / 2) + " and pressure " + (pressure25 * 20)' + }, + { + object_id: 'a', + name: 'alive', + type: 'None', + expression: 'alive|trim' + }, + { + object_id: 'u', + name: 'updated', + type: 'Boolean', + expression: 'updated|trim' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M', + throttling: 'PT5S' +}; + +describe('Java expression language (JEXL) based transformations plugin', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.attributeAlias.update); iotAgentLib.addQueryMiddleware(iotAgentLib.dataPlugins.attributeAlias.query); iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.expressionTransformation.update); @@ -210,24 +208,24 @@ describe('Java expression language (JEXL) based transformations plugin', functio }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When an update comes for expressions with syntax errors', function() { + describe('When an update comes for expressions with syntax errors', function () { // Case: Update for an attribute with bad expression - var values = [ + const values = [ { name: 'p', type: 'centigrades', value: '52' } ]; - - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'LightError', '', values, function(error) { + + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'LightError', '', values, function (error) { should.exist(error); error.name.should.equal('INVALID_EXPRESSION'); error.code.should.equal(400); @@ -235,10 +233,10 @@ describe('Java expression language (JEXL) based transformations plugin', functio }); }); }); - - describe('When there are expression attributes that are just calculated (not sent by the device)', function() { + + describe('When there are expression attributes that are just calculated (not sent by the device)', function () { // Case: Expression which results is sent as a new attribute - var values = [ + const values = [ { name: 'p', type: 'Number', @@ -250,32 +248,36 @@ describe('Java expression language (JEXL) based transformations plugin', functio value: '12' } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin2.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin2.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - - it('should calculate them and add them to the payload', function(done) { - iotAgentLib.update('ws1', 'WeatherStation', '', values, function(error) { + + it('should calculate them and add them to the payload', function (done) { + iotAgentLib.update('ws1', 'WeatherStation', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - - describe('When an expression with multiple variables with numbers arrive', function() { + + describe('When an expression with multiple variables with numbers arrive', function () { // Case: Update for integer and string attributes with expression - - var values = [ + + const values = [ { name: 'p25', type: 'Number', @@ -287,306 +289,346 @@ describe('Java expression language (JEXL) based transformations plugin', functio value: '12' } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin4.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin4.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - - it('should calculate it and add it to the payload', function(done) { - iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function(error) { + + it('should calculate it and add it to the payload', function (done) { + iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - - describe('When an update comes for attributes without expressions and type integer', function() { + + describe('When an update comes for attributes without expressions and type integer', function () { // Case: Update for an integer attribute without expression - var values = [ + const values = [ { name: 'e', type: 'Number', value: 52 } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin11.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin11.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - - describe('When an update comes for attributes with numeric expressions and type integer', function() { + + describe('When an update comes for attributes with numeric expressions and type integer', function () { // Case: Update for an integer attribute with arithmetic expression - var values = [ + const values = [ { name: 'p', type: 'Number', value: 52 } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin1.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin1.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStation', '', values, function(error) { + + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStation', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - - describe('When an update comes for attributes with string expression and type integer', function() { + + describe('When an update comes for attributes with string expression and type integer', function () { // Case: Update for an integer attribute with string expression - var values = [ + const values = [ { name: 'e', type: 'Number', value: 52 } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin11.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin11.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function(error) { + + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - - describe('When an update comes for attributes without expressions and type float', function() { + + describe('When an update comes for attributes without expressions and type float', function () { // Case: Update for a Float attribute without expressions - - var values = [ + + const values = [ { name: 'e', type: 'Number', value: 0.44 } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin3.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin3.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - - describe('When an update comes for attributes with numeric expressions and type float', function() { + + describe('When an update comes for attributes with numeric expressions and type float', function () { // Case: Update for a Float attribute with arithmetic expression - - var values = [ + + const values = [ { name: 'e', type: 'Number', value: 0.44 } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin8.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin8.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStation', '', values, function(error) { + + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStation', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - - describe('When an update comes for attributes with string expressions and type float', function() { + + describe('When an update comes for attributes with string expressions and type float', function () { // Case: Update for a Float attribute with string expression - - var values = [ + + const values = [ { name: 'e', type: 'Number', value: 0.44 } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin3.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin3.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function(error) { + + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - - describe('When an update comes for attributes without expressions and NULL type', function() { + + describe('When an update comes for attributes without expressions and NULL type', function () { // Case: Update for a Null attribute without expression - - var values = [ + + const values = [ { name: 'a', type: 'None', value: null } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin5.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin5.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - - describe('When an update comes for attributes with numeric expressions and NULL type', function() { + + describe('When an update comes for attributes with numeric expressions and NULL type', function () { // Case: Update for a Null attribute with arithmetic expression - - var values = [ + + const values = [ { name: 'a', type: 'None', value: null } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin5.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin5.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStation', '', values, function(error) { + + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStation', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - - describe('When an update comes for attributes with string expressions and NULL type', function() { + + describe('When an update comes for attributes with string expressions and NULL type', function () { // Case: Update for a Null attribute with string expression - - var values = [ + + const values = [ { name: 'a', type: 'None', value: null } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin5.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin5.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function(error) { + + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -594,63 +636,71 @@ describe('Java expression language (JEXL) based transformations plugin', functio }); }); - describe('When an update comes for attributes without expressions and Boolean type', function() { + describe('When an update comes for attributes without expressions and Boolean type', function () { // Case: Update for a Boolean attribute without expression - - var values = [ + + const values = [ { name: 'u', type: 'Boolean', value: true } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin9.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin9.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - - describe('When an update comes for attributes with numeric expressions and Boolean type', function() { + + describe('When an update comes for attributes with numeric expressions and Boolean type', function () { // Case: Update for a Boolean attribute with arithmetic expression - - var values = [ + + const values = [ { name: 'u', type: 'Boolean', value: true } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin10.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin10.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStation', '', values, function(error) { + + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStation', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -658,9 +708,9 @@ describe('Java expression language (JEXL) based transformations plugin', functio }); }); - describe('When an update comes for attributes with string expressions and Boolean type', function() { + describe('When an update comes for attributes with string expressions and Boolean type', function () { // Case: Update for a Boolean attribute with string expression - var values = [ + const values = [ { name: 'u', type: 'Boolean', @@ -668,20 +718,24 @@ describe('Java expression language (JEXL) based transformations plugin', functio } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/ws1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin9.json')) - .query({type: 'WeatherStation'}) + .post( + '/v2/entities/ws1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin9.json' + ) + ) + .query({ type: 'WeatherStation' }) .reply(204); }); - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function(error) { + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('ws1', 'WeatherStationMultiple', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -689,135 +743,147 @@ describe('Java expression language (JEXL) based transformations plugin', functio }); }); - describe('When an update comes for attributes without expressions and Object type', function() { + describe('When an update comes for attributes without expressions and Object type', function () { // Case: Update for a JSON document attribute without expression - var values = [ + const values = [ { name: 'm', type: 'Object', value: { name: 'Manufacturer1', VAT: 'U12345678' } } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin6.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin6.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - - describe('When an update comes for attributes without expressions and Object type', function() { + + describe('When an update comes for attributes without expressions and Object type', function () { // Case: Update for a JSON array attribute without expression - - var values = [ + + const values = [ { name: 'r', type: 'Object', value: ['v0.1', 'v0.2', 'v0.3'] } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin7.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin7.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - - describe('When there are expressions including other attributes and they are not updated', function() { - - var values = [ + + describe('When there are expressions including other attributes and they are not updated', function () { + const values = [ { name: 'x', type: 'Number', value: 0.44 } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin12.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin12.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - - describe('When there are expressions including other attributes and they are updated', function() { - - var values = [ + + describe('When there are expressions including other attributes and they are updated', function () { + const values = [ { name: 'p', type: 'Number', value: 10 } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin13.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin13.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - - describe('When there are expressions including other attributes and they are updated' + - '(overriding situation)', function() { - - var values = [ + + describe('When there are expressions including other attributes and they are updated (overriding situation)', function () { + const values = [ { name: 'x', type: 'Number', @@ -829,26 +895,29 @@ describe('Java expression language (JEXL) based transformations plugin', functio value: 10 } ]; - - beforeEach(function() { + + beforeEach(function () { nock.cleanAll(); - + contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin13.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextExpressionPlugin13.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - - it('should apply the expression before sending the values', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + + it('should apply the expression before sending the values', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - }); diff --git a/test/unit/ngsiv2/general/contextBrokerOAuthSecurityAccess-test.js b/test/unit/ngsiv2/general/contextBrokerOAuthSecurityAccess-test.js index 929eb9d9a..443238714 100644 --- a/test/unit/ngsiv2/general/contextBrokerOAuthSecurityAccess-test.js +++ b/test/unit/ngsiv2/general/contextBrokerOAuthSecurityAccess-test.js @@ -22,75 +22,75 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - request = require('request'), - timekeeper = require('timekeeper'), - contextBrokerMock, - oauth2Mock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041 - }, - authentication: { - type: 'oauth2', - url: 'http://192.168.1.1:3000', - header: 'Authorization', - clientId: 'context-broker', - clientSecret: 'c8d58d16-0a42-400e-9765-f32e154a5a9e', - tokenPath: '/auth/realms/default/protocol/openid-connect/token', - enabled: true - }, - types: { - 'Light': { - service: 'smartGondor', - subservice: 'electricity', - trust: 'eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3cHdWclJ3', - type: 'Light', - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'Termometer': { - commands: [], - type: 'Termometer', - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ] - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' - }; -describe('NGSI-v2 - Secured access to the Context Broker with OAuth2 provider', function() { - var values = [ +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +const request = require('request'); +const timekeeper = require('timekeeper'); +let contextBrokerMock; +let oauth2Mock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041 + }, + authentication: { + type: 'oauth2', + url: 'http://192.168.1.1:3000', + header: 'Authorization', + clientId: 'context-broker', + clientSecret: 'c8d58d16-0a42-400e-9765-f32e154a5a9e', + tokenPath: '/auth/realms/default/protocol/openid-connect/token', + enabled: true + }, + types: { + Light: { + service: 'smartGondor', + subservice: 'electricity', + trust: 'eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3cHdWclJ3', + type: 'Light', + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] + }, + Termometer: { + commands: [], + type: 'Termometer', + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; + +describe('NGSI-v2 - Secured access to the Context Broker with OAuth2 provider', function () { + const values = [ { name: 'state', type: 'Boolean', @@ -103,111 +103,117 @@ describe('NGSI-v2 - Secured access to the Context Broker with OAuth2 provider', } ]; - beforeEach(function() { + beforeEach(function () { logger.setLevel('FATAL'); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); nock.cleanAll(); }); - describe('When a measure is sent to the Context Broker via an Update Context operation', function() { - beforeEach(function(done) { + describe('When a measure is sent to the Context Broker via an Update Context operation', function () { + beforeEach(function (done) { nock.cleanAll(); oauth2Mock = nock('http://192.168.1.1:3000') - .post('/auth/realms/default/protocol/openid-connect/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) - .reply( - 201, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrust.json'), - {}); + .post( + '/auth/realms/default/protocol/openid-connect/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) + .reply(201, utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrust.json'), {}); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'electricity') .matchHeader('Authorization', 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3cHdWclJ3') - .post('/v2/entities/light1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext1.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext1.json') + ) + .query({ type: 'Light' }) .reply(204, {}); iotAgentLib.activate(iotAgentConfig, done); }); - it('should ask OAuth2 provider for a token based on the trust token', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should ask OAuth2 provider for a token based on the trust token', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); oauth2Mock.done(); done(); }); }); - it('should send the generated token in the auth header', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should send the generated token in the auth header', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - describe('When a measure is sent to the Context Broker and the access is forbidden', function() { - beforeEach(function(done) { + describe('When a measure is sent to the Context Broker and the access is forbidden', function () { + beforeEach(function (done) { nock.cleanAll(); oauth2Mock = nock('http://192.168.1.1:3000') - .post('/auth/realms/default/protocol/openid-connect/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) - .reply( - 201, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrust.json'), - {}); + .post( + '/auth/realms/default/protocol/openid-connect/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) + .reply(201, utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrust.json'), {}); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'electricity') .matchHeader('Authorization', 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3cHdWclJ3') - .post('/v2/entities/light1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext1.json')) - .query({type: 'Light'}) - .reply( - 403, {}); + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext1.json') + ) + .query({ type: 'Light' }) + .reply(403, {}); iotAgentLib.activate(iotAgentConfig, done); }); - it('it should return a ACCESS_FORBIDDEN error to the caller', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('it should return a ACCESS_FORBIDDEN error to the caller', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.exist(error); error.name.should.equal('ACCESS_FORBIDDEN'); done(); }); }); }); - describe('When a measure is sent and the trust is rejected asking for the token', function() { - beforeEach(function(done) { + describe('When a measure is sent and the trust is rejected asking for the token', function () { + beforeEach(function (done) { nock.cleanAll(); - oauth2Mock = nock('http://192.168.1.1:3000') - .post('/auth/realms/default/protocol/openid-connect/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) + oauth2Mock = nock('http://192.168.1.1:3000') + .post( + '/auth/realms/default/protocol/openid-connect/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) .reply( - 400, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustUnauthorized.json')); + 400, + utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustUnauthorized.json') + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'electricity') .matchHeader('Authorization', 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3cHdWclJ3') - .post('/v2/entities/light1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext1.json')) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext1.json') + ) .reply(204, {}); iotAgentLib.activate(iotAgentConfig, done); }); - it('it should return a AUTHENTICATION_ERROR error to the caller', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('it should return a AUTHENTICATION_ERROR error to the caller', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.exist(error); error.name.should.equal('AUTHENTICATION_ERROR'); done(); @@ -215,99 +221,106 @@ describe('NGSI-v2 - Secured access to the Context Broker with OAuth2 provider', }); }); - describe('When the user requests information about a device in a protected CB', function() { - var attributes = [ - 'state', - 'dimming' - ]; + describe('When the user requests information about a device in a protected CB', function () { + const attributes = ['state', 'dimming']; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); oauth2Mock = nock('http://192.168.1.1:3000') - .post('/auth/realms/default/protocol/openid-connect/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) - .reply( - 201, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrust.json'), - {}); + .post( + '/auth/realms/default/protocol/openid-connect/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) + .reply(201, utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrust.json'), {}); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'electricity') .matchHeader('Authorization', 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3cHdWclJ3') .get('/v2/entities/light1/attrs?attrs=state,dimming&type=Light') - .reply(200, - utils.readExampleFile('./test/unit/ngsiv2/examples/contextResponses/queryContext1Success.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/ngsiv2/examples/contextResponses/queryContext1Success.json') + ); iotAgentLib.activate(iotAgentConfig, done); }); - it('should send the Auth Token along with the information query', function(done) { - iotAgentLib.query('light1', 'Light', '', attributes, function(error) { + it('should send the Auth Token along with the information query', function (done) { + iotAgentLib.query('light1', 'Light', '', attributes, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - describe('When subscriptions are used on a protected Context Broker', function() { - beforeEach(function(done) { - var optionsProvision = { + describe('When subscriptions are used on a protected Context Broker', function () { + beforeEach(function (done) { + const optionsProvision = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice3.json'), + './test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice3.json' + ), headers: { 'fiware-service': 'smartGondor', 'fiware-servicepath': 'electricity' } }; - + nock.cleanAll(); - - iotAgentLib.activate(iotAgentConfig, function() { + + iotAgentLib.activate(iotAgentConfig, function () { oauth2Mock = nock('http://192.168.1.1:3000') - .post('/auth/realms/default/protocol/openid-connect/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) + .post( + '/auth/realms/default/protocol/openid-connect/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) .times(3) - .reply( - 201, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrust.json'), - {}); - + .reply(201, utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrust.json'), {}); contextBrokerMock = nock('http://192.168.1.1:1026'); contextBrokerMock - .post('/v2/registrations', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerProvisionedDeviceWithGroup3.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .post( + '/v2/registrations', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerProvisionedDeviceWithGroup3.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); contextBrokerMock - .post('/v2/entities?options=upsert', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/createProvisionedDeviceWithGroupAndStatic3.json')) - .reply(204, {}); + .post( + '/v2/entities?options=upsert', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/createProvisionedDeviceWithGroupAndStatic3.json' + ) + ) + .reply(204, {}); contextBrokerMock - .post('/v2/subscriptions', - utils.readExampleFile('./test/unit/ngsiv2/examples' + - '/subscriptionRequests/simpleSubscriptionRequest2.json')) + .post( + '/v2/subscriptions', + utils.readExampleFile( + './test/unit/ngsiv2/examples/subscriptionRequests/simpleSubscriptionRequest2.json' + ) + ) .matchHeader('Authorization', 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3cHdWclJ3') - .reply(201, null, {'Location': '/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8'}); + .reply(201, null, { Location: '/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8' }); - - iotAgentLib.clearAll(function() { - request(optionsProvision, function(error, result, body) { + iotAgentLib.clearAll(function () { + request(optionsProvision, function (error, result, body) { done(); }); }); }); }); - it('subscribe requests use auth header', function(done) { - iotAgentLib.getDevice('Light1', 'smartGondor', 'electricity', function(error, device) { - iotAgentLib.subscribe(device, ['dimming'], null, function(error) { + it('subscribe requests use auth header', function (done) { + iotAgentLib.getDevice('Light1', 'smartGondor', 'electricity', function (error, device) { + iotAgentLib.subscribe(device, ['dimming'], null, function (error) { should.not.exist(error); contextBrokerMock.done(); @@ -317,36 +330,30 @@ describe('NGSI-v2 - Secured access to the Context Broker with OAuth2 provider', }); }); - it('unsubscribe requests use auth header', function(done) { - - oauth2Mock - .post('/auth/realms/default/protocol/openid-connect/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) - .reply( - 201, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrust.json'), - {}); + it('unsubscribe requests use auth header', function (done) { + oauth2Mock + .post( + '/auth/realms/default/protocol/openid-connect/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) + .reply(201, utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrust.json'), {}); - contextBrokerMock - .delete('/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8') - .reply(204); + contextBrokerMock.delete('/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8').reply(204); - iotAgentLib.getDevice('Light1', 'smartGondor', 'electricity', function(error, device) { - iotAgentLib.subscribe(device, ['dimming'], null, function(error) { - iotAgentLib.unsubscribe(device, '51c0ac9ed714fb3b37d7d5a8', function(error) { + iotAgentLib.getDevice('Light1', 'smartGondor', 'electricity', function (error, device) { + iotAgentLib.subscribe(device, ['dimming'], null, function (error) { + iotAgentLib.unsubscribe(device, '51c0ac9ed714fb3b37d7d5a8', function (error) { contextBrokerMock.done(); done(); }); }); }); }); - }); }); -describe('NGSI-v2 - Secured access to the Context Broker with OAuth2 provider (FIWARE Keyrock IDM)', function() { - - var values = [ +describe('NGSI-v2 - Secured access to the Context Broker with OAuth2 provider (FIWARE Keyrock IDM)', function () { + const values = [ { name: 'state', type: 'Boolean', @@ -359,49 +366,54 @@ describe('NGSI-v2 - Secured access to the Context Broker with OAuth2 provider (F } ]; - beforeEach(function() { + beforeEach(function () { logger.setLevel('FATAL'); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); nock.cleanAll(); }); - describe('When a measure is sent to the Context Broker via an Update Context operation', function() { - beforeEach(function(done) { + describe('When a measure is sent to the Context Broker via an Update Context operation', function () { + beforeEach(function (done) { nock.cleanAll(); oauth2Mock = nock('http://192.168.1.1:3000') - .post('/oauth2/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) + .post( + '/oauth2/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) .reply( 200, utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock.json'), - {}); + {} + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'electricity') .matchHeader('Authorization', 'Bearer c1b752e377680acd1349a3ed59db855a1db07605') - .post('/v2/entities/light1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext1.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext1.json') + ) + .query({ type: 'Light' }) .reply(204, {}); iotAgentConfig.authentication.tokenPath = '/oauth2/token'; iotAgentLib.activate(iotAgentConfig, done); }); - it('should ask OAuth2 provider for a token based on the trust token', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should ask OAuth2 provider for a token based on the trust token', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); oauth2Mock.done(); done(); }); }); - it('should send the generated token in the auth header', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should send the generated token in the auth header', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -409,36 +421,38 @@ describe('NGSI-v2 - Secured access to the Context Broker with OAuth2 provider (F }); }); - describe('When the user requests information about a device in a protected CB', function() { - var attributes = [ - 'state', - 'dimming' - ]; + describe('When the user requests information about a device in a protected CB', function () { + const attributes = ['state', 'dimming']; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); oauth2Mock = nock('http://192.168.1.1:3000') - .post('/oauth2/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) + .post( + '/oauth2/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) .reply( 200, utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock.json'), - {}); + {} + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'electricity') .matchHeader('Authorization', 'Bearer c1b752e377680acd1349a3ed59db855a1db07605') .get('/v2/entities/light1/attrs?attrs=state,dimming&type=Light') - .reply(200, - utils.readExampleFile('./test/unit/ngsiv2/examples/contextResponses/queryContext1Success.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/ngsiv2/examples/contextResponses/queryContext1Success.json') + ); iotAgentLib.activate(iotAgentConfig, done); }); - it('should send the Auth Token along with the information query', function(done) { - iotAgentLib.query('light1', 'Light', '', attributes, function(error) { + it('should send the Auth Token along with the information query', function (done) { + iotAgentLib.query('light1', 'Light', '', attributes, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -446,22 +460,25 @@ describe('NGSI-v2 - Secured access to the Context Broker with OAuth2 provider (F }); }); - describe('When a measure is sent and the refresh token is not valid', function() { - beforeEach(function(done) { + describe('When a measure is sent and the refresh token is not valid', function () { + beforeEach(function (done) { nock.cleanAll(); oauth2Mock = nock('http://192.168.1.1:3000') - .post('/oauth2/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) + .post( + '/oauth2/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) .reply( - 400, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustUnauthorizedKeyrock.json')); + 400, + utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustUnauthorizedKeyrock.json') + ); iotAgentLib.activate(iotAgentConfig, done); }); - it('it should return a AUTHENTICATION_ERROR error to the caller', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('it should return a AUTHENTICATION_ERROR error to the caller', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.exist(error); error.name.should.equal('AUTHENTICATION_ERROR'); done(); @@ -469,23 +486,28 @@ describe('NGSI-v2 - Secured access to the Context Broker with OAuth2 provider (F }); }); - describe('When a measure is sent to the Context Broker and the client credentials are invalid', function() { - beforeEach(function(done) { + describe('When a measure is sent to the Context Broker and the client credentials are invalid', function () { + beforeEach(function (done) { nock.cleanAll(); oauth2Mock = nock('http://192.168.1.1:3000') - .post('/oauth2/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) + .post( + '/oauth2/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) .reply( - 400, - utils.readExampleFile('./test/unit/examples/oauthResponses/' + - 'tokenFromTrustInvalidCredentialsKeyrock.json'), {}); + 400, + utils.readExampleFile( + './test/unit/examples/oauthResponses/tokenFromTrustInvalidCredentialsKeyrock.json' + ), + {} + ); iotAgentLib.activate(iotAgentConfig, done); }); - it('it should return a AUTHENTICATION_ERROR error to the caller', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('it should return a AUTHENTICATION_ERROR error to the caller', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.exist(error); error.name.should.equal('AUTHENTICATION_ERROR'); done(); @@ -493,32 +515,37 @@ describe('NGSI-v2 - Secured access to the Context Broker with OAuth2 provider (F }); }); - describe('When a measure is sent to the Context Broker and the access is unauthorized', function() { - beforeEach(function(done) { + describe('When a measure is sent to the Context Broker and the access is unauthorized', function () { + beforeEach(function (done) { nock.cleanAll(); oauth2Mock = nock('http://192.168.1.1:3000') - .post('/oauth2/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true)) + .post( + '/oauth2/token', + utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrust.json', true) + ) .reply( 200, utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock.json'), - {}); + {} + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'electricity') .matchHeader('Authorization', 'Bearer c1b752e377680acd1349a3ed59db855a1db07605') - .post('/v2/entities/light1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext1.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext1.json') + ) + .query({ type: 'Light' }) .reply(401, 'Auth-token not found in request header'); iotAgentLib.activate(iotAgentConfig, done); }); - it('it should return a ACCESS_FORBIDDEN error to the caller', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('it should return a ACCESS_FORBIDDEN error to the caller', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.exist(error); error.name.should.equal('ACCESS_FORBIDDEN'); done(); @@ -527,271 +554,327 @@ describe('NGSI-v2 - Secured access to the Context Broker with OAuth2 provider (F }); }); -describe('NGSI-v2 - Secured access to the Context Broker with OAuth2 provider (FIWARE Keyrock IDM)' + - 'configured through group provisioning', function() { - var groupCreation = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionFullGroup.json'), - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - } - }; - - var values = [ - { - name: 'status', - type: 'String', - value: 'STARTING' - } - ]; +describe( + 'NGSI-v2 - Secured access to the Context Broker with OAuth2 provider (FIWARE Keyrock IDM)' + + 'configured through group provisioning', + function () { + const groupCreation = { + url: 'http://localhost:4041/iot/services', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionFullGroup.json'), + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } + }; - beforeEach(function() { - logger.setLevel('FATAL'); - }); + const values = [ + { + name: 'status', + type: 'String', + value: 'STARTING' + } + ]; - afterEach(function(done) { - iotAgentLib.deactivate(done); - nock.cleanAll(); - }); + beforeEach(function () { + logger.setLevel('FATAL'); + }); - describe('When a measure is sent to the Context Broker via an Update Context operation', function() { - var oauth2Mock2; - var contextBrokerMock2; - beforeEach(function(done) { + afterEach(function (done) { + iotAgentLib.deactivate(done); nock.cleanAll(); - oauth2Mock = nock('http://192.168.1.1:3000') - .post('/oauth2/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrustKeyrockGroup.json', true)) - .reply( - 200, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock.json'), - {}); + }); - oauth2Mock2 = nock('http://192.168.1.1:3000') - .post('/oauth2/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrustKeyrockGroup2.json', true)) - .reply( - 200, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock2.json'), - {}); + describe('When a measure is sent to the Context Broker via an Update Context operation', function () { + let oauth2Mock2; + let contextBrokerMock2; + beforeEach(function (done) { + nock.cleanAll(); + oauth2Mock = nock('http://192.168.1.1:3000') + .post( + '/oauth2/token', + utils.readExampleFile( + './test/unit/examples/oauthRequests/getTokenFromTrustKeyrockGroup.json', + true + ) + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock.json'), + {} + ); + + oauth2Mock2 = nock('http://192.168.1.1:3000') + .post( + '/oauth2/token', + utils.readExampleFile( + './test/unit/examples/oauthRequests/getTokenFromTrustKeyrockGroup2.json', + true + ) + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock2.json'), + {} + ); + + contextBrokerMock = nock('http://unexistentHost:1026') + .matchHeader('fiware-service', 'TestService') + .matchHeader('fiware-servicepath', '/testingPath') + .matchHeader('Authorization', 'Bearer c1b752e377680acd1349a3ed59db855a1db07605') + .post( + '/v2/entities/machine1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContext3WithStatic.json' + ) + ) + .query({ type: 'SensorMachine' }) + .reply(204, {}); + + contextBrokerMock2 = nock('http://unexistentHost:1026') + .matchHeader('fiware-service', 'TestService') + .matchHeader('fiware-servicepath', '/testingPath') + .matchHeader('Authorization', 'Bearer bbb752e377680acd1349a3ed59db855a1db076aa') + .post( + '/v2/entities/machine1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContext3WithStatic.json' + ) + ) + .query({ type: 'SensorMachine' }) + .reply(204, {}); + + iotAgentConfig.authentication.tokenPath = '/oauth2/token'; + iotAgentLib.activate(iotAgentConfig, function () { + request(groupCreation, function (error, response, body) { + done(); + }); + }); + }); + it( + 'should ask OAuth2 provider for a token based on the' + + 'trust token and send the generated token in the auth header', + function (done) { + iotAgentLib.update('machine1', 'SensorMachine', '', values, function (error) { + should.not.exist(error); + oauth2Mock.done(); + contextBrokerMock.done(); + done(); + }); + } + ); - contextBrokerMock = nock('http://unexistentHost:1026') - .matchHeader('fiware-service', 'TestService') - .matchHeader('fiware-servicepath', '/testingPath') - .matchHeader('Authorization', 'Bearer c1b752e377680acd1349a3ed59db855a1db07605') - .post('/v2/entities/machine1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext3WithStatic.json')) - .query({type: 'SensorMachine'}) - .reply(204, {}); + it('should use the updated trust token in the following requests', function (done) { + iotAgentLib.update('machine1', 'SensorMachine', '', values, function (error) { + should.not.exist(error); + oauth2Mock2.done(); + contextBrokerMock2.done(); + done(); + }); + }); + }); - contextBrokerMock2 = nock('http://unexistentHost:1026') - .matchHeader('fiware-service', 'TestService') - .matchHeader('fiware-servicepath', '/testingPath') - .matchHeader('Authorization', 'Bearer bbb752e377680acd1349a3ed59db855a1db076aa') - .post('/v2/entities/machine1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext3WithStatic.json')) - .query({type: 'SensorMachine'}) - .reply(204, {}); + describe('When a device is provisioned for a configuration contains an OAuth2 trust token', function () { + const values = [ + { + name: 'status', + type: 'String', + value: 'STARTING' + } + ]; + const deviceCreation = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice2.json'), + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } + }; + let contextBrokerMock2; + let contextBrokerMock3; + beforeEach(function (done) { + const time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 + timekeeper.freeze(time); + nock.cleanAll(); - iotAgentConfig.authentication.tokenPath = '/oauth2/token'; - iotAgentLib.activate(iotAgentConfig, function() { - request(groupCreation, function(error, response, body) { + oauth2Mock = nock('http://192.168.1.1:3000') + .post( + '/oauth2/token', + utils.readExampleFile( + './test/unit/examples/oauthRequests/getTokenFromTrustKeyrockGroup3.json', + true + ) + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock3.json'), + {} + ) + .post( + '/oauth2/token', + utils.readExampleFile( + './test/unit/examples/oauthRequests/getTokenFromTrustKeyrockGroup4.json', + true + ) + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock4.json'), + {} + ) + .post( + '/oauth2/token', + utils.readExampleFile( + './test/unit/examples/oauthRequests/getTokenFromTrustKeyrockGroup5.json', + true + ) + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock5.json'), + {} + ); + + contextBrokerMock = nock('http://unexistenthost:1026') + .matchHeader('fiware-service', 'TestService') + .matchHeader('fiware-servicepath', '/testingPath') + .matchHeader('Authorization', 'Bearer asd752e377680acd1349a3ed59db855a1db07ere') + .post( + '/v2/registrations', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerProvisionedDeviceWithGroup2.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); + + contextBrokerMock2 = nock('http://unexistenthost:1026') + .matchHeader('fiware-service', 'TestService') + .matchHeader('fiware-servicepath', '/testingPath') + .matchHeader('authorization', 'Bearer bea752e377680acd1349a3ed59db855a1db07zxc') + .post( + '/v2/entities?options=upsert', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/createProvisionedDeviceWithGroupAndStatic2.json' + ) + ) + .reply(204, {}); + + contextBrokerMock3 = nock('http://unexistentHost:1026') + .matchHeader('fiware-service', 'TestService') + .matchHeader('fiware-servicepath', '/testingPath') + .matchHeader('authorization', 'Bearer zzz752e377680acd1349a3ed59db855a1db07bbb') + .post( + '/v2/entities/Light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext4.json') + ) + .query({ type: 'SensorMachine' }) + .reply(204, {}); + + iotAgentConfig.authentication.tokenPath = '/oauth2/token'; + iotAgentLib.activate(iotAgentConfig, function () { done(); }); }); - }); - it('should ask OAuth2 provider for a token based on the' + - 'trust token and send the generated token in the auth header', function(done) { - iotAgentLib.update('machine1', 'SensorMachine', '', values, function(error) { - should.not.exist(error); - oauth2Mock.done(); - contextBrokerMock.done(); + + afterEach(function (done) { + timekeeper.reset(); + done(); }); - }); - it('should use the updated trust token in the following requests', function(done) { - iotAgentLib.update('machine1', 'SensorMachine', '', values, function(error) { - should.not.exist(error); - oauth2Mock2.done(); - contextBrokerMock2.done(); - done(); + it('should not raise any error', function (done) { + request(deviceCreation, function (error, response, body) { + should.not.exist(error); + response.statusCode.should.equal(201); + contextBrokerMock.done(); + contextBrokerMock2.done(); + done(); + }); }); - }); - }); + it('should send the mixed data to the Context Broker', function (done) { + iotAgentLib.update('Light1', 'SensorMachine', '', values, function (error) { + should.not.exist(error); + contextBrokerMock3.done(); + done(); + }); + }); + }); + } +); - describe('When a device is provisioned for a configuration contains an OAuth2 trust token', function() { - var values = [ - { - name: 'status', - type: 'String', - value: 'STARTING' - } - ]; - var deviceCreation = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', +describe( + 'NGSI-v2 - Secured access to the Context Broker with OAuth2 provider (FIWARE Keyrock IDM)' + + 'configured through group provisioning. Permanent token', + function () { + const groupCreation = { + url: 'http://localhost:4041/iot/services', method: 'POST', - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice2.json'), + json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionFullGroup.json'), headers: { 'fiware-service': 'TestService', 'fiware-servicepath': '/testingPath' } }; - var contextBrokerMock2; - var contextBrokerMock3; - beforeEach(function(done) { - var time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 - timekeeper.freeze(time); - nock.cleanAll(); - - oauth2Mock = nock('http://192.168.1.1:3000') - .post('/oauth2/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrustKeyrockGroup3.json', true)) - .reply( - 200, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock3.json'), - {}) - .post('/oauth2/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrustKeyrockGroup4.json', true)) - .reply( - 200, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock4.json'), - {}) - .post('/oauth2/token', - utils.readExampleFile('./test/unit/examples/oauthRequests/getTokenFromTrustKeyrockGroup5.json', true)) - .reply( - 200, - utils.readExampleFile('./test/unit/examples/oauthResponses/tokenFromTrustKeyrock5.json'), - {}); - - - contextBrokerMock = nock('http://unexistenthost:1026') - .matchHeader('fiware-service', 'TestService') - .matchHeader('fiware-servicepath', '/testingPath') - .matchHeader('Authorization', 'Bearer asd752e377680acd1349a3ed59db855a1db07ere') - .post('/v2/registrations', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerProvisionedDeviceWithGroup2.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); - - contextBrokerMock2 = nock('http://unexistenthost:1026') - .matchHeader('fiware-service', 'TestService') - .matchHeader('fiware-servicepath', '/testingPath') - .matchHeader('authorization', 'Bearer bea752e377680acd1349a3ed59db855a1db07zxc') - .post('/v2/entities?options=upsert', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/createProvisionedDeviceWithGroupAndStatic2.json')) - .reply(204, {}); - - contextBrokerMock3 = nock('http://unexistentHost:1026') - .matchHeader('fiware-service', 'TestService') - .matchHeader('fiware-servicepath', '/testingPath') - .matchHeader('authorization', 'Bearer zzz752e377680acd1349a3ed59db855a1db07bbb') - .post('/v2/entities/Light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContext4.json')) - .query({type: 'SensorMachine'}) - .reply(204, {}); - - - iotAgentConfig.authentication.tokenPath = '/oauth2/token'; - iotAgentLib.activate(iotAgentConfig, function() { - done(); - }); - }); - afterEach(function(done) { - timekeeper.reset(); + const values = [ + { + name: 'status', + type: 'String', + value: 'STARTING' + } + ]; - done(); + beforeEach(function () { + logger.setLevel('FATAL'); + iotAgentConfig.authentication.permanentToken = true; }); - it('should not raise any error', function(done) { - request(deviceCreation, function(error, response, body) { - should.not.exist(error); - response.statusCode.should.equal(201); - contextBrokerMock.done(); - contextBrokerMock2.done(); - done(); - }); + afterEach(function (done) { + iotAgentLib.deactivate(done); + nock.cleanAll(); }); - it('should send the mixed data to the Context Broker', function(done) { - iotAgentLib.update('Light1', 'SensorMachine', '', values, function(error) { - should.not.exist(error); - contextBrokerMock3.done(); - done(); + describe('When a measure is sent to the Context Broker via an Update Context operation', function () { + beforeEach(function (done) { + nock.cleanAll(); + + contextBrokerMock = nock('http://unexistentHost:1026') + .matchHeader('fiware-service', 'TestService') + .matchHeader('fiware-servicepath', '/testingPath') + .matchHeader('Authorization', 'Bearer 999210dacf913772606c95dd0b895d5506cbc988') + .post( + '/v2/entities/machine1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContext3WithStatic.json' + ) + ) + .query({ type: 'SensorMachine' }) + .reply(204, {}); + + iotAgentConfig.authentication.tokenPath = '/oauth2/token'; + iotAgentLib.activate(iotAgentConfig, function () { + request(groupCreation, function (error, response, body) { + done(); + }); + }); }); - }); - - }); -}); - -describe('NGSI-v2 - Secured access to the Context Broker with OAuth2 provider (FIWARE Keyrock IDM)' + - 'configured through group provisioning. Permanent token', function() { - var groupCreation = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionFullGroup.json'), - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - } - }; - - var values = [ - { - name: 'status', - type: 'String', - value: 'STARTING' - } - ]; - - beforeEach(function() { - logger.setLevel('FATAL'); - iotAgentConfig.authentication.permanentToken = true; - }); - - afterEach(function(done) { - iotAgentLib.deactivate(done); - nock.cleanAll(); - }); - - describe('When a measure is sent to the Context Broker via an Update Context operation', function() { - beforeEach(function(done) { - nock.cleanAll(); - - contextBrokerMock = nock('http://unexistentHost:1026') - .matchHeader('fiware-service', 'TestService') - .matchHeader('fiware-servicepath', '/testingPath') - .matchHeader('Authorization', 'Bearer 999210dacf913772606c95dd0b895d5506cbc988') - .post('/v2/entities/machine1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext3WithStatic.json')) - .query({type: 'SensorMachine'}) - .reply(204, {}); - - - iotAgentConfig.authentication.tokenPath = '/oauth2/token'; - iotAgentLib.activate(iotAgentConfig, function() { - request(groupCreation, function(error, response, body) { + it('should send the permanent token in the auth header', function (done) { + iotAgentLib.update('machine1', 'SensorMachine', '', values, function (error) { + should.not.exist(error); + contextBrokerMock.done(); done(); }); }); - }); - it('should send the permanent token in the auth header', function(done) { - iotAgentLib.update('machine1', 'SensorMachine', '', values, function(error) { - should.not.exist(error); - contextBrokerMock.done(); - done(); - }); - }); - it('should use the permanent trust token in the following requests', function(done) { - iotAgentLib.update('machine1', 'SensorMachine', '', values, function(error) { - should.not.exist(error); - contextBrokerMock.done(); - done(); + it('should use the permanent trust token in the following requests', function (done) { + iotAgentLib.update('machine1', 'SensorMachine', '', values, function (error) { + should.not.exist(error); + contextBrokerMock.done(); + done(); + }); }); }); - }); -}); + } +); diff --git a/test/unit/ngsiv2/general/deviceService-test.js b/test/unit/ngsiv2/general/deviceService-test.js index 82d4bbcce..a63d8288b 100644 --- a/test/unit/ngsiv2/general/deviceService-test.js +++ b/test/unit/ngsiv2/general/deviceService-test.js @@ -22,176 +22,167 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; -/* jshint camelcase: false */ +/* eslint-disable no-unused-vars */ -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - should = require('should'), - nock = require('nock'), - request = require('request'), - logger = require('logops'), - async = require('async'), - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041 +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const nock = require('nock'); +const request = require('request'); +const logger = require('logops'); +const async = require('async'); +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'BrokenLight': { - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'Termometer': { - type: 'Termometer', - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ] - }, - 'Humidity': { - type: 'Humidity', - cbHost: 'http://192.168.1.1:3024', - commands: [], - lazy: [], - active: [ - { - name: 'humidity', - type: 'percentage' - } - ] - }, - 'Motion': { - type: 'Motion', - commands: [], - lazy: [], - staticAttributes: [ - { - 'name': 'location', - 'type': 'Vector', - 'value': '(123,523)' - } - ], - active: [ - { - name: 'humidity', - type: 'percentage' - } - ] - } + BrokenLight: { + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - iotManager: { - host: 'localhost', - port: 8082, - path: '/protocols', - protocol: 'MQTT_UL', - description: 'MQTT Ultralight 2.0 IoT Agent (Node.js version)' + Termometer: { + type: 'Termometer', + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [] }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' - }, - groupCreation = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/services', - method: 'POST', - json: { - services: [ + Humidity: { + type: 'Humidity', + cbHost: 'http://192.168.1.1:3024', + commands: [], + lazy: [], + active: [ { - resource: '', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', - entity_type: 'TheLightType', - trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', - cbHost: 'http://unexistentHost:1026', - commands: [], - lazy: [], - attributes: [ - { - name: 'status', - type: 'Boolean' - } - ], - static_attributes: [] + name: 'humidity', + type: 'percentage' } ] }, - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' + Motion: { + type: 'Motion', + commands: [], + lazy: [], + staticAttributes: [ + { + name: 'location', + type: 'Vector', + value: '(123,523)' + } + ], + active: [ + { + name: 'humidity', + type: 'percentage' + } + ] } }, - deviceCreation = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json'), - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - } + iotManager: { + host: 'localhost', + port: 8082, + path: '/protocols', + protocol: 'MQTT_UL', + description: 'MQTT Ultralight 2.0 IoT Agent (Node.js version)' }, - contextBrokerMock, - iotamMock; - + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; +const groupCreation = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/services', + method: 'POST', + json: { + services: [ + { + resource: '', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', + entity_type: 'TheLightType', + trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', + cbHost: 'http://unexistentHost:1026', + commands: [], + lazy: [], + attributes: [ + { + name: 'status', + type: 'Boolean' + } + ], + static_attributes: [] + } + ] + }, + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } +}; +const deviceCreation = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json'), + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } +}; +let contextBrokerMock; +let iotamMock; /* jshint camelcase: false */ -describe('NGSI-v2 - Device Service: utils', function() { - beforeEach(function(done) { +describe('NGSI-v2 - Device Service: utils', function () { + beforeEach(function (done) { nock.cleanAll(); logger.setLevel('FATAL'); - iotamMock = nock('http://localhost:8082') - .post('/protocols') - .reply(200, {}); + iotamMock = nock('http://localhost:8082').post('/protocols').reply(200, {}); iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { + afterEach(function (done) { nock.cleanAll(); - async.series([ - iotAgentLib.clearAll, - iotAgentLib.deactivate - ], done); + async.series([iotAgentLib.clearAll, iotAgentLib.deactivate], done); }); - describe('When an existing device tries to be retrieved with retrieveOrCreate()', function() { - beforeEach(function(done) { - + describe('When an existing device tries to be retrieved with retrieveOrCreate()', function () { + beforeEach(function (done) { // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under // provisioning folder @@ -201,16 +192,16 @@ describe('NGSI-v2 - Device Service: utils', function() { .post('/v2/entities?options=upsert') .reply(204); - async.series([ - request.bind(request, groupCreation), - request.bind(request, deviceCreation) - ], function(error, results) { + async.series([request.bind(request, groupCreation), request.bind(request, deviceCreation)], function ( + error, + results + ) { done(); }); }); - it('should return the existing device', function(done) { - iotAgentLib.retrieveDevice('Light1', '801230BJKL23Y9090DSFL123HJK09H324HV8732', function(error, device) { + it('should return the existing device', function (done) { + iotAgentLib.retrieveDevice('Light1', '801230BJKL23Y9090DSFL123HJK09H324HV8732', function (error, device) { should.not.exist(error); should.exist(device); @@ -220,9 +211,8 @@ describe('NGSI-v2 - Device Service: utils', function() { }); }); - describe('When an unexisting device tries to be retrieved for an existing APIKey', function() { - beforeEach(function(done) { - + describe('When an unexisting device tries to be retrieved for an existing APIKey', function () { + beforeEach(function (done) { // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under // provisioning folder @@ -232,36 +222,38 @@ describe('NGSI-v2 - Device Service: utils', function() { .post('/v2/entities?options=upsert') .reply(204); - async.series([ - request.bind(request, groupCreation) - ], function(error, results) { + async.series([request.bind(request, groupCreation)], function (error, results) { done(); }); }); - it('should register the device and return it', function(done) { - iotAgentLib.retrieveDevice('UNEXISTENT_DEV', '801230BJKL23Y9090DSFL123HJK09H324HV8732', - function(error, device) { - should.not.exist(error); - should.exist(device); + it('should register the device and return it', function (done) { + iotAgentLib.retrieveDevice('UNEXISTENT_DEV', '801230BJKL23Y9090DSFL123HJK09H324HV8732', function ( + error, + device + ) { + should.not.exist(error); + should.exist(device); - device.id.should.equal('UNEXISTENT_DEV'); - should.exist(device.protocol); - device.protocol.should.equal('MQTT_UL'); - done(); - }); + device.id.should.equal('UNEXISTENT_DEV'); + should.exist(device.protocol); + device.protocol.should.equal('MQTT_UL'); + done(); + }); }); }); - describe('When an unexisting device tries to be retrieved for an unexisting APIKey', function() { - it('should raise an error', function(done) { - iotAgentLib.retrieveDevice('UNEXISTENT_DEV_AND_GROUP', 'H2332Y909DSF3H346yh20JK092', - function(error, device) { - should.exist(error); - error.name.should.equal('DEVICE_GROUP_NOT_FOUND'); - should.not.exist(device); - done(); - }); + describe('When an unexisting device tries to be retrieved for an unexisting APIKey', function () { + it('should raise an error', function (done) { + iotAgentLib.retrieveDevice('UNEXISTENT_DEV_AND_GROUP', 'H2332Y909DSF3H346yh20JK092', function ( + error, + device + ) { + should.exist(error); + error.name.should.equal('DEVICE_GROUP_NOT_FOUND'); + should.not.exist(device); + done(); + }); }); }); }); diff --git a/test/unit/ngsiv2/general/https-support-test.js b/test/unit/ngsiv2/general/https-support-test.js index c619665f5..91e705384 100644 --- a/test/unit/ngsiv2/general/https-support-test.js +++ b/test/unit/ngsiv2/general/https-support-test.js @@ -23,129 +23,126 @@ * Modified by: Federico M. Facca - Martel Innovate * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; -/* jshint camelcase: false */ +/* eslint-disable no-unused-vars */ -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - request = require('request'), - nock = require('nock'), - utils = require('../../../tools/utils'), - groupRegistryMemory = require('../../../../lib/services/groups/groupRegistryMemory'), - should = require('should'), - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - url: 'https://192.168.1.1:1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ], - service: 'smartGondor', - subservice: 'gardens' - }, - 'Termometer': { - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ], - service: 'smartGondor', - subservice: 'gardens' - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - iotManager: { - url: 'https://mockediotam.com:9876', - path: '/protocols', - protocol: 'GENERIC_PROTOCOL', - description: 'A generic protocol', - agentPath: '/iot' - }, - defaultResource: '/iot/d' +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const request = require('request'); +const nock = require('nock'); +const utils = require('../../../tools/utils'); +const groupRegistryMemory = require('../../../../lib/services/groups/groupRegistryMemory'); +const should = require('should'); +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + url: 'https://192.168.1.1:1026', + ngsiVersion: 'v2' }, - groupCreation = { - service: 'theService', - subservice: 'theSubService', - resource: '/deviceTest', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', - type: 'SensorMachine', - trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', - commands: [ - { - name: 'wheel1', - type: 'Wheel' - } - ], - lazy: [ - { - name: 'luminescence', - type: 'Lumens' - } - ], - attributes: [ - { - name: 'status', - type: 'Boolean' - } - ] + server: { + port: 4041 }, - device1 = { - id: 'light1', - type: 'Light', - service: 'smartGondor', - subservice: 'gardens' + types: { + Light: { + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ], + service: 'smartGondor', + subservice: 'gardens' + }, + Termometer: { + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [], + service: 'smartGondor', + subservice: 'gardens' + } }, - contextBrokerMock, - iotamMock; - - -describe('NGSI-v2 - HTTPS support tests IOTAM', function() { + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + iotManager: { + url: 'https://mockediotam.com:9876', + path: '/protocols', + protocol: 'GENERIC_PROTOCOL', + description: 'A generic protocol', + agentPath: '/iot' + }, + defaultResource: '/iot/d' +}; +const groupCreation = { + service: 'theService', + subservice: 'theSubService', + resource: '/deviceTest', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', + type: 'SensorMachine', + trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', + commands: [ + { + name: 'wheel1', + type: 'Wheel' + } + ], + lazy: [ + { + name: 'luminescence', + type: 'Lumens' + } + ], + attributes: [ + { + name: 'status', + type: 'Boolean' + } + ] +}; +const device1 = { + id: 'light1', + type: 'Light', + service: 'smartGondor', + subservice: 'gardens' +}; +let contextBrokerMock; +let iotamMock; - describe('When the IoT Agents is started with https "iotManager" config', function() { - beforeEach(function(done) { +describe('NGSI-v2 - HTTPS support tests IOTAM', function () { + describe('When the IoT Agents is started with https "iotManager" config', function () { + beforeEach(function (done) { nock.cleanAll(); iotamMock = nock('https://mockediotam.com:9876') - .post('/protocols', - utils.readExampleFile('./test/unit/examples/iotamRequests/registrationWithGroupsWithoutCB.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); + .post( + '/protocols', + utils.readExampleFile('./test/unit/examples/iotamRequests/registrationWithGroupsWithoutCB.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); groupRegistryMemory.create(groupCreation, done); }); - afterEach(function(done) { + afterEach(function (done) { nock.cleanAll(); - groupRegistryMemory.clear(function() { + groupRegistryMemory.clear(function () { iotAgentLib.deactivate(done); }); }); - it('should register without errors to the IoT Manager', function(done) { - iotAgentLib.activate(iotAgentConfig, function(error) { + it('should register without errors to the IoT Manager', function (done) { + iotAgentLib.activate(iotAgentConfig, function (error) { should.not.exist(error); iotamMock.done(); done(); @@ -154,15 +151,15 @@ describe('NGSI-v2 - HTTPS support tests IOTAM', function() { }); }); -describe('NGSI-v2 - HTTPS support tests', function() { - - describe('When subscription is sent to HTTPS context broker', function() { - beforeEach(function(done) { - var optionsProvision = { +describe('NGSI-v2 - HTTPS support tests', function () { + describe('When subscription is sent to HTTPS context broker', function () { + beforeEach(function (done) { + const optionsProvision = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), + './test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json' + ), headers: { 'fiware-service': 'smartGondor', 'fiware-servicepath': '/gardens' @@ -171,42 +168,48 @@ describe('NGSI-v2 - HTTPS support tests', function() { nock.cleanAll(); - iotAgentLib.activate(iotAgentConfig, function() { + iotAgentLib.activate(iotAgentConfig, function () { contextBrokerMock = nock('https://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', - utils.readExampleFile('./test/unit/ngsiv2/examples/' + - 'contextRequests/createMinimumProvisionedDevice.json')) + .post( + '/v2/entities?options=upsert', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/createMinimumProvisionedDevice.json' + ) + ) .reply(204); contextBrokerMock = nock('https://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/subscriptions', utils.readExampleFile('./test/unit/ngsiv2/examples' + - '/subscriptionRequests/simpleSubscriptionRequest.json')) - .reply(201, null, {'Location': '/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8'}); - + .post( + '/v2/subscriptions', + utils.readExampleFile( + './test/unit/ngsiv2/examples/subscriptionRequests/simpleSubscriptionRequest.json' + ) + ) + .reply(201, null, { Location: '/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8' }); - iotAgentLib.clearAll(function() { - request(optionsProvision, function(error, result, body) { + iotAgentLib.clearAll(function () { + request(optionsProvision, function (error, result, body) { done(); }); }); }); }); - afterEach(function(done) { + afterEach(function (done) { nock.cleanAll(); iotAgentLib.setNotificationHandler(); - iotAgentLib.clearAll(function() { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - it('should send the appropriate request to the Context Broker', function(done) { - iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function(error, device) { - iotAgentLib.subscribe(device, ['attr_name'], null, function(error) { + it('should send the appropriate request to the Context Broker', function (done) { + iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function (error, device) { + iotAgentLib.subscribe(device, ['attr_name'], null, function (error) { should.not.exist(error); contextBrokerMock.done(); @@ -217,8 +220,8 @@ describe('NGSI-v2 - HTTPS support tests', function() { }); }); - describe('When a new device is connected to the IoT Agent', function() { - beforeEach(function(done) { + describe('When a new device is connected to the IoT Agent', function () { + beforeEach(function (done) { nock.cleanAll(); // This mock does not check the payload since the aim of the test is not to verify @@ -230,31 +233,31 @@ describe('NGSI-v2 - HTTPS support tests', function() { .post('/v2/entities?options=upsert') .reply(204); - var nockBody = utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json'); + const nockBody = utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json' + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v2/registrations', nockBody) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); - - iotAgentLib.activate(iotAgentConfig, function(error) { + iotAgentLib.activate(iotAgentConfig, function (error) { iotAgentLib.clearAll(done); }); }); - it('should register as ContextProvider using HTTPS', function(done) { - iotAgentLib.register(device1, function(error) { - should.not.exist(error); - contextBrokerMock.done(); - done(); + it('should register as ContextProvider using HTTPS', function (done) { + iotAgentLib.register(device1, function (error) { + should.not.exist(error); + contextBrokerMock.done(); + done(); }); }); - afterEach(function(done) { + afterEach(function (done) { nock.cleanAll(); - iotAgentLib.clearAll(function() { + iotAgentLib.clearAll(function () { // We need to remove the registrationId so that the library does not consider next operatios as updates. delete device1.registrationId; iotAgentLib.deactivate(done); diff --git a/test/unit/ngsiv2/general/iotam-autoregistration-test.js b/test/unit/ngsiv2/general/iotam-autoregistration-test.js index 2218a113f..0a7615b56 100644 --- a/test/unit/ngsiv2/general/iotam-autoregistration-test.js +++ b/test/unit/ngsiv2/general/iotam-autoregistration-test.js @@ -20,190 +20,187 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; - -/* jshint camelcase: false */ - -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - request = require('request'), - nock = require('nock'), - utils = require('../../../tools/utils'), - groupRegistryMemory = require('../../../../lib/services/groups/groupRegistryMemory'), - should = require('should'), - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - type: 'Light', + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const request = require('request'); +const nock = require('nock'); +const utils = require('../../../tools/utils'); +const groupRegistryMemory = require('../../../../lib/services/groups/groupRegistryMemory'); +const should = require('should'); +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + attributes: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] + } + }, + providerUrl: 'http://smartGondor.com', + iotManager: { + host: 'mockediotam.com', + port: 9876, + path: '/protocols', + protocol: 'GENERIC_PROTOCOL', + description: 'A generic protocol', + agentPath: '/iot' + }, + defaultResource: '/iot/d' +}; +const groupCreation = { + service: 'theService', + subservice: 'theSubService', + resource: '/deviceTest', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', + type: 'SensorMachine', + trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', + cbHost: 'http://unexistentHost:1026', + commands: [ + { + name: 'wheel1', + type: 'Wheel' + } + ], + lazy: [ + { + name: 'luminescence', + type: 'Lumens' + } + ], + attributes: [ + { + name: 'status', + type: 'Boolean' + } + ] +}; +const optionsCreation = { + url: 'http://localhost:4041/iot/services', + method: 'POST', + json: { + services: [ + { + resource: '/deviceTest', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', + entity_type: 'SensorMachine', + trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', + cbHost: 'http://unexistentHost:1026', + commands: [ + { + name: 'wheel1', + type: 'Wheel' + } + ], lazy: [ { - name: 'temperature', - type: 'centigrades' + name: 'luminescence', + type: 'Lumens' } ], attributes: [ { - name: 'pressure', - type: 'Hgmm' + name: 'status', + type: 'Boolean' } ] } - }, - providerUrl: 'http://smartGondor.com', - iotManager: { - host: 'mockediotam.com', - port: 9876, - path: '/protocols', - protocol: 'GENERIC_PROTOCOL', - description: 'A generic protocol', - agentPath: '/iot' - }, - defaultResource: '/iot/d' + ] }, - groupCreation = { - service: 'theService', - subservice: 'theSubService', - resource: '/deviceTest', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', - type: 'SensorMachine', - trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', - cbHost: 'http://unexistentHost:1026', - commands: [ - { - name: 'wheel1', - type: 'Wheel' - } - ], - lazy: [ - { - name: 'luminescence', - type: 'Lumens' - } - ], - attributes: [ + headers: { + 'fiware-service': 'theService', + 'fiware-servicepath': 'theSubService' + } +}; +const optionsCreationStatic = { + url: 'http://localhost:4041/iot/services', + method: 'POST', + json: { + services: [ { - name: 'status', - type: 'Boolean' + resource: '/deviceTest', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', + entity_type: 'SensorMachine', + trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', + cbHost: 'http://unexistentHost:1026', + commands: [ + { + name: 'wheel1', + type: 'Wheel' + } + ], + static_attributes: [ + { + name: 'position', + type: 'location', + values: '123,12' + } + ], + attributes: [ + { + name: 'status', + type: 'Boolean' + } + ] } ] }, - optionsCreation = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: { - services: [ - { - resource: '/deviceTest', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', - entity_type: 'SensorMachine', - trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', - cbHost: 'http://unexistentHost:1026', - commands: [ - { - name: 'wheel1', - type: 'Wheel' - } - ], - lazy: [ - { - name: 'luminescence', - type: 'Lumens' - } - ], - attributes: [ - { - name: 'status', - type: 'Boolean' - } - ] - } - ] - }, - headers: { - 'fiware-service': 'theService', - 'fiware-servicepath': 'theSubService' - } + headers: { + 'fiware-service': 'theService', + 'fiware-servicepath': 'theSubService' + } +}; +const optionsDelete = { + url: 'http://localhost:4041/iot/services', + method: 'DELETE', + json: {}, + headers: { + 'fiware-service': 'theService', + 'fiware-servicepath': 'theSubService' }, - optionsCreationStatic = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: { - services: [ - { - resource: '/deviceTest', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', - entity_type: 'SensorMachine', - trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', - cbHost: 'http://unexistentHost:1026', - commands: [ - { - name: 'wheel1', - type: 'Wheel' - } - ], - static_attributes: [ - { - name: 'position', - type: 'location', - values: '123,12' - } - ], - attributes: [ - { - name: 'status', - type: 'Boolean' - } - ] - } - ] - }, - headers: { - 'fiware-service': 'theService', - 'fiware-servicepath': 'theSubService' - } - }, - optionsDelete = { - url: 'http://localhost:4041/iot/services', - method: 'DELETE', - json: {}, - headers: { - 'fiware-service': 'theService', - 'fiware-servicepath': 'theSubService' - }, - qs: { - resource: '/deviceTest', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732' - } - }, - iotamMock; - -describe('NGSI-v2 - IoT Manager autoregistration', function() { - describe('When the IoT Agent is started without a "iotManager" config parameter and empty services', function() { - beforeEach(function() { + qs: { + resource: '/deviceTest', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732' + } +}; +let iotamMock; + +describe('NGSI-v2 - IoT Manager autoregistration', function () { + describe('When the IoT Agent is started without a "iotManager" config parameter and empty services', function () { + beforeEach(function () { nock.cleanAll(); iotamMock = nock('http://mockediotam.com:9876') - .post('/protocols', - utils.readExampleFile('./test/unit/examples/iotamRequests/registrationEmpty.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); + .post('/protocols', utils.readExampleFile('./test/unit/examples/iotamRequests/registrationEmpty.json')) + .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); }); - it('should register itself to the provided IoT Manager URL', function(done) { - iotAgentLib.activate(iotAgentConfig, function(error) { + it('should register itself to the provided IoT Manager URL', function (done) { + iotAgentLib.activate(iotAgentConfig, function (error) { should.not.exist(error); iotamMock.done(); done(); @@ -211,25 +208,23 @@ describe('NGSI-v2 - IoT Manager autoregistration', function() { }); }); - describe('When the IoT Agents is started with "iotManager" config with missing attributes', function() { - beforeEach(function() { + describe('When the IoT Agents is started with "iotManager" config with missing attributes', function () { + beforeEach(function () { nock.cleanAll(); delete iotAgentConfig.providerUrl; iotamMock = nock('http://mockediotam.com:9876') - .post('/protocols', - utils.readExampleFile('./test/unit/examples/iotamRequests/registrationEmpty.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); + .post('/protocols', utils.readExampleFile('./test/unit/examples/iotamRequests/registrationEmpty.json')) + .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); }); - afterEach(function() { + afterEach(function () { iotAgentConfig.providerUrl = 'http://smartGondor.com'; }); - it('should fail with a MISSING_CONFIG_PARAMS error', function(done) { - iotAgentLib.activate(iotAgentConfig, function(error) { + it('should fail with a MISSING_CONFIG_PARAMS error', function (done) { + iotAgentLib.activate(iotAgentConfig, function (error) { should.exist(error); error.name.should.equal('MISSING_CONFIG_PARAMS'); done(); @@ -237,27 +232,28 @@ describe('NGSI-v2 - IoT Manager autoregistration', function() { }); }); - describe('When the IoT Agents is started with "iotManager" config and multiple services', function() { - beforeEach(function(done) { + describe('When the IoT Agents is started with "iotManager" config and multiple services', function () { + beforeEach(function (done) { nock.cleanAll(); iotamMock = nock('http://mockediotam.com:9876') - .post('/protocols', - utils.readExampleFile('./test/unit/examples/iotamRequests/registrationWithGroups.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); + .post( + '/protocols', + utils.readExampleFile('./test/unit/examples/iotamRequests/registrationWithGroups.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); groupRegistryMemory.create(groupCreation, done); }); - afterEach(function(done) { - groupRegistryMemory.clear(function() { + afterEach(function (done) { + groupRegistryMemory.clear(function () { iotAgentLib.deactivate(done); }); }); - it('should send all the service information to the IoT Manager in the registration', function(done) { - iotAgentLib.activate(iotAgentConfig, function(error) { + it('should send all the service information to the IoT Manager in the registration', function (done) { + iotAgentLib.activate(iotAgentConfig, function (error) { should.not.exist(error); iotamMock.done(); done(); @@ -265,35 +261,34 @@ describe('NGSI-v2 - IoT Manager autoregistration', function() { }); }); - describe('When a new service is created in the IoT Agent', function() { - beforeEach(function(done) { + describe('When a new service is created in the IoT Agent', function () { + beforeEach(function (done) { nock.cleanAll(); iotamMock = nock('http://mockediotam.com:9876') - .post('/protocols', - utils.readExampleFile('./test/unit/examples/iotamRequests/registrationEmpty.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); + .post('/protocols', utils.readExampleFile('./test/unit/examples/iotamRequests/registrationEmpty.json')) + .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); iotamMock - .post('/protocols', - utils.readExampleFile('./test/unit/examples/iotamRequests/registrationWithGroups.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); + .post( + '/protocols', + utils.readExampleFile('./test/unit/examples/iotamRequests/registrationWithGroups.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); - iotAgentLib.activate(iotAgentConfig, function(error) { + iotAgentLib.activate(iotAgentConfig, function (error) { done(); }); }); - afterEach(function(done) { - groupRegistryMemory.clear(function() { + afterEach(function (done) { + groupRegistryMemory.clear(function () { iotAgentLib.deactivate(done); }); }); - it('should update the registration in the IoT Manager', function(done) { - request(optionsCreation, function(error, result, body) { + it('should update the registration in the IoT Manager', function (done) { + request(optionsCreation, function (error, result, body) { should.not.exist(error); iotamMock.done(); done(); @@ -301,35 +296,34 @@ describe('NGSI-v2 - IoT Manager autoregistration', function() { }); }); - describe('When a service is removed from the IoT Agent', function() { - beforeEach(function(done) { + describe('When a service is removed from the IoT Agent', function () { + beforeEach(function (done) { nock.cleanAll(); iotamMock = nock('http://mockediotam.com:9876') - .post('/protocols', - utils.readExampleFile('./test/unit/examples/iotamRequests/registrationWithGroups.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); + .post( + '/protocols', + utils.readExampleFile('./test/unit/examples/iotamRequests/registrationWithGroups.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); iotamMock - .post('/protocols', - utils.readExampleFile('./test/unit/examples/iotamRequests/registrationEmpty.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); + .post('/protocols', utils.readExampleFile('./test/unit/examples/iotamRequests/registrationEmpty.json')) + .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); - groupRegistryMemory.create(groupCreation, function() { + groupRegistryMemory.create(groupCreation, function () { iotAgentLib.activate(iotAgentConfig, done); }); }); - afterEach(function(done) { - groupRegistryMemory.clear(function() { + afterEach(function (done) { + groupRegistryMemory.clear(function () { iotAgentLib.deactivate(done); }); }); - it('should update the registration in the IoT Manager', function(done) { - request(optionsDelete, function(error, result, body) { + it('should update the registration in the IoT Manager', function (done) { + request(optionsDelete, function (error, result, body) { should.not.exist(error); iotamMock.done(); done(); @@ -337,35 +331,34 @@ describe('NGSI-v2 - IoT Manager autoregistration', function() { }); }); - describe('When a new service with static attributes is created in the IoT Agent', function() { - beforeEach(function(done) { + describe('When a new service with static attributes is created in the IoT Agent', function () { + beforeEach(function (done) { nock.cleanAll(); iotamMock = nock('http://mockediotam.com:9876') - .post('/protocols', - utils.readExampleFile('./test/unit/examples/iotamRequests/registrationEmpty.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); + .post('/protocols', utils.readExampleFile('./test/unit/examples/iotamRequests/registrationEmpty.json')) + .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); iotamMock - .post('/protocols', - utils.readExampleFile('./test/unit/examples/iotamRequests/registrationWithStaticGroups.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); + .post( + '/protocols', + utils.readExampleFile('./test/unit/examples/iotamRequests/registrationWithStaticGroups.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/iotamResponses/registrationSuccess.json')); - iotAgentLib.activate(iotAgentConfig, function(error) { + iotAgentLib.activate(iotAgentConfig, function (error) { done(); }); }); - afterEach(function(done) { - groupRegistryMemory.clear(function() { + afterEach(function (done) { + groupRegistryMemory.clear(function () { iotAgentLib.deactivate(done); }); }); - it('should update the registration in the IoT Manager', function(done) { - request(optionsCreationStatic, function(error, result, body) { + it('should update the registration in the IoT Manager', function (done) { + request(optionsCreationStatic, function (error, result, body) { should.not.exist(error); iotamMock.done(); done(); diff --git a/test/unit/ngsiv2/general/startup-test.js b/test/unit/ngsiv2/general/startup-test.js index 0d3921c13..0b429b284 100644 --- a/test/unit/ngsiv2/general/startup-test.js +++ b/test/unit/ngsiv2/general/startup-test.js @@ -22,48 +22,49 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - should = require('should'), - nock = require('nock'), - utils = require('../../../tools/utils'), - config = require('../../../../lib/commonConfig'), - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026', - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - attributes: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - } - }, - providerUrl: 'http://smartGondor.com' +/* eslint-disable no-unused-vars */ +/* eslint-disable no-unused-expressions */ + +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const should = require('should'); +const nock = require('nock'); +const utils = require('../../../tools/utils'); +const config = require('../../../../lib/commonConfig'); +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026' }, - iotamMock; - -describe('NGSI-v2 - Startup tests', function() { + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + attributes: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] + } + }, + providerUrl: 'http://smartGondor.com' +}; +let iotamMock; - describe('When the IoT Agent is started with environment variables', function() { - beforeEach(function() { +describe('NGSI-v2 - Startup tests', function () { + describe('When the IoT Agent is started with environment variables', function () { + beforeEach(function () { process.env.IOTA_CB_HOST = 'cbhost'; process.env.IOTA_CB_PORT = '1111'; process.env.IOTA_CB_NGSI_VERSION = 'v2'; @@ -88,11 +89,13 @@ describe('NGSI-v2 - Startup tests', function() { iotamMock = nock('http://iotamhost:4444') .post('/iotampath') - .reply(200, - utils.readExampleFile('./test/unit/ngsiv2/examples/iotamResponses/registrationSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/ngsiv2/examples/iotamResponses/registrationSuccess.json') + ); }); - afterEach(function() { + afterEach(function () { delete process.env.IOTA_CB_HOST; delete process.env.IOTA_CB_PORT; delete process.env.IOTA_CB_NGSI_VERSION; @@ -114,12 +117,12 @@ describe('NGSI-v2 - Startup tests', function() { delete process.env.IOTA_DEFAULT_RESOURCE; }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); }); - it('should load the correct configuration parameters', function(done) { - iotAgentLib.activate(iotAgentConfig, function(error) { + it('should load the correct configuration parameters', function (done) { + iotAgentLib.activate(iotAgentConfig, function (error) { config.getConfig().contextBroker.url.should.equal('http://cbhost:1111'); config.getConfig().contextBroker.ngsiVersion.should.equal('v2'); config.getConfig().server.host.should.equal('localhost'); @@ -142,8 +145,8 @@ describe('NGSI-v2 - Startup tests', function() { }); }); - describe('When the IoT Agent is started with mongodb params', function() { - beforeEach(function() { + describe('When the IoT Agent is started with mongodb params', function () { + beforeEach(function () { process.env.IOTA_MONGO_HOST = 'mongohost'; process.env.IOTA_MONGO_PORT = '5555'; process.env.IOTA_MONGO_DB = 'themongodb'; @@ -158,11 +161,13 @@ describe('NGSI-v2 - Startup tests', function() { iotamMock = nock('http://iotamhost:4444') .post('/iotampath') - .reply(200, - utils.readExampleFile('./test/unit/ngsiv2/examples/iotamResponses/registrationSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/ngsiv2/examples/iotamResponses/registrationSuccess.json') + ); }); - afterEach(function() { + afterEach(function () { delete process.env.IOTA_MONGO_HOST; delete process.env.IOTA_MONGO_PORT; delete process.env.IOTA_MONGO_DB; @@ -176,11 +181,11 @@ describe('NGSI-v2 - Startup tests', function() { delete process.env.IOTA_MONGO_EXTRAARGS; }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); }); - ['true', 'True', 'TRUE'].forEach(function(t) { + ['true', 'True', 'TRUE'].forEach(function (t) { it('should load ssl=ture with ssl=' + t, function (done) { process.env.IOTA_MONGO_SSL = t; @@ -194,6 +199,7 @@ describe('NGSI-v2 - Startup tests', function() { config.getConfig().mongodb.authSource.should.equal('customAuthSource'); config.getConfig().mongodb.retries.should.equal('10'); config.getConfig().mongodb.retryTime.should.equal('5'); + /* eslint-disable-next-line no-unused-expressions */ config.getConfig().mongodb.ssl.should.be.true; should.not.exist(config.getConfig().mongodb.extraArgs); done(); @@ -201,7 +207,7 @@ describe('NGSI-v2 - Startup tests', function() { }); }); - ['false', 'False', 'FALSE', 'invalid'].forEach(function(t) { + ['false', 'False', 'FALSE', 'invalid'].forEach(function (t) { it('should load ssl=false with ssl=' + t, function (done) { process.env.IOTA_MONGO_SSL = t; @@ -222,7 +228,7 @@ describe('NGSI-v2 - Startup tests', function() { }); }); - ['', 'undefined'].forEach(function(t) { + ['', 'undefined'].forEach(function (t) { it('should load no ssl parameter with ssl=' + t, function (done) { if (t !== 'undefined') { process.env.IOTA_MONGO_SSL = t; @@ -246,11 +252,14 @@ describe('NGSI-v2 - Startup tests', function() { }); [ - {in: '{"a": "b"}', expect: {a: 'b'}}, - {in: '{"a": "b", "c": "d"}', expect: {a: 'b', c: 'd'}}, - {in: '{"a": "b", "c": [1, 2], "d": -5, "e": {"f": "g"}}', expect: {a: 'b', c: [1, 2], d: -5, e: {f: 'g'}}}, - {in: '{}', expect: {}} - ].forEach(function(param) { + { in: '{"a": "b"}', expect: { a: 'b' } }, + { in: '{"a": "b", "c": "d"}', expect: { a: 'b', c: 'd' } }, + { + in: '{"a": "b", "c": [1, 2], "d": -5, "e": {"f": "g"}}', + expect: { a: 'b', c: [1, 2], d: -5, e: { f: 'g' } } + }, + { in: '{}', expect: {} } + ].forEach(function (param) { it('should load estraArgs with param=' + param.in, function (done) { process.env.IOTA_MONGO_EXTRAARGS = param.in; @@ -271,7 +280,7 @@ describe('NGSI-v2 - Startup tests', function() { }); }); - ['', 'str', '[]'].forEach(function(param) { + ['', 'str', '[]'].forEach(function (param) { it('should not load estraArgs with param=' + param, function (done) { process.env.IOTA_MONGO_EXTRAARGS = param; @@ -293,27 +302,25 @@ describe('NGSI-v2 - Startup tests', function() { }); }); - - describe('When the IoT Agent is started with Keystone', function() { - beforeEach(function() { + describe('When the IoT Agent is started with Keystone', function () { + beforeEach(function () { process.env.IOTA_AUTH_ENABLED = 'true'; process.env.IOTA_AUTH_USER = '1111'; process.env.IOTA_AUTH_PASSWORD = 'xxxx'; - }); - afterEach(function() { + afterEach(function () { delete process.env.IOTA_AUTH_ENABLED; delete process.env.IOTA_AUTH_USER; delete process.env.IOTA_AUTH_PASSWORD; }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); }); - it('should load the correct configuration parameters', function(done) { - iotAgentLib.activate(iotAgentConfig, function(error) { + it('should load the correct configuration parameters', function (done) { + iotAgentLib.activate(iotAgentConfig, function (error) { config.getConfig().authentication.user.should.equal('1111'); config.getConfig().authentication.password.should.equal('xxxx'); done(); @@ -321,26 +328,25 @@ describe('NGSI-v2 - Startup tests', function() { }); }); - describe('When the IoT Agent is started with Keyrock', function() { - beforeEach(function() { + describe('When the IoT Agent is started with Keyrock', function () { + beforeEach(function () { process.env.IOTA_AUTH_ENABLED = 'true'; process.env.IOTA_AUTH_CLIENT_ID = '1111'; process.env.IOTA_AUTH_CLIENT_SECRET = 'xxxx'; - }); - afterEach(function() { + afterEach(function () { delete process.env.IOTA_AUTH_ENABLED; delete process.env.IOTA_AUTH_CLIENT_ID; delete process.env.IOTA_AUTH_CLIENT_SECRET; }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); }); - it('should load the correct configuration parameters', function(done) { - iotAgentLib.activate(iotAgentConfig, function(error) { + it('should load the correct configuration parameters', function (done) { + iotAgentLib.activate(iotAgentConfig, function (error) { config.getConfig().authentication.clientId.should.equal('1111'); config.getConfig().authentication.clientSecret.should.equal('xxxx'); done(); diff --git a/test/unit/ngsiv2/lazyAndCommands/active-devices-attribute-update-test.js b/test/unit/ngsiv2/lazyAndCommands/active-devices-attribute-update-test.js index 9ba5253ad..767fcfe1b 100644 --- a/test/unit/ngsiv2/lazyAndCommands/active-devices-attribute-update-test.js +++ b/test/unit/ngsiv2/lazyAndCommands/active-devices-attribute-update-test.js @@ -22,50 +22,50 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - mongoUtils = require('../../mongodb/mongoDBUtils'), - request = require('request'), - contextBrokerMock, - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - // commands are not defined - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' - }, - device = { - id: 'somelight', - type: 'Light', - service: 'smartGondor', - subservice: 'gardens' - }; +/* eslint-disable no-unused-vars */ -describe('NGSI-v2 - Update attribute functionalities', function() { +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +const mongoUtils = require('../../mongodb/mongoDBUtils'); +const request = require('request'); +let contextBrokerMock; +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041 + }, + types: { + Light: { + // commands are not defined + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; +const device = { + id: 'somelight', + type: 'Light', + service: 'smartGondor', + subservice: 'gardens' +}; - beforeEach(function(done) { +describe('NGSI-v2 - Update attribute functionalities', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); nock.cleanAll(); @@ -74,7 +74,7 @@ describe('NGSI-v2 - Update attribute functionalities', function() { .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v2/registrations') - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') @@ -85,10 +85,10 @@ describe('NGSI-v2 - Update attribute functionalities', function() { iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { - iotAgentLib.deactivate(function() { - mongoUtils.cleanDbs(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { + iotAgentLib.deactivate(function () { + mongoUtils.cleanDbs(function () { nock.cleanAll(); iotAgentLib.setDataUpdateHandler(); iotAgentLib.setCommandHandler(); @@ -98,8 +98,8 @@ describe('NGSI-v2 - Update attribute functionalities', function() { }); }); - describe('When a attribute update arrives to the IoT Agent as Context Provider', function() { - var options = { + describe('When a attribute update arrives to the IoT Agent as Context Provider', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/update', method: 'POST', json: { @@ -121,8 +121,8 @@ describe('NGSI-v2 - Update attribute functionalities', function() { } }; - beforeEach(function(done) { - iotAgentLib.register(device, function(error) { + beforeEach(function (done) { + iotAgentLib.register(device, function (error) { if (error) { done('Device registration failed'); } @@ -130,10 +130,10 @@ describe('NGSI-v2 - Update attribute functionalities', function() { }); }); - it('should call the client handler with correct values, even if commands are not defined', function(done) { - var handlerCalled = false; + it('should call the client handler with correct values, even if commands are not defined', function (done) { + let handlerCalled = false; - iotAgentLib.setDataUpdateHandler(function(id, type, service, subservice, attributes, callback) { + iotAgentLib.setDataUpdateHandler(function (id, type, service, subservice, attributes, callback) { id.should.equal('Light:somelight'); type.should.equal('Light'); should.exist(attributes); @@ -143,14 +143,13 @@ describe('NGSI-v2 - Update attribute functionalities', function() { handlerCalled = true; callback(null, { - id: id, - type: type, - attributes: attributes + id, + type, + attributes }); }); - - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); handlerCalled.should.equal(true); done(); diff --git a/test/unit/ngsiv2/lazyAndCommands/command-test.js b/test/unit/ngsiv2/lazyAndCommands/command-test.js index aa409d1de..4f27f5173 100644 --- a/test/unit/ngsiv2/lazyAndCommands/command-test.js +++ b/test/unit/ngsiv2/lazyAndCommands/command-test.js @@ -22,108 +22,111 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - mongoUtils = require('../../mongodb/mongoDBUtils'), - request = require('request'), - timekeeper = require('timekeeper'), - contextBrokerMock, - statusAttributeMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +const mongoUtils = require('../../mongodb/mongoDBUtils'); +const request = require('request'); +const timekeeper = require('timekeeper'); +let contextBrokerMock; +let statusAttributeMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - server: { - port: 4041 + Termometer: { + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [] }, - types: { - 'Light': { - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'Termometer': { - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ] - }, - 'Motion': { - commands: [], - lazy: [ - { - name: 'moving', - type: 'Boolean' - } - ], - staticAttributes: [ - { - 'name': 'location', - 'type': 'Vector', - 'value': '(123,523)' - } - ], - active: [] - }, - 'Robot': { - commands: [ - { - name: 'position', - type: 'Array' - } - ], - lazy: [], - staticAttributes: [], - active: [] - } + Motion: { + commands: [], + lazy: [ + { + name: 'moving', + type: 'Boolean' + } + ], + staticAttributes: [ + { + name: 'location', + type: 'Vector', + value: '(123,523)' + } + ], + active: [] }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' + Robot: { + commands: [ + { + name: 'position', + type: 'Array' + } + ], + lazy: [], + staticAttributes: [], + active: [] + } }, - device3 = { - id: 'r2d2', - type: 'Robot', - service: 'smartGondor', - subservice: 'gardens' - }; + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; +const device3 = { + id: 'r2d2', + type: 'Robot', + service: 'smartGondor', + subservice: 'gardens' +}; -describe('NGSI-v2 - Command functionalities', function() { - beforeEach(function(done) { +describe('NGSI-v2 - Command functionalities', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - var time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 + const time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 timekeeper.freeze(time); nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/registrations', + .post( + '/v2/registrations', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgentCommands.json')) - .reply(201, null,{'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgentCommands.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') @@ -134,12 +137,12 @@ describe('NGSI-v2 - Command functionalities', function() { iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { + afterEach(function (done) { timekeeper.reset(); - delete(device3.registrationId); - iotAgentLib.clearAll(function() { - iotAgentLib.deactivate(function() { - mongoUtils.cleanDbs(function() { + delete device3.registrationId; + iotAgentLib.clearAll(function () { + iotAgentLib.deactivate(function () { + mongoUtils.cleanDbs(function () { nock.cleanAll(); iotAgentLib.setDataUpdateHandler(); iotAgentLib.setCommandHandler(); @@ -149,17 +152,17 @@ describe('NGSI-v2 - Command functionalities', function() { }); }); - describe('When a device is preregistered with commands', function() { - it('should register as Context Provider of the commands', function(done) { - iotAgentLib.register(device3, function(error) { + describe('When a device is preregistered with commands', function () { + it('should register as Context Provider of the commands', function (done) { + iotAgentLib.register(device3, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - describe('When a command update arrives to the IoT Agent as Context Provider', function() { - var options = { + describe('When a command update arrives to the IoT Agent as Context Provider', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/update', method: 'POST', json: { @@ -170,7 +173,7 @@ describe('NGSI-v2 - Command functionalities', function() { type: 'Robot', position: { type: 'Array', - value:'[28, -104, 23]' + value: '[28, -104, 23]' } } ] @@ -181,25 +184,24 @@ describe('NGSI-v2 - Command functionalities', function() { } }; - beforeEach(function(done) { - - iotAgentLib.register(device3, function(error) { + beforeEach(function (done) { + iotAgentLib.register(device3, function (error) { done(); }); }); - it('should call the client handler', function(done) { - var handlerCalled = false; + it('should call the client handler', function (done) { + let handlerCalled = false; - iotAgentLib.setCommandHandler(function(id, type, service, subservice, attributes, callback) { + iotAgentLib.setCommandHandler(function (id, type, service, subservice, attributes, callback) { id.should.equal(device3.type + ':' + device3.id); type.should.equal(device3.type); attributes[0].name.should.equal('position'); attributes[0].value.should.equal('[28, -104, 23]'); handlerCalled = true; callback(null, { - id: id, - type: type, + id, + type, attributes: [ { name: 'position', @@ -210,17 +212,17 @@ describe('NGSI-v2 - Command functionalities', function() { }); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); handlerCalled.should.equal(true); done(); }); }); - it('should create the attribute with the "_status" prefix in the Context Broker', function(done) { - iotAgentLib.setCommandHandler(function(id, type, service, subservice, attributes, callback) { + it('should create the attribute with the "_status" prefix in the Context Broker', function (done) { + iotAgentLib.setCommandHandler(function (id, type, service, subservice, attributes, callback) { callback(null, { - id: id, - type: type, + id, + type, attributes: [ { name: 'position', @@ -231,19 +233,19 @@ describe('NGSI-v2 - Command functionalities', function() { }); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); done(); }); }); - it('should create the attribute with the "_status" prefix in the Context Broker', function(done) { - var serviceAndSubservice = false; + it('should create the attribute with the "_status" prefix in the Context Broker', function (done) { + let serviceAndSubservice = false; - iotAgentLib.setCommandHandler(function(id, type, service, subservice, attributes, callback) { + iotAgentLib.setCommandHandler(function (id, type, service, subservice, attributes, callback) { serviceAndSubservice = service === 'smartGondor' && subservice === 'gardens'; callback(null, { - id: id, - type: type, + id, + type, attributes: [ { name: 'position', @@ -254,56 +256,58 @@ describe('NGSI-v2 - Command functionalities', function() { }); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { serviceAndSubservice.should.equal(true); done(); }); }); }); - describe('When an update arrives from the south bound for a registered command', function() { - beforeEach(function(done) { + describe('When an update arrives from the south bound for a registered command', function () { + beforeEach(function (done) { statusAttributeMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/r2d2/attrs?type=Robot', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextCommandFinish.json')) + .post( + '/v2/entities/r2d2/attrs?type=Robot', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextCommandFinish.json') + ) .reply(204); - iotAgentLib.register(device3, function(error) { + iotAgentLib.register(device3, function (error) { done(); }); }); - it('should update its value and status in the Context Broker', function(done) { - iotAgentLib.setCommandResult('r2d2', 'Robot', '', 'position', '[72, 368, 1]', 'FINISHED', - function(error) { - should.not.exist(error); - statusAttributeMock.done(); - done(); - }); + it('should update its value and status in the Context Broker', function (done) { + iotAgentLib.setCommandResult('r2d2', 'Robot', '', 'position', '[72, 368, 1]', 'FINISHED', function (error) { + should.not.exist(error); + statusAttributeMock.done(); + done(); + }); }); }); - describe('When an error command arrives from the south bound for a registered command', function() { - beforeEach(function(done) { + describe('When an error command arrives from the south bound for a registered command', function () { + beforeEach(function (done) { statusAttributeMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/r2d2/attrs?type=Robot', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextCommandError.json')) + .post( + '/v2/entities/r2d2/attrs?type=Robot', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextCommandError.json') + ) .reply(204); - iotAgentLib.register(device3, function(error) { + iotAgentLib.register(device3, function (error) { done(); }); }); - it('should update its status in the Context Broker', function(done) { - iotAgentLib.setCommandResult('r2d2', 'Robot', '', 'position', 'Stalled', 'ERROR', - function(error) { - should.not.exist(error); - statusAttributeMock.done(); - done(); - }); + it('should update its status in the Context Broker', function (done) { + iotAgentLib.setCommandResult('r2d2', 'Robot', '', 'position', 'Stalled', 'ERROR', function (error) { + should.not.exist(error); + statusAttributeMock.done(); + done(); + }); }); }); }); diff --git a/test/unit/ngsiv2/lazyAndCommands/lazy-devices-test.js b/test/unit/ngsiv2/lazyAndCommands/lazy-devices-test.js index 6de60746e..31ae03891 100644 --- a/test/unit/ngsiv2/lazyAndCommands/lazy-devices-test.js +++ b/test/unit/ngsiv2/lazyAndCommands/lazy-devices-test.js @@ -22,151 +22,151 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - async = require('async'), - apply = async.apply, - should = require('should'), - logger = require('logops'), - nock = require('nock'), - mongoUtils = require('../../mongodb/mongoDBUtils'), - request = require('request'), - timekeeper = require('timekeeper'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const async = require('async'); +const apply = async.apply; +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +const mongoUtils = require('../../mongodb/mongoDBUtils'); +const request = require('request'); +const timekeeper = require('timekeeper'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - server: { - port: 4041 + Termometer: { + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [] }, - types: { - 'Light': { - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'Termometer': { - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ] - }, - 'Motion': { - commands: [], - lazy: [ - { - name: 'moving', - type: 'Boolean' - } - ], - staticAttributes: [ - { - 'name': 'location', - 'type': 'Vector', - 'value': '(123,523)' - } - ], - active: [] - }, - 'RobotPre': { - commands: [], - lazy: [ - { - name: 'moving', - type: 'Boolean' - } - ], - staticAttributes: [], - attributes: [], - internalAttributes: { - lwm2mResourceMapping: { - position: { - objectType: 9090, - objectInstance: 0, - objectResource: 0 - } + Motion: { + commands: [], + lazy: [ + { + name: 'moving', + type: 'Boolean' + } + ], + staticAttributes: [ + { + name: 'location', + type: 'Vector', + value: '(123,523)' + } + ], + active: [] + }, + RobotPre: { + commands: [], + lazy: [ + { + name: 'moving', + type: 'Boolean' + } + ], + staticAttributes: [], + attributes: [], + internalAttributes: { + lwm2mResourceMapping: { + position: { + objectType: 9090, + objectInstance: 0, + objectResource: 0 } } } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' - }, - device1 = { - id: 'light1', - type: 'Light', - service: 'smartGondor', - subservice: 'gardens' - }, - device2 = { - id: 'motion1', - type: 'Motion', - service: 'smartGondor', - subservice: 'gardens' + } }, - device3 = { - id: 'TestRobotPre', - type: 'RobotPre', - service: 'smartGondor', - subservice: 'gardens', - internalAttributes: { - lwm2mResourceMapping: { - position: { - objectType: 6789, - objectInstance: 0, - objectResource: 17 - } + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; +const device1 = { + id: 'light1', + type: 'Light', + service: 'smartGondor', + subservice: 'gardens' +}; +const device2 = { + id: 'motion1', + type: 'Motion', + service: 'smartGondor', + subservice: 'gardens' +}; +const device3 = { + id: 'TestRobotPre', + type: 'RobotPre', + service: 'smartGondor', + subservice: 'gardens', + internalAttributes: { + lwm2mResourceMapping: { + position: { + objectType: 6789, + objectInstance: 0, + objectResource: 17 } } - }; + } +}; -describe('NGSI-v2 - IoT Agent Lazy Devices', function() { - beforeEach(function(done) { +describe('NGSI-v2 - IoT Agent Lazy Devices', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - var time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 + const time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 timekeeper.freeze(time); mongoUtils.cleanDbs(done); iotAgentLib.setDataQueryHandler(null); }); - afterEach(function(done) { + afterEach(function (done) { timekeeper.reset(); - delete(device1.registrationId); - delete(device2.registrationId); - delete(device3.registrationId); + delete device1.registrationId; + delete device2.registrationId; + delete device3.registrationId; - iotAgentLib.clearAll(function() { - iotAgentLib.deactivate(function() { + iotAgentLib.clearAll(function () { + iotAgentLib.deactivate(function () { mongoUtils.cleanDbs(done); }); }); }); - describe('When the IoT Agent receives an update on the device data in JSON format', function() { - var options = { + describe('When the IoT Agent receives an update on the device data in JSON format', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/update', method: 'POST', json: { @@ -188,16 +188,19 @@ describe('NGSI-v2 - IoT Agent Lazy Devices', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/registrations', + .post( + '/v2/registrations', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') @@ -205,22 +208,18 @@ describe('NGSI-v2 - IoT Agent Lazy Devices', function() { .post('/v2/entities?options=upsert') .reply(204); - async.series([ - apply(iotAgentLib.activate, iotAgentConfig), - apply(iotAgentLib.register, device1) - ], done); + async.series([apply(iotAgentLib.activate, iotAgentConfig), apply(iotAgentLib.register, device1)], done); }); - it('should call the device handler with the received data', function(done) { - - iotAgentLib.setDataUpdateHandler(function(id, type, service, subservice, attributes, callback) { + it('should call the device handler with the received data', function (done) { + iotAgentLib.setDataUpdateHandler(function (id, type, service, subservice, attributes, callback) { id.should.equal(device1.type + ':' + device1.id); type.should.equal(device1.type); attributes[0].value.should.equal(12); - callback(null); + callback(null); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(204); done(); @@ -228,50 +227,52 @@ describe('NGSI-v2 - IoT Agent Lazy Devices', function() { }); }); - describe('When a IoT Agent receives an update on multiple contexts', function() { + describe('When a IoT Agent receives an update on multiple contexts', function () { it('should call the device handler for each of the contexts'); }); - describe('When a context query arrives to the IoT Agent', function() { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/query', - method: 'POST', - json: true, - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': 'gardens' - }, - body: { - entities: [ - { - id: 'Light:light1' - } - ], - attrs: [ 'dimming' ] - } + describe('When a context query arrives to the IoT Agent', function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/query', + method: 'POST', + json: true, + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': 'gardens' }, - sensorData = [ - { - id: 'Light:light1', - type: 'Light', - dimming: + body: { + entities: [ { - type: 'Percentage', - value: 19 + id: 'Light:light1' } + ], + attrs: ['dimming'] + } + }; + const sensorData = [ + { + id: 'Light:light1', + type: 'Light', + dimming: { + type: 'Percentage', + value: 19 } - ]; + } + ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/registrations', + .post( + '/v2/registrations', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') @@ -279,24 +280,22 @@ describe('NGSI-v2 - IoT Agent Lazy Devices', function() { .post('/v2/entities?options=upsert') .reply(204); - async.series([ - apply(iotAgentLib.activate, iotAgentConfig), - apply(iotAgentLib.register, device1) - ], done); + async.series([apply(iotAgentLib.activate, iotAgentConfig), apply(iotAgentLib.register, device1)], done); }); - it('should return the information querying the underlying devices', function(done) { - var expectedResponse = utils - .readExampleFile('./test/unit/ngsiv2/examples/contextProviderResponses/queryInformationResponse.json'); + it('should return the information querying the underlying devices', function (done) { + const expectedResponse = utils.readExampleFile( + './test/unit/ngsiv2/examples/contextProviderResponses/queryInformationResponse.json' + ); - iotAgentLib.setDataQueryHandler(function(id, type, service, subservice, attributes, callback) { + iotAgentLib.setDataQueryHandler(function (id, type, service, subservice, attributes, callback) { id.should.equal(device1.type + ':' + device1.id); type.should.equal(device1.type); attributes[0].should.equal('dimming'); callback(null, sensorData[0]); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); body.should.eql(expectedResponse); done(); @@ -304,35 +303,38 @@ describe('NGSI-v2 - IoT Agent Lazy Devices', function() { }); }); - describe('When a context query arrives to the IoT Agent and no handler is set', function() { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/query', - method: 'POST', - json: true, - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': 'gardens' - }, - body: { - entities: [ - { - id: 'Light:light1' - } - ], - attrs: [ 'dimming' ] - } - }; + describe('When a context query arrives to the IoT Agent and no handler is set', function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/query', + method: 'POST', + json: true, + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': 'gardens' + }, + body: { + entities: [ + { + id: 'Light:light1' + } + ], + attrs: ['dimming'] + } + }; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/registrations', + .post( + '/v2/registrations', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') @@ -340,70 +342,71 @@ describe('NGSI-v2 - IoT Agent Lazy Devices', function() { .post('/v2/entities?options=upsert') .reply(204); - async.series([ - apply(iotAgentLib.activate, iotAgentConfig), - apply(iotAgentLib.register, device1) - ], function(error) { + async.series([apply(iotAgentLib.activate, iotAgentConfig), apply(iotAgentLib.register, device1)], function ( + error + ) { done(); }); }); - it('should not give any error', function(done) { - request(options, function(error, response, body) { + it('should not give any error', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(200); done(); }); }); - it('should return the empty value', function(done) { - request(options, function(error, response, body) { - var entities = body; + it('should return the empty value', function (done) { + request(options, function (error, response, body) { + const entities = body; entities[0].dimming.value.should.equal(''); done(); }); }); }); - describe('When a query arrives to the IoT Agent without any attributes', function() { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/query', - method: 'POST', - json: true, - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': 'gardens' - }, - body: { - entities: [ - { - id: 'Light:light1' - } - ] - } + describe('When a query arrives to the IoT Agent without any attributes', function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/query', + method: 'POST', + json: true, + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': 'gardens' }, - sensorData = [ - { - id: 'Light:light1', - type: 'Light', - temperature: + body: { + entities: [ { - type: 'centigrades', - value: 19 + id: 'Light:light1' } + ] + } + }; + const sensorData = [ + { + id: 'Light:light1', + type: 'Light', + temperature: { + type: 'centigrades', + value: 19 } - ]; + } + ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/registrations', + .post( + '/v2/registrations', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') @@ -411,25 +414,22 @@ describe('NGSI-v2 - IoT Agent Lazy Devices', function() { .post('/v2/entities?options=upsert') .reply(204); - async.series([ - apply(iotAgentLib.activate, iotAgentConfig), - apply(iotAgentLib.register, device1) - ], done); + async.series([apply(iotAgentLib.activate, iotAgentConfig), apply(iotAgentLib.register, device1)], done); }); - it('should return the information of all the attributes', function(done) { - var expectedResponse = utils.readExampleFile( - './test/unit/ngsiv2/examples/contextProviderResponses/' + - 'queryInformationResponseEmptyAttributes.json'); + it('should return the information of all the attributes', function (done) { + const expectedResponse = utils.readExampleFile( + './test/unit/ngsiv2/examples/contextProviderResponses/queryInformationResponseEmptyAttributes.json' + ); - iotAgentLib.setDataQueryHandler(function(id, type, service, subservice, attributes, callback) { + iotAgentLib.setDataQueryHandler(function (id, type, service, subservice, attributes, callback) { should.exist(attributes); attributes.length.should.equal(1); attributes[0].should.equal('temperature'); callback(null, sensorData[0]); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); body.should.eql(expectedResponse); done(); @@ -437,46 +437,48 @@ describe('NGSI-v2 - IoT Agent Lazy Devices', function() { }); }); - describe('When a context query arrives to the IoT Agent for a type with static attributes', function() { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/query', - method: 'POST', - json: true, - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': 'gardens' - }, - body: { - entities: [ - { - id: 'Motion:motion1' - } - ], - attrs: [ 'moving', 'location'] - } + describe('When a context query arrives to the IoT Agent for a type with static attributes', function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/query', + method: 'POST', + json: true, + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': 'gardens' }, - sensorData = [ - { - id: 'Motion:motion1', - type: 'Motion', - 'moving': + body: { + entities: [ { - type: 'Boolean', - value: true + id: 'Motion:motion1' } + ], + attrs: ['moving', 'location'] + } + }; + const sensorData = [ + { + id: 'Motion:motion1', + type: 'Motion', + moving: { + type: 'Boolean', + value: true } - ]; + } + ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/registrations', + .post( + '/v2/registrations', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent2.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent2.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') @@ -484,17 +486,15 @@ describe('NGSI-v2 - IoT Agent Lazy Devices', function() { .post('/v2/entities?options=upsert') .reply(204); - async.series([ - apply(iotAgentLib.activate, iotAgentConfig), - apply(iotAgentLib.register, device2) - ], done); + async.series([apply(iotAgentLib.activate, iotAgentConfig), apply(iotAgentLib.register, device2)], done); }); - it('should return the information adding the static attributes', function(done) { - var expectedResponse = utils.readExampleFile( - './test/unit/ngsiv2/examples/contextProviderResponses/queryInformationStaticAttributesResponse.json'); + it('should return the information adding the static attributes', function (done) { + const expectedResponse = utils.readExampleFile( + './test/unit/ngsiv2/examples/contextProviderResponses/queryInformationStaticAttributesResponse.json' + ); - iotAgentLib.setDataQueryHandler(function(id, type, service, subservice, attributes, callback) { + iotAgentLib.setDataQueryHandler(function (id, type, service, subservice, attributes, callback) { id.should.equal('Motion:motion1'); type.should.equal('Motion'); attributes[0].should.equal('moving'); @@ -502,7 +502,7 @@ describe('NGSI-v2 - IoT Agent Lazy Devices', function() { callback(null, sensorData[0]); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); body.should.eql(expectedResponse); done(); @@ -510,114 +510,125 @@ describe('NGSI-v2 - IoT Agent Lazy Devices', function() { }); }); - describe('When the IoT Agent receives an update on the device data in JSON format for a type with' + - 'internalAttributes', function() { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/update', - method: 'POST', - json: { - actionType: 'update', - entities: [ - { - id: 'RobotPre:TestRobotPre', - type: 'RobotPre', - moving: { - type: 'Boolean', - value: true - } - } - ] - }, - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': 'gardens' - } - }; - - beforeEach(function(done) { - nock.cleanAll(); - - contextBrokerMock = nock('http://192.168.1.1:1026') - .matchHeader('fiware-service', 'smartGondor') - .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/registrations', - utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent4.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); - - contextBrokerMock - .matchHeader('fiware-service', 'smartGondor') - .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities?options=upsert') - .reply(204); - - async.series([ - apply(iotAgentLib.activate, iotAgentConfig), - apply(iotAgentLib.register, device3) - ], done); - }); - - it('should call the device handler with the received data', function(done) { - - iotAgentLib.setDataUpdateHandler(function(id, type, service, subservice, attributes, callback) { - id.should.equal(device3.type + ':' + device3.id); - type.should.equal(device3.type); - attributes[0].value.should.equal(true); - callback(null); - }); - - request(options, function(error, response, body) { - should.not.exist(error); - response.statusCode.should.equal(204); - done(); - }); - }); - }); - - describe('When a context query arrives to the IoT Agent and id and type query params are not present', function() { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/query', + describe( + 'When the IoT Agent receives an update on the device data in JSON format for a type with' + + 'internalAttributes', + function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/update', method: 'POST', - json: true, - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': 'gardens' - }, - body: { + json: { + actionType: 'update', entities: [ { - idPattern: '.*' + id: 'RobotPre:TestRobotPre', + type: 'RobotPre', + moving: { + type: 'Boolean', + value: true + } } ] + }, + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': 'gardens' } }; - beforeEach(function(done) { + beforeEach(function (done) { + nock.cleanAll(); + + contextBrokerMock = nock('http://192.168.1.1:1026') + .matchHeader('fiware-service', 'smartGondor') + .matchHeader('fiware-servicepath', 'gardens') + .post( + '/v2/registrations', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent4.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); + + contextBrokerMock + .matchHeader('fiware-service', 'smartGondor') + .matchHeader('fiware-servicepath', 'gardens') + .post('/v2/entities?options=upsert') + .reply(204); + + async.series([apply(iotAgentLib.activate, iotAgentConfig), apply(iotAgentLib.register, device3)], done); + }); + + it('should call the device handler with the received data', function (done) { + iotAgentLib.setDataUpdateHandler(function (id, type, service, subservice, attributes, callback) { + id.should.equal(device3.type + ':' + device3.id); + type.should.equal(device3.type); + attributes[0].value.should.equal(true); + callback(null); + }); + + request(options, function (error, response, body) { + should.not.exist(error); + response.statusCode.should.equal(204); + done(); + }); + }); + } + ); + + describe('When a context query arrives to the IoT Agent and id and type query params are not present', function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/query', + method: 'POST', + json: true, + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': 'gardens' + }, + body: { + entities: [ + { + idPattern: '.*' + } + ] + } + }; + + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/registrations', + .post( + '/v2/registrations', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/registrations', + .post( + '/v2/registrations', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent2.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent2.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/registrations', + .post( + '/v2/registrations', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent4.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent4.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') @@ -626,17 +637,19 @@ describe('NGSI-v2 - IoT Agent Lazy Devices', function() { .times(3) .reply(204); - async.series([ - apply(iotAgentLib.activate, iotAgentConfig), - apply(iotAgentLib.register, device1), - apply(iotAgentLib.register, device2), - apply(iotAgentLib.register, device3), - ], done); + async.series( + [ + apply(iotAgentLib.activate, iotAgentConfig), + apply(iotAgentLib.register, device1), + apply(iotAgentLib.register, device2), + apply(iotAgentLib.register, device3) + ], + done + ); }); - it('should return error as idPattern is not supported', function(done) { - - request(options, function(error, response, body) { + it('should return error as idPattern is not supported', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(400); body.error.should.equal('BadRequest'); @@ -646,51 +659,60 @@ describe('NGSI-v2 - IoT Agent Lazy Devices', function() { }); }); - describe('When a context query arrives to the IoT Agent and id query param is not present', function() { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/query', - method: 'POST', - json: true, - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': 'gardens' - }, - body: { - entities: [ - { - idPattern: '.*', - type: 'Light' - } - ] - } - }; + describe('When a context query arrives to the IoT Agent and id query param is not present', function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/query', + method: 'POST', + json: true, + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': 'gardens' + }, + body: { + entities: [ + { + idPattern: '.*', + type: 'Light' + } + ] + } + }; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/registrations', + .post( + '/v2/registrations', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/registrations', + .post( + '/v2/registrations', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent2.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent2.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/registrations', + .post( + '/v2/registrations', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent4.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent4.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') @@ -699,17 +721,19 @@ describe('NGSI-v2 - IoT Agent Lazy Devices', function() { .times(3) .reply(204); - async.series([ - apply(iotAgentLib.activate, iotAgentConfig), - apply(iotAgentLib.register, device1), - apply(iotAgentLib.register, device2), - apply(iotAgentLib.register, device3), - ], done); + async.series( + [ + apply(iotAgentLib.activate, iotAgentConfig), + apply(iotAgentLib.register, device1), + apply(iotAgentLib.register, device2), + apply(iotAgentLib.register, device3) + ], + done + ); }); - it('should return error as idPattern is not supported', function(done) { - - request(options, function(error, response, body) { + it('should return error as idPattern is not supported', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(400); body.error.should.equal('BadRequest'); @@ -719,47 +743,49 @@ describe('NGSI-v2 - IoT Agent Lazy Devices', function() { }); }); - describe('When a query arrives to the IoT Agent with id, type and attributes', function() { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/query', - method: 'POST', - json: true, - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': 'gardens' - }, - body: { - entities: [ - { - id: 'Light:light1', - type: 'Light' - } - ], - attrs: [ 'temperature' ] - } + describe('When a query arrives to the IoT Agent with id, type and attributes', function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/query', + method: 'POST', + json: true, + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': 'gardens' }, - sensorData = [ - { - id: 'Light:light1', - type: 'Light', - temperature: + body: { + entities: [ { - type: 'centigrades', - value: 19 + id: 'Light:light1', + type: 'Light' } + ], + attrs: ['temperature'] + } + }; + const sensorData = [ + { + id: 'Light:light1', + type: 'Light', + temperature: { + type: 'centigrades', + value: 19 } - ]; + } + ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/registrations', + .post( + '/v2/registrations', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') @@ -767,25 +793,22 @@ describe('NGSI-v2 - IoT Agent Lazy Devices', function() { .post('/v2/entities?options=upsert') .reply(204); - async.series([ - apply(iotAgentLib.activate, iotAgentConfig), - apply(iotAgentLib.register, device1) - ], done); + async.series([apply(iotAgentLib.activate, iotAgentConfig), apply(iotAgentLib.register, device1)], done); }); - it('should return the information of all the attributes', function(done) { - var expectedResponse = utils.readExampleFile( - './test/unit/ngsiv2/examples/contextProviderResponses/' + - 'queryInformationResponseEmptyAttributes.json'); + it('should return the information of all the attributes', function (done) { + const expectedResponse = utils.readExampleFile( + './test/unit/ngsiv2/examples/contextProviderResponses/queryInformationResponseEmptyAttributes.json' + ); - iotAgentLib.setDataQueryHandler(function(id, type, service, subservice, attributes, callback) { + iotAgentLib.setDataQueryHandler(function (id, type, service, subservice, attributes, callback) { should.exist(attributes); attributes.length.should.equal(1); attributes[0].should.equal('temperature'); callback(null, sensorData[0]); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); body.should.eql(expectedResponse); done(); diff --git a/test/unit/ngsiv2/lazyAndCommands/polling-commands-test.js b/test/unit/ngsiv2/lazyAndCommands/polling-commands-test.js index d2bcf2ef9..de3c128b0 100644 --- a/test/unit/ngsiv2/lazyAndCommands/polling-commands-test.js +++ b/test/unit/ngsiv2/lazyAndCommands/polling-commands-test.js @@ -22,107 +22,107 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - mongoUtils = require('../../mongodb/mongoDBUtils'), - request = require('request'), - contextBrokerMock, - statusAttributeMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +const mongoUtils = require('../../mongodb/mongoDBUtils'); +const request = require('request'); +let contextBrokerMock; +let statusAttributeMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - server: { - port: 4041 + Termometer: { + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [] }, - types: { - 'Light': { - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'Termometer': { - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ] - }, - 'Motion': { - commands: [], - lazy: [ - { - name: 'moving', - type: 'Boolean' - } - ], - staticAttributes: [ - { - 'name': 'location', - 'type': 'Vector', - 'value': '(123,523)' - } - ], - active: [] - }, - 'Robot': { - commands: [ - { - name: 'position', - type: 'Array' - } - ], - lazy: [], - staticAttributes: [], - active: [] - } - }, - deviceRegistry: { - type: 'mongodb' + Motion: { + commands: [], + lazy: [ + { + name: 'moving', + type: 'Boolean' + } + ], + staticAttributes: [ + { + name: 'location', + type: 'Vector', + value: '(123,523)' + } + ], + active: [] }, + Robot: { + commands: [ + { + name: 'position', + type: 'Array' + } + ], + lazy: [], + staticAttributes: [], + active: [] + } + }, + deviceRegistry: { + type: 'mongodb' + }, - mongodb: { - host: 'localhost', - port: '27017', - db: 'iotagent' - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - pollingExpiration: 200, - pollingDaemonFrequency: 20 + mongodb: { + host: 'localhost', + port: '27017', + db: 'iotagent' }, - device3 = { - id: 'r2d2', - type: 'Robot', - service: 'smartGondor', - subservice: 'gardens', - polling: true - }; - -describe('NGSI-v2 - Polling commands', function() { - beforeEach(function(done) { + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + pollingExpiration: 200, + pollingDaemonFrequency: 20 +}; +const device3 = { + id: 'r2d2', + type: 'Robot', + service: 'smartGondor', + subservice: 'gardens', + polling: true +}; + +describe('NGSI-v2 - Polling commands', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); nock.cleanAll(); @@ -131,7 +131,7 @@ describe('NGSI-v2 - Polling commands', function() { .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v2/registrations') - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') @@ -139,15 +139,14 @@ describe('NGSI-v2 - Polling commands', function() { .post('/v2/entities?options=upsert') .reply(204); - iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { - delete(device3.registrationId); - iotAgentLib.clearAll(function() { - iotAgentLib.deactivate(function() { - mongoUtils.cleanDbs(function() { + afterEach(function (done) { + delete device3.registrationId; + iotAgentLib.clearAll(function () { + iotAgentLib.deactivate(function () { + mongoUtils.cleanDbs(function () { nock.cleanAll(); iotAgentLib.setDataUpdateHandler(); iotAgentLib.setCommandHandler(); @@ -157,8 +156,8 @@ describe('NGSI-v2 - Polling commands', function() { }); }); - describe('When a command update arrives to the IoT Agent for a device with polling', function() { - var options = { + describe('When a command update arrives to the IoT Agent for a device with polling', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/update', method: 'POST', json: { @@ -180,28 +179,29 @@ describe('NGSI-v2 - Polling commands', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { statusAttributeMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/Robot:r2d2/attrs?type=Robot', - utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextCommandStatus.json')) + .post( + '/v2/entities/Robot:r2d2/attrs?type=Robot', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextCommandStatus.json') + ) .reply(204); - iotAgentLib.register(device3, function(error) { + iotAgentLib.register(device3, function (error) { done(); }); }); - it('should not call the client handler', function(done) { - var handlerCalled = false; + it('should not call the client handler', function (done) { + let handlerCalled = false; - iotAgentLib.setCommandHandler(function(id, type, service, subservice, attributes, callback) { + iotAgentLib.setCommandHandler(function (id, type, service, subservice, attributes, callback) { handlerCalled = true; callback(null, { - id: id, - type: type, + id, + type, attributes: [ { name: 'position', @@ -212,30 +212,30 @@ describe('NGSI-v2 - Polling commands', function() { }); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); handlerCalled.should.equal(false); done(); }); }); - it('should create the attribute with the "_status" prefix in the Context Broker', function(done) { - iotAgentLib.setCommandHandler(function(id, type, service, subservice, attributes, callback) { + it('should create the attribute with the "_status" prefix in the Context Broker', function (done) { + iotAgentLib.setCommandHandler(function (id, type, service, subservice, attributes, callback) { callback(null); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); statusAttributeMock.done(); done(); }); }); - it('should store the commands in the queue', function(done) { - iotAgentLib.setCommandHandler(function(id, type, service, subservice, attributes, callback) { + it('should store the commands in the queue', function (done) { + iotAgentLib.setCommandHandler(function (id, type, service, subservice, attributes, callback) { callback(null); }); - request(options, function(error, response, body) { - iotAgentLib.commandQueue('smartGondor', 'gardens', 'r2d2', function(error, listCommands) { + request(options, function (error, response, body) { + iotAgentLib.commandQueue('smartGondor', 'gardens', 'r2d2', function (error, listCommands) { should.not.exist(error); listCommands.count.should.equal(1); listCommands.commands[0].name.should.equal('position'); @@ -247,8 +247,8 @@ describe('NGSI-v2 - Polling commands', function() { }); }); - describe('When a command arrives with multiple values in the value field', function() { - var options = { + describe('When a command arrives with multiple values in the value field', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/update', method: 'POST', json: { @@ -273,26 +273,27 @@ describe('NGSI-v2 - Polling commands', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { statusAttributeMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/Robot:r2d2/attrs?type=Robot', - utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextCommandStatus.json')) + .post( + '/v2/entities/Robot:r2d2/attrs?type=Robot', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextCommandStatus.json') + ) .reply(204); - iotAgentLib.register(device3, function(error) { + iotAgentLib.register(device3, function (error) { done(); }); }); - it('should return a 200 OK both in HTTP and in the status code', function(done) { - iotAgentLib.setCommandHandler(function(id, type, service, subservice, attributes, callback) { + it('should return a 200 OK both in HTTP and in the status code', function (done) { + iotAgentLib.setCommandHandler(function (id, type, service, subservice, attributes, callback) { callback(null); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(204); @@ -302,8 +303,8 @@ describe('NGSI-v2 - Polling commands', function() { }); }); - describe('When a polling command expires', function() { - var options = { + describe('When a polling command expires', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/v2/op/update', method: 'POST', json: { @@ -325,36 +326,40 @@ describe('NGSI-v2 - Polling commands', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { statusAttributeMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/Robot:r2d2/attrs?type=Robot', - utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextCommandStatus.json')) + .post( + '/v2/entities/Robot:r2d2/attrs?type=Robot', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextCommandStatus.json') + ) .reply(204); statusAttributeMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/Robot:r2d2/attrs?type=Robot', + .post( + '/v2/entities/Robot:r2d2/attrs?type=Robot', utils.readExampleFile( - './test/unit//ngsiv2/examples/contextRequests/updateContextCommandExpired.json')) + './test/unit//ngsiv2/examples/contextRequests/updateContextCommandExpired.json' + ) + ) .reply(204); - iotAgentLib.register(device3, function(error) { + iotAgentLib.register(device3, function (error) { done(); }); }); - it('should remove it from the queue', function(done) { - iotAgentLib.setCommandHandler(function(id, type, service, subservice, attributes, callback) { + it('should remove it from the queue', function (done) { + iotAgentLib.setCommandHandler(function (id, type, service, subservice, attributes, callback) { callback(null); }); - request(options, function(error, response, body) { - setTimeout(function() { - iotAgentLib.commandQueue('smartGondor', 'gardens', 'r2d2', function(error, listCommands) { + request(options, function (error, response, body) { + setTimeout(function () { + iotAgentLib.commandQueue('smartGondor', 'gardens', 'r2d2', function (error, listCommands) { should.not.exist(error); listCommands.count.should.equal(0); done(); @@ -363,14 +368,14 @@ describe('NGSI-v2 - Polling commands', function() { }); }); - it('should mark it as ERROR in the Context Broker', function(done) { - iotAgentLib.setCommandHandler(function(id, type, service, subservice, attributes, callback) { + it('should mark it as ERROR in the Context Broker', function (done) { + iotAgentLib.setCommandHandler(function (id, type, service, subservice, attributes, callback) { callback(null); }); - request(options, function(error, response, body) { - setTimeout(function() { - iotAgentLib.commandQueue('smartGondor', 'gardens', 'r2d2', function(error, listCommands) { + request(options, function (error, response, body) { + setTimeout(function () { + iotAgentLib.commandQueue('smartGondor', 'gardens', 'r2d2', function (error, listCommands) { statusAttributeMock.done(); done(); }); diff --git a/test/unit/ngsiv2/ngsiService/active-devices-test.js b/test/unit/ngsiv2/ngsiService/active-devices-test.js index 51a53e9a0..86dd06106 100644 --- a/test/unit/ngsiv2/ngsiService/active-devices-test.js +++ b/test/unit/ngsiv2/ngsiService/active-devices-test.js @@ -22,130 +22,130 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - timekeeper = require('timekeeper'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const timekeeper = require('timekeeper'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - server: { - port: 4041 + BrokenLight: { + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'BrokenLight': { - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'Termometer': { - type: 'Termometer', - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ] - }, - 'Humidity': { - type: 'Humidity', - cbHost: 'http://192.168.1.1:3024', - commands: [], - lazy: [], - active: [ - { - name: 'humidity', - type: 'percentage' - } - ] - }, - 'Motion': { - type: 'Motion', - commands: [], - lazy: [], - staticAttributes: [ - { - 'name': 'location', - 'type': 'geo:point', - 'value': '153,523' - } - ], - active: [ - { - name: 'humidity', - type: 'percentage' - } - ] - }, - 'Lamp': { - type: 'Lamp', - commands: [], - lazy: [], - staticAttributes: [ - { - 'name': 'controlledProperty', - 'type': 'text', - 'value': 'StaticValue', - 'metadata':{ - 'includes':{'type': 'Text', 'value' :'bell'} - } + Termometer: { + type: 'Termometer', + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [] + }, + Humidity: { + type: 'Humidity', + cbHost: 'http://192.168.1.1:3024', + commands: [], + lazy: [], + active: [ + { + name: 'humidity', + type: 'percentage' + } + ] + }, + Motion: { + type: 'Motion', + commands: [], + lazy: [], + staticAttributes: [ + { + name: 'location', + type: 'geo:point', + value: '153,523' + } + ], + active: [ + { + name: 'humidity', + type: 'percentage' + } + ] + }, + Lamp: { + type: 'Lamp', + commands: [], + lazy: [], + staticAttributes: [ + { + name: 'controlledProperty', + type: 'text', + value: 'StaticValue', + metadata: { + includes: { type: 'Text', value: 'bell' } } - ], - active: [ - { - name: 'luminosity', - type: 'text', - metadata:{ - unitCode:{type: 'Text', value :'CAL'} - } + } + ], + active: [ + { + name: 'luminosity', + type: 'text', + metadata: { + unitCode: { type: 'Text', value: 'CAL' } } - ] - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' - }; - -describe('NGSI-v2 - Active attributes test', function() { - var values = [ + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; + +describe('NGSI-v2 - Active attributes test', function () { + const values = [ { name: 'state', type: 'boolean', @@ -158,31 +158,33 @@ describe('NGSI-v2 - Active attributes test', function() { } ]; - beforeEach(function() { + beforeEach(function () { logger.setLevel('FATAL'); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); }); - describe('When the IoT Agent receives new information from a device', function() { - beforeEach(function(done) { + describe('When the IoT Agent receives new information from a device', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext.json') + ) + .query({ type: 'Light' }) .reply(204); iotAgentLib.activate(iotAgentConfig, done); }); - it('should change the value of the corresponding attribute in the context broker', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should change the value of the corresponding attribute in the context broker', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -190,11 +192,11 @@ describe('NGSI-v2 - Active attributes test', function() { }); }); - describe('When the IoT Agent receives new information and the timestamp flag is on', function() { - var modifiedValues; + describe('When the IoT Agent receives new information and the timestamp flag is on', function () { + let modifiedValues; - beforeEach(function(done) { - var time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 + beforeEach(function (done) { + const time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 modifiedValues = [ { @@ -216,24 +218,26 @@ describe('NGSI-v2 - Active attributes test', function() { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextTimestamp.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextTimestamp.json') + ) + .query({ type: 'Light' }) .reply(204); iotAgentConfig.timestamp = true; iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { + afterEach(function (done) { delete iotAgentConfig.timestamp; timekeeper.reset(); done(); }); - it('should add the timestamp to the entity and all the attributes', function(done) { - iotAgentLib.update('light1', 'Light', '', modifiedValues, function(error) { + it('should add the timestamp to the entity and all the attributes', function (done) { + iotAgentLib.update('light1', 'Light', '', modifiedValues, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -241,11 +245,10 @@ describe('NGSI-v2 - Active attributes test', function() { }); }); - describe('When the IoTA gets a set of values with a TimeInstant which are not in ISO8601 format', function() { - var modifiedValues; - - beforeEach(function(done) { + describe('When the IoTA gets a set of values with a TimeInstant which are not in ISO8601 format', function () { + let modifiedValues; + beforeEach(function (done) { modifiedValues = [ { name: 'state', @@ -265,13 +268,13 @@ describe('NGSI-v2 - Active attributes test', function() { iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { + afterEach(function (done) { delete iotAgentConfig.timestamp; done(); }); - it('should fail with a 400 BAD_TIMESTAMP error', function(done) { - iotAgentLib.update('light1', 'Light', '', modifiedValues, function(error) { + it('should fail with a 400 BAD_TIMESTAMP error', function (done) { + iotAgentLib.update('light1', 'Light', '', modifiedValues, function (error) { should.exist(error); error.code.should.equal(400); error.name.should.equal('BAD_TIMESTAMP'); @@ -280,12 +283,11 @@ describe('NGSI-v2 - Active attributes test', function() { }); }); - describe('When the IoTA gets a set of values with a TimeInstant which are in ISO8601 format ' + - 'without milis', function() { - var modifiedValues; + describe('When the IoTA gets a set of values with a TimeInstant which are in ISO8601 format without milis', function () { + let modifiedValues; - beforeEach(function(done) { - var time = new Date(1666477342000); // 2022-10-22T22:22:22Z + beforeEach(function (done) { + const time = new Date(1666477342000); // 2022-10-22T22:22:22Z modifiedValues = [ { @@ -307,25 +309,28 @@ describe('NGSI-v2 - Active attributes test', function() { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextTimestampOverrideWithoutMilis.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextTimestampOverrideWithoutMilis.json' + ) + ) + .query({ type: 'Light' }) .reply(204); iotAgentConfig.timestamp = true; iotAgentLib.activate(iotAgentConfig, done); - }); - afterEach(function(done) { + afterEach(function (done) { delete iotAgentConfig.timestamp; timekeeper.reset(); done(); }); - it('should not fail', function(done) { - iotAgentLib.update('light1', 'Light', '', modifiedValues, function(error) { + it('should not fail', function (done) { + iotAgentLib.update('light1', 'Light', '', modifiedValues, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -333,12 +338,11 @@ describe('NGSI-v2 - Active attributes test', function() { }); }); - describe('When the IoT Agent receives new information, the timestamp flag is on' + - 'and timezone is defined', function() { - var modifiedValues; + describe('When the IoT Agent receives new information, the timestamp flag is onand timezone is defined', function () { + let modifiedValues; - beforeEach(function(done) { - var time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 + beforeEach(function (done) { + const time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 modifiedValues = [ { @@ -360,10 +364,13 @@ describe('NGSI-v2 - Active attributes test', function() { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/' + - 'updateContextTimestampTimezone.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextTimestampTimezone.json' + ) + ) + .query({ type: 'Light' }) .reply(204); iotAgentConfig.timestamp = true; @@ -371,7 +378,7 @@ describe('NGSI-v2 - Active attributes test', function() { iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { + afterEach(function (done) { delete iotAgentConfig.timestamp; delete iotAgentConfig.types.Light.timezone; timekeeper.reset(); @@ -379,8 +386,8 @@ describe('NGSI-v2 - Active attributes test', function() { done(); }); - it('should add the timestamp to the entity and all the attributes', function(done) { - iotAgentLib.update('light1', 'Light', '', modifiedValues, function(error) { + it('should add the timestamp to the entity and all the attributes', function (done) { + iotAgentLib.update('light1', 'Light', '', modifiedValues, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -388,11 +395,11 @@ describe('NGSI-v2 - Active attributes test', function() { }); }); - describe('When the IoTA gets a set of values with a TimeInstant and the timestamp flag is on', function() { - var modifiedValues; + describe('When the IoTA gets a set of values with a TimeInstant and the timestamp flag is on', function () { + let modifiedValues; - beforeEach(function(done) { - var time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 + beforeEach(function (done) { + const time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 modifiedValues = [ { @@ -414,24 +421,28 @@ describe('NGSI-v2 - Active attributes test', function() { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextTimestampOverride.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextTimestampOverride.json' + ) + ) + .query({ type: 'Light' }) .reply(204); iotAgentConfig.timestamp = true; iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { + afterEach(function (done) { delete iotAgentConfig.timestamp; timekeeper.reset(); done(); }); - it('should not override the received instant and should not add metadatas for this request', function(done) { - iotAgentLib.update('light1', 'Light', '', modifiedValues, function(error) { + it('should not override the received instant and should not add metadatas for this request', function (done) { + iotAgentLib.update('light1', 'Light', '', modifiedValues, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -439,12 +450,11 @@ describe('NGSI-v2 - Active attributes test', function() { }); }); - describe('When the IoTA gets a set of values with a TimeInstant, the timestamp flag is on' + - 'and timezone is defined', function() { - var modifiedValues; + describe('When the IoTA gets a set of values with a TimeInstant, the timestamp flag is onand timezone is defined', function () { + let modifiedValues; - beforeEach(function(done) { - var time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 + beforeEach(function (done) { + const time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 modifiedValues = [ { @@ -466,9 +476,13 @@ describe('NGSI-v2 - Active attributes test', function() { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextTimestampOverride.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextTimestampOverride.json' + ) + ) + .query({ type: 'Light' }) .reply(204); iotAgentConfig.timestamp = true; @@ -476,7 +490,7 @@ describe('NGSI-v2 - Active attributes test', function() { iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function(done) { + afterEach(function (done) { delete iotAgentConfig.timestamp; delete iotAgentConfig.types.Light.timezone; timekeeper.reset(); @@ -484,8 +498,8 @@ describe('NGSI-v2 - Active attributes test', function() { done(); }); - it('should not override the received instant and should not add metadatas for this request', function(done) { - iotAgentLib.update('light1', 'Light', '', modifiedValues, function(error) { + it('should not override the received instant and should not add metadatas for this request', function (done) { + iotAgentLib.update('light1', 'Light', '', modifiedValues, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -493,15 +507,15 @@ describe('NGSI-v2 - Active attributes test', function() { }); }); - describe('When the IoT Agent receives information from a device whose type doesn\'t have a type name', function() { - beforeEach(function(done) { + describe("When the IoT Agent receives information from a device whose type doesn't have a type name", function () { + beforeEach(function (done) { nock.cleanAll(); iotAgentLib.activate(iotAgentConfig, done); }); - it('should fail with a 500 TYPE_NOT_FOUND error', function(done) { - iotAgentLib.update('light1', 'BrokenLight', '', values, function(error) { + it('should fail with a 500 TYPE_NOT_FOUND error', function (done) { + iotAgentLib.update('light1', 'BrokenLight', '', values, function (error) { should.exist(error); error.code.should.equal(500); error.name.should.equal('TYPE_NOT_FOUND'); @@ -510,24 +524,28 @@ describe('NGSI-v2 - Active attributes test', function() { }); }); - describe('When the Context Broker returns an HTTP error code updating an entity', function() { - beforeEach(function(done) { + describe('When the Context Broker returns an HTTP error code updating an entity', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext.json')) - .query({type: 'Light'}) - .reply(413, - utils.readExampleFile('./test/unit/ngsiv2/examples/contextResponses/updateContext1Failed.json')); + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext.json') + ) + .query({ type: 'Light' }) + .reply( + 413, + utils.readExampleFile('./test/unit/ngsiv2/examples/contextResponses/updateContext1Failed.json') + ); iotAgentLib.activate(iotAgentConfig, done); }); - it('should return ENTITY_GENERIC_ERROR an error to the caller', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should return ENTITY_GENERIC_ERROR an error to the caller', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.exist(error); should.exist(error.name); error.code.should.equal(413); @@ -539,24 +557,28 @@ describe('NGSI-v2 - Active attributes test', function() { }); }); - describe('When the Context Broker returns an application error code updating an entity', function() { - beforeEach(function(done) { + describe('When the Context Broker returns an application error code updating an entity', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext.json')) - .query({type: 'Light'}) - .reply(400, - utils.readExampleFile('./test/unit/ngsiv2/examples/contextResponses/updateContext2Failed.json')); + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext.json') + ) + .query({ type: 'Light' }) + .reply( + 400, + utils.readExampleFile('./test/unit/ngsiv2/examples/contextResponses/updateContext2Failed.json') + ); iotAgentLib.activate(iotAgentConfig, done); }); - it('should return ENTITY_GENERIC_ERROR an error to the caller', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should return ENTITY_GENERIC_ERROR an error to the caller', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.exist(error); should.exist(error.name); error.name.should.equal('ENTITY_GENERIC_ERROR'); @@ -565,24 +587,28 @@ describe('NGSI-v2 - Active attributes test', function() { }); }); - describe('When there is a transport error connecting to the Context Broker', function() { - beforeEach(function(done) { + describe('When there is a transport error connecting to the Context Broker', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext.json')) - .query({type: 'Light'}) - .reply(500, - utils.readExampleFile('./test/unit/ngsiv2/examples/contextResponses/updateContext2Failed.json')); + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext.json') + ) + .query({ type: 'Light' }) + .reply( + 500, + utils.readExampleFile('./test/unit/ngsiv2/examples/contextResponses/updateContext2Failed.json') + ); iotAgentLib.activate(iotAgentConfig, done); }); - it('should return a ENTITY_GENERIC_ERROR error to the caller', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should return a ENTITY_GENERIC_ERROR error to the caller', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.exist(error); should.exist(error.name); error.name.should.equal('ENTITY_GENERIC_ERROR'); @@ -594,23 +620,25 @@ describe('NGSI-v2 - Active attributes test', function() { }); }); - describe('When the IoT Agent recieves information for a type with a configured Context Broker', function() { - beforeEach(function(done) { + describe('When the IoT Agent recieves information for a type with a configured Context Broker', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:3024') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/humSensor/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext.json')) - .query({type: 'Humidity'}) + .post( + '/v2/entities/humSensor/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContext.json') + ) + .query({ type: 'Humidity' }) .reply(204); iotAgentLib.activate(iotAgentConfig, done); }); - it('should use the Context Broker defined by the type', function(done) { - iotAgentLib.update('humSensor', 'Humidity', '', values, function(error) { + it('should use the Context Broker defined by the type', function (done) { + iotAgentLib.update('humSensor', 'Humidity', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -618,8 +646,8 @@ describe('NGSI-v2 - Active attributes test', function() { }); }); - describe('When an IoT Agent receives information for a type with static attributes', function() { - var newValues = [ + describe('When an IoT Agent receives information for a type with static attributes', function () { + const newValues = [ { name: 'moving', type: 'boolean', @@ -627,21 +655,25 @@ describe('NGSI-v2 - Active attributes test', function() { } ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/motion1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextStaticAttributes.json')) - .query({type: 'Motion'}) + .post( + '/v2/entities/motion1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextStaticAttributes.json' + ) + ) + .query({ type: 'Motion' }) .reply(204); iotAgentLib.activate(iotAgentConfig, done); }); - it('should decorate the entity with the static attributes', function(done) { - iotAgentLib.update('motion1', 'Motion', '', newValues, function(error) { + it('should decorate the entity with the static attributes', function (done) { + iotAgentLib.update('motion1', 'Motion', '', newValues, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -649,9 +681,8 @@ describe('NGSI-v2 - Active attributes test', function() { }); }); - - describe('When an IoT Agent receives information for a type with static attributes with metadata', function() { - var newValues = [ + describe('When an IoT Agent receives information for a type with static attributes with metadata', function () { + const newValues = [ { name: 'luminosity', type: 'text', @@ -659,22 +690,26 @@ describe('NGSI-v2 - Active attributes test', function() { } ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); /* jshint maxlen: 200 */ contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/lamp1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextStaticAttributesMetadata.json')) - .query({type: 'Lamp'}) + .post( + '/v2/entities/lamp1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextStaticAttributesMetadata.json' + ) + ) + .query({ type: 'Lamp' }) .reply(204); iotAgentLib.activate(iotAgentConfig, done); }); - it('should decorate the entity with the static attributes', function(done) { - iotAgentLib.update('lamp1', 'Lamp', '', newValues, function(error) { + it('should decorate the entity with the static attributes', function (done) { + iotAgentLib.update('lamp1', 'Lamp', '', newValues, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); diff --git a/test/unit/ngsiv2/ngsiService/autocast-test.js b/test/unit/ngsiv2/ngsiService/autocast-test.js index da5517e26..c3707494d 100644 --- a/test/unit/ngsiv2/ngsiService/autocast-test.js +++ b/test/unit/ngsiv2/ngsiService/autocast-test.js @@ -22,78 +22,77 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - autocast: true, - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - type: 'Light', - active: [ - { - name: 'pressure', - type: 'Number' - }, - { - name: 'temperature', - type: 'Number' - }, - { - name: 'id', - type: 'String' - }, - { - name: 'status', - type: 'Boolean' - }, - { - name: 'keep_alive', - type: 'None' - }, - { - name: 'tags', - type: 'Array' - }, - { - name: 'configuration', - type: 'Object' - } - ] - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' - }; - -describe('NGSI-v2 - JSON native types autocast test', function() { - beforeEach(function() { + +/* eslint-disable no-useless-concat */ + +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + autocast: true, + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + active: [ + { + name: 'pressure', + type: 'Number' + }, + { + name: 'temperature', + type: 'Number' + }, + { + name: 'id', + type: 'String' + }, + { + name: 'status', + type: 'Boolean' + }, + { + name: 'keep_alive', + type: 'None' + }, + { + name: 'tags', + type: 'Array' + }, + { + name: 'configuration', + type: 'Object' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; + +describe('NGSI-v2 - JSON native types autocast test', function () { + beforeEach(function () { logger.setLevel('FATAL'); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); }); - describe('When the IoT Agent receives new information from a device.' + - 'Observation with Number type and Integer value', function() { - - var values = [ + describe('When the IoT Agent receives new information from a device. Observation with Number type and Integer value', function () { + const values = [ { name: 'pressure', type: 'Number', @@ -101,22 +100,24 @@ describe('NGSI-v2 - JSON native types autocast test', function() { } ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAutocast1.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAutocast1.json') + ) + .query({ type: 'Light' }) .reply(204); iotAgentLib.activate(iotAgentConfig, done); }); - it('should change the value of the corresponding attribute in the context broker', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should change the value of the corresponding attribute in the context broker', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -124,10 +125,8 @@ describe('NGSI-v2 - JSON native types autocast test', function() { }); }); - describe('When the IoT Agent receives new information from a device.' + - 'Observation with Number type and Float value', function() { - - var values = [ + describe('When the IoT Agent receives new information from a device. Observation with Number type and Float value', function () { + const values = [ { name: 'temperature', type: 'Number', @@ -135,22 +134,24 @@ describe('NGSI-v2 - JSON native types autocast test', function() { } ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAutocast2.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAutocast2.json') + ) + .query({ type: 'Light' }) .reply(204); iotAgentLib.activate(iotAgentConfig, done); }); - it('should change the value of the corresponding attribute in the context broker', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should change the value of the corresponding attribute in the context broker', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -158,10 +159,8 @@ describe('NGSI-v2 - JSON native types autocast test', function() { }); }); - describe('When the IoT Agent receives new information from a device.' + - 'Observation with Boolean type and True value', function() { - - var values = [ + describe('When the IoT Agent receives new information from a device. Observation with Boolean type and True value', function () { + const values = [ { name: 'status', type: 'Boolean', @@ -169,22 +168,24 @@ describe('NGSI-v2 - JSON native types autocast test', function() { } ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAutocast3.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAutocast3.json') + ) + .query({ type: 'Light' }) .reply(204); iotAgentLib.activate(iotAgentConfig, done); }); - it('should change the value of the corresponding attribute in the context broker', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should change the value of the corresponding attribute in the context broker', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -192,10 +193,8 @@ describe('NGSI-v2 - JSON native types autocast test', function() { }); }); - describe('When the IoT Agent receives new information from a device.' + - 'Observation with Boolean type and False value', function() { - - var values = [ + describe('When the IoT Agent receives new information from a device. Observation with Boolean type and False value', function () { + const values = [ { name: 'status', type: 'Boolean', @@ -203,22 +202,24 @@ describe('NGSI-v2 - JSON native types autocast test', function() { } ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAutocast4.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAutocast4.json') + ) + .query({ type: 'Light' }) .reply(204); iotAgentLib.activate(iotAgentConfig, done); }); - it('should change the value of the corresponding attribute in the context broker', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should change the value of the corresponding attribute in the context broker', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -226,9 +227,8 @@ describe('NGSI-v2 - JSON native types autocast test', function() { }); }); - describe('When the IoT Agent receives new information from a device. Observation with None type', function() { - - var values = [ + describe('When the IoT Agent receives new information from a device. Observation with None type', function () { + const values = [ { name: 'keep_alive', type: 'None', @@ -236,22 +236,24 @@ describe('NGSI-v2 - JSON native types autocast test', function() { } ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAutocast5.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAutocast5.json') + ) + .query({ type: 'Light' }) .reply(204); iotAgentLib.activate(iotAgentConfig, done); }); - it('should change the value of the corresponding attribute in the context broker', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should change the value of the corresponding attribute in the context broker', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -259,9 +261,8 @@ describe('NGSI-v2 - JSON native types autocast test', function() { }); }); - describe('When the IoT Agent receives new information from a device. Observation with Array type', function() { - - var values = [ + describe('When the IoT Agent receives new information from a device. Observation with Array type', function () { + const values = [ { name: 'tags', type: 'Array', @@ -269,22 +270,24 @@ describe('NGSI-v2 - JSON native types autocast test', function() { } ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAutocast6.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAutocast6.json') + ) + .query({ type: 'Light' }) .reply(204); iotAgentLib.activate(iotAgentConfig, done); }); - it('should change the value of the corresponding attribute in the context broker', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should change the value of the corresponding attribute in the context broker', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -292,9 +295,8 @@ describe('NGSI-v2 - JSON native types autocast test', function() { }); }); - describe('When the IoT Agent receives new information from a device. Observation with Object type', function() { - - var values = [ + describe('When the IoT Agent receives new information from a device. Observation with Object type', function () { + const values = [ { name: 'configuration', type: 'Object', @@ -302,22 +304,24 @@ describe('NGSI-v2 - JSON native types autocast test', function() { } ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAutocast7.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAutocast7.json') + ) + .query({ type: 'Light' }) .reply(204); iotAgentLib.activate(iotAgentConfig, done); }); - it('should change the value of the corresponding attribute in the context broker', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should change the value of the corresponding attribute in the context broker', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); diff --git a/test/unit/ngsiv2/ngsiService/staticAttributes-test.js b/test/unit/ngsiv2/ngsiService/staticAttributes-test.js index 0181dbf15..a7d240f8f 100644 --- a/test/unit/ngsiv2/ngsiService/staticAttributes-test.js +++ b/test/unit/ngsiv2/ngsiService/staticAttributes-test.js @@ -22,68 +22,68 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - async = require('async'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ], - staticAttributes: [ - { - name: 'attr1', - type: 'type1' - }, - { - name: 'attr2', - type: 'type2' - }, - { - name: 'attr3', - type: 'type3' - }, - { - name: 'attr4', - type: 'type4' - }, - ] - } - }, - timestamp: true, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' - }; +/* eslint-disable no-unused-vars */ +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const async = require('async'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ], + staticAttributes: [ + { + name: 'attr1', + type: 'type1' + }, + { + name: 'attr2', + type: 'type2' + }, + { + name: 'attr3', + type: 'type3' + }, + { + name: 'attr4', + type: 'type4' + } + ] + } + }, + timestamp: true, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; -describe('NGSI-v2 - Static attributes test', function() { - var values = [ +describe('NGSI-v2 - Static attributes test', function () { + const values = [ { name: 'state', type: 'boolean', @@ -96,52 +96,55 @@ describe('NGSI-v2 - Static attributes test', function() { } ]; - beforeEach(function() { + beforeEach(function () { logger.setLevel('FATAL'); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); }); - describe('When information from a device with multiple static attributes and metadata is sent', function() { - beforeEach(function(done) { + describe('When information from a device with multiple static attributes and metadata is sent', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v2/entities/light1/attrs') - .query({type: 'Light'}) + .query({ type: 'Light' }) .times(4) .reply(204) - .post('/v2/entities/light1/attrs', function(body) { - var metadatas = 0; - for (var i in body) { + .post('/v2/entities/light1/attrs', function (body) { + let metadatas = 0; + for (const i in body) { if (body[i].metadata) { metadatas += Object.keys(body[i].metadata).length; } } return metadatas === Object.keys(body).length - 1; }) - .query({type: 'Light'}) + .query({ type: 'Light' }) .reply(204); iotAgentLib.activate(iotAgentConfig, done); }); - it('should send a single TimeInstant per attribute', function(done) { - async.series([ - async.apply(iotAgentLib.update, 'light1', 'Light', '', values), - async.apply(iotAgentLib.update, 'light1', 'Light', '', values), - async.apply(iotAgentLib.update, 'light1', 'Light', '', values), - async.apply(iotAgentLib.update, 'light1', 'Light', '', values), - async.apply(iotAgentLib.update, 'light1', 'Light', '', values) - ], function(error, results) { - should.not.exist(error); - contextBrokerMock.done(); - done(); - }); + it('should send a single TimeInstant per attribute', function (done) { + async.series( + [ + async.apply(iotAgentLib.update, 'light1', 'Light', '', values), + async.apply(iotAgentLib.update, 'light1', 'Light', '', values), + async.apply(iotAgentLib.update, 'light1', 'Light', '', values), + async.apply(iotAgentLib.update, 'light1', 'Light', '', values), + async.apply(iotAgentLib.update, 'light1', 'Light', '', values) + ], + function (error, results) { + should.not.exist(error); + contextBrokerMock.done(); + done(); + } + ); }); }); }); diff --git a/test/unit/ngsiv2/ngsiService/subscriptions-test.js b/test/unit/ngsiv2/ngsiService/subscriptions-test.js index 320318f37..b8e7749be 100644 --- a/test/unit/ngsiv2/ngsiService/subscriptions-test.js +++ b/test/unit/ngsiv2/ngsiService/subscriptions-test.js @@ -22,33 +22,34 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - should = require('should'), - request = require('request'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041 - }, - types: {}, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' - }; - -describe('NGSI-v2 - Subscription tests', function() { - beforeEach(function(done) { - var optionsProvision = { + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const request = require('request'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041 + }, + types: {}, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; + +describe('NGSI-v2 - Subscription tests', function () { + beforeEach(function (done) { + const optionsProvision = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), @@ -60,43 +61,49 @@ describe('NGSI-v2 - Subscription tests', function() { nock.cleanAll(); - iotAgentLib.activate(iotAgentConfig, function() { + iotAgentLib.activate(iotAgentConfig, function () { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', - utils.readExampleFile('./test/unit/ngsiv2/examples/' + - 'contextRequests/createMinimumProvisionedDevice.json')) + .post( + '/v2/entities?options=upsert', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/createMinimumProvisionedDevice.json' + ) + ) .reply(204); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/subscriptions', utils.readExampleFile('./test/unit/ngsiv2/examples' + - '/subscriptionRequests/simpleSubscriptionRequest.json')) - .reply(201, null, {'Location': '/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8'}); - - iotAgentLib.clearAll(function() { - request(optionsProvision, function(error, result, body) { + .post( + '/v2/subscriptions', + utils.readExampleFile( + './test/unit/ngsiv2/examples/subscriptionRequests/simpleSubscriptionRequest.json' + ) + ) + .reply(201, null, { Location: '/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8' }); + + iotAgentLib.clearAll(function () { + request(optionsProvision, function (error, result, body) { done(); }); }); }); }); - afterEach(function(done) { + afterEach(function (done) { nock.cleanAll(); iotAgentLib.setNotificationHandler(); - iotAgentLib.clearAll(function() { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When a client invokes the subscribe() function for device', function() { - it('should send the appropriate request to the Context Broker', function(done) { - iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function(error, device) { - - iotAgentLib.subscribe(device, ['attr_name'], null, function(error) { + describe('When a client invokes the subscribe() function for device', function () { + it('should send the appropriate request to the Context Broker', function (done) { + iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function (error, device) { + iotAgentLib.subscribe(device, ['attr_name'], null, function (error) { should.not.exist(error); contextBrokerMock.done(); @@ -105,10 +112,10 @@ describe('NGSI-v2 - Subscription tests', function() { }); }); }); - it('should store the subscription ID in the Device Registry', function(done) { - iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function(error, device) { - iotAgentLib.subscribe(device, ['attr_name'], null, function(error) { - iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function(error, device) { + it('should store the subscription ID in the Device Registry', function (done) { + iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function (error, device) { + iotAgentLib.subscribe(device, ['attr_name'], null, function (error) { + iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function (error, device) { should.not.exist(error); should.exist(device); should.exist(device.subscriptions); @@ -121,8 +128,8 @@ describe('NGSI-v2 - Subscription tests', function() { }); }); }); - describe('When a client invokes the unsubscribe() function for an entity', function() { - beforeEach(function(done) { + describe('When a client invokes the unsubscribe() function for an entity', function () { + beforeEach(function (done) { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') @@ -131,12 +138,11 @@ describe('NGSI-v2 - Subscription tests', function() { done(); }); - it('should delete the subscription from the CB', function(done) { - iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function(error, device) { - iotAgentLib.subscribe(device, ['attr_name'], null, function(error) { - iotAgentLib.unsubscribe(device, '51c0ac9ed714fb3b37d7d5a8', function(error) { - iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function(error, device) { - + it('should delete the subscription from the CB', function (done) { + iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function (error, device) { + iotAgentLib.subscribe(device, ['attr_name'], null, function (error) { + iotAgentLib.unsubscribe(device, '51c0ac9ed714fb3b37d7d5a8', function (error) { + iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function (error, device) { contextBrokerMock.done(); done(); }); @@ -144,11 +150,11 @@ describe('NGSI-v2 - Subscription tests', function() { }); }); }); - it('should remove the id from the subscriptions array', function(done) { - iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function(error, device) { - iotAgentLib.subscribe(device, ['attr_name'], null, function(error) { - iotAgentLib.unsubscribe(device, '51c0ac9ed714fb3b37d7d5a8', function(error) { - iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function(error, device) { + it('should remove the id from the subscriptions array', function (done) { + iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function (error, device) { + iotAgentLib.subscribe(device, ['attr_name'], null, function (error) { + iotAgentLib.unsubscribe(device, '51c0ac9ed714fb3b37d7d5a8', function (error) { + iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function (error, device) { should.not.exist(error); should.exist(device); should.exist(device.subscriptions); @@ -160,8 +166,8 @@ describe('NGSI-v2 - Subscription tests', function() { }); }); }); - describe('When a client removes a device from the registry', function() { - beforeEach(function(done) { + describe('When a client removes a device from the registry', function () { + beforeEach(function (done) { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') @@ -171,10 +177,10 @@ describe('NGSI-v2 - Subscription tests', function() { done(); }); - it('should delete the subscription from the CB', function(done) { - iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function(error, device) { - iotAgentLib.subscribe(device, ['attr_name'], null, function(error) { - iotAgentLib.unregister(device.id, 'smartGondor', '/gardens', function(error) { + it('should delete the subscription from the CB', function (done) { + iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function (error, device) { + iotAgentLib.subscribe(device, ['attr_name'], null, function (error) { + iotAgentLib.unregister(device.id, 'smartGondor', '/gardens', function (error) { contextBrokerMock.done(); done(); }); @@ -182,28 +188,26 @@ describe('NGSI-v2 - Subscription tests', function() { }); }); }); - describe('When a new notification comes to the IoTAgent', function() { - beforeEach(function(done) { - iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function(error, device) { - iotAgentLib.subscribe(device, ['attr_name'], null, function(error) { + describe('When a new notification comes to the IoTAgent', function () { + beforeEach(function (done) { + iotAgentLib.getDevice('MicroLight1', 'smartGondor', '/gardens', function (error, device) { + iotAgentLib.subscribe(device, ['attr_name'], null, function (error) { done(); }); }); }); - it('should invoke the user defined callback', function(done) { - var notificationOptions = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', - method: 'POST', - json: utils.readExampleFile('./test/unit/ngsiv2/examples/subscriptionRequests' + - '/simpleNotification.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - - executedHandler = false; + it('should invoke the user defined callback', function (done) { + const notificationOptions = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', + method: 'POST', + json: utils.readExampleFile('./test/unit/ngsiv2/examples/subscriptionRequests/simpleNotification.json'), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + let executedHandler = false; function mockedHandler(device, notification, callback) { executedHandler = true; @@ -212,27 +216,26 @@ describe('NGSI-v2 - Subscription tests', function() { iotAgentLib.setNotificationHandler(mockedHandler); - request(notificationOptions, function(error, response, body) { + request(notificationOptions, function (error, response, body) { should.not.exist(error); executedHandler.should.equal(true); done(); }); }); - it('should invoke all the notification middlewares before the user defined callback', function(done) { - var notificationOptions = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', - method: 'POST', - json: utils.readExampleFile('./test/unit/ngsiv2/examples/subscriptionRequests' + - '/simpleNotification.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - executedMiddlewares = false, - executedHandler = false, - modifiedData = false; + it('should invoke all the notification middlewares before the user defined callback', function (done) { + const notificationOptions = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', + method: 'POST', + json: utils.readExampleFile('./test/unit/ngsiv2/examples/subscriptionRequests/simpleNotification.json'), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + let executedMiddlewares = false; + let executedHandler = false; + let modifiedData = false; function mockedHandler(device, notification, callback) { executedHandler = true; @@ -254,7 +257,7 @@ describe('NGSI-v2 - Subscription tests', function() { iotAgentLib.addNotificationMiddleware(mockedMiddleware); iotAgentLib.setNotificationHandler(mockedHandler); - request(notificationOptions, function(error, response, body) { + request(notificationOptions, function (error, response, body) { should.not.exist(error); executedHandler.should.equal(true); executedMiddlewares.should.equal(true); @@ -262,22 +265,27 @@ describe('NGSI-v2 - Subscription tests', function() { done(); }); }); - it('should get the correspondent device information', function(done) { - var notificationOptions = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', - method: 'POST', - json: utils.readExampleFile('./test/unit/ngsiv2/examples/subscriptionRequests/' + - 'simpleNotification.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - rightFields = false; + it('should get the correspondent device information', function (done) { + const notificationOptions = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', + method: 'POST', + json: utils.readExampleFile('./test/unit/ngsiv2/examples/subscriptionRequests/simpleNotification.json'), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + let rightFields = false; function mockedHandler(device, data, callback) { - if (device && device.id === 'MicroLight1' && device.name === 'FirstMicroLight' && - data && data.length === 1 && data[0].name === 'attr_name') { + if ( + device && + device.id === 'MicroLight1' && + device.name === 'FirstMicroLight' && + data && + data.length === 1 && + data[0].name === 'attr_name' + ) { rightFields = true; } @@ -286,7 +294,7 @@ describe('NGSI-v2 - Subscription tests', function() { iotAgentLib.setNotificationHandler(mockedHandler); - request(notificationOptions, function(error, response, body) { + request(notificationOptions, function (error, response, body) { should.not.exist(error); rightFields.should.equal(true); @@ -294,20 +302,18 @@ describe('NGSI-v2 - Subscription tests', function() { }); }); }); - describe('When a wrong notification arrives at the IOTA', function() { - it('should not call the handler', function(done) { - var notificationOptions = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', - method: 'POST', - json: utils.readExampleFile('./test/unit/ngsiv2/examples/subscriptionRequests/' + - 'errorNotification.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - - executedHandler = false; + describe('When a wrong notification arrives at the IOTA', function () { + it('should not call the handler', function (done) { + const notificationOptions = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', + method: 'POST', + json: utils.readExampleFile('./test/unit/ngsiv2/examples/subscriptionRequests/errorNotification.json'), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + let executedHandler = false; function mockedHandler(device, notification, callback) { executedHandler = true; @@ -316,7 +322,7 @@ describe('NGSI-v2 - Subscription tests', function() { iotAgentLib.setNotificationHandler(mockedHandler); - request(notificationOptions, function(error, response, body) { + request(notificationOptions, function (error, response, body) { should.not.exist(error); executedHandler.should.equal(false); diff --git a/test/unit/ngsiv2/plugins/alias-plugin_test.js b/test/unit/ngsiv2/plugins/alias-plugin_test.js index 0a26c44dd..1bd3d7616 100644 --- a/test/unit/ngsiv2/plugins/alias-plugin_test.js +++ b/test/unit/ngsiv2/plugins/alias-plugin_test.js @@ -22,103 +22,99 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; /* jshint camelcase: false */ -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - autocast: true, - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - object_id: 't', - name: 'temperature', - type: 'Number', - metadata: { type: 'Property', value:'CEL'} - - } - ], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Number', - metadata: { type: 'Property', value:'Hgmm'} - - }, - { - object_id: 'l', - name: 'luminance', - type: 'Number', - metadata: { type: 'Property', value:'CAL'} - - }, - { - object_id: 'ut', - name: 'unix_timestamp', - type: 'Number' - }, - { - object_id: 'ap', - name: 'active_power', - type: 'Number' - }, - { - object_id: 'ap', - name: 'active_power', - type: 'Number' - }, - { - object_id: 's', - name: 'status', - type: 'Boolean' - }, - { - object_id: 'al', - name: 'keep_alive', - type: 'None' - }, - { - object_id: 'ta', - name: 'tags', - type: 'Array' - }, - { - object_id: 'c', - name: 'configuration', - type: 'Object' - } - ] - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' - }; - -describe('NGSI-v2 - Attribute alias plugin', function() { - beforeEach(function(done) { +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + autocast: true, + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + object_id: 't', + name: 'temperature', + type: 'Number', + metadata: { type: 'Property', value: 'CEL' } + } + ], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Number', + metadata: { type: 'Property', value: 'Hgmm' } + }, + { + object_id: 'l', + name: 'luminance', + type: 'Number', + metadata: { type: 'Property', value: 'CAL' } + }, + { + object_id: 'ut', + name: 'unix_timestamp', + type: 'Number' + }, + { + object_id: 'ap', + name: 'active_power', + type: 'Number' + }, + { + object_id: 'ap', + name: 'active_power', + type: 'Number' + }, + { + object_id: 's', + name: 'status', + type: 'Boolean' + }, + { + object_id: 'al', + name: 'keep_alive', + type: 'None' + }, + { + object_id: 'ta', + name: 'tags', + type: 'Array' + }, + { + object_id: 'c', + name: 'configuration', + type: 'Object' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; + +describe('NGSI-v2 - Attribute alias plugin', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.attributeAlias.update); iotAgentLib.addQueryMiddleware(iotAgentLib.dataPlugins.attributeAlias.query); done(); @@ -126,13 +122,13 @@ describe('NGSI-v2 - Attribute alias plugin', function() { }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When an update comes for attributes with aliases', function() { - var values = [ + describe('When an update comes for attributes with aliases', function () { + const values = [ { name: 't', type: 'centigrades', @@ -145,29 +141,30 @@ describe('NGSI-v2 - Attribute alias plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextAliasPlugin1.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAliasPlugin1.json') + ) + .query({ type: 'Light' }) .reply(204); }); - it('should rename the attributes as expected by the alias mappings' + - 'and cast values to JSON native types', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should rename the attributes as expected by the alias mappings and cast values to JSON native types', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - describe('When an update comes for attributes with aliases and a different type', function() { - var values = [ + describe('When an update comes for attributes with aliases and a different type', function () { + const values = [ { name: 'l', type: 'lums', @@ -175,29 +172,30 @@ describe('NGSI-v2 - Attribute alias plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextAliasPlugin2.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAliasPlugin2.json') + ) + .query({ type: 'Light' }) .reply(204); }); - it('should rename the attributes as expected by the alias mappings' + - 'and cast values to JSON native types', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should rename the attributes as expected by the alias mappings and cast values to JSON native types', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - describe('When an update comes for attributes with aliases and integer type', function() { - var values = [ + describe('When an update comes for attributes with aliases and integer type', function () { + const values = [ { name: 'ut', type: 'Number', @@ -205,20 +203,22 @@ describe('NGSI-v2 - Attribute alias plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextAliasPlugin3.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAliasPlugin3.json') + ) + .query({ type: 'Light' }) .reply(204); }); - it('should rename the attributes as expected by the mappings', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should rename the attributes as expected by the mappings', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -226,8 +226,8 @@ describe('NGSI-v2 - Attribute alias plugin', function() { }); }); - describe('When an update comes for attributes with aliases and integer type.', function() { - var values = [ + describe('When an update comes for attributes with aliases and integer type.', function () { + const values = [ { name: 'ut', type: 'Number', @@ -235,21 +235,22 @@ describe('NGSI-v2 - Attribute alias plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextAliasPlugin3.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAliasPlugin3.json') + ) + .query({ type: 'Light' }) .reply(204); }); - it('should rename the attributes as expected by the alias mappings' + - 'and cast values to JSON native types', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should rename the attributes as expected by the alias mappings and cast values to JSON native types', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -257,8 +258,8 @@ describe('NGSI-v2 - Attribute alias plugin', function() { }); }); - describe('When an update comes for attributes with aliases and float type', function() { - var values = [ + describe('When an update comes for attributes with aliases and float type', function () { + const values = [ { name: 'ap', type: 'Number', @@ -266,21 +267,22 @@ describe('NGSI-v2 - Attribute alias plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextAliasPlugin4.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAliasPlugin4.json') + ) + .query({ type: 'Light' }) .reply(204); }); - it('should rename the attributes as expected by the alias mappings' + - 'and cast values to JSON native types', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should rename the attributes as expected by the alias mappings and cast values to JSON native types', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -288,8 +290,8 @@ describe('NGSI-v2 - Attribute alias plugin', function() { }); }); - describe('When an update comes for attributes with aliases and boolean type', function() { - var values = [ + describe('When an update comes for attributes with aliases and boolean type', function () { + const values = [ { name: 's', type: 'Boolean', @@ -297,21 +299,22 @@ describe('NGSI-v2 - Attribute alias plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextAliasPlugin5.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAliasPlugin5.json') + ) + .query({ type: 'Light' }) .reply(204); }); - it('should rename the attributes as expected by the alias mappings' + - 'and cast values to JSON native types', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should rename the attributes as expected by the alias mappings and cast values to JSON native types', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -319,8 +322,8 @@ describe('NGSI-v2 - Attribute alias plugin', function() { }); }); - describe('When an update comes for attributes with aliases and None type', function() { - var values = [ + describe('When an update comes for attributes with aliases and None type', function () { + const values = [ { name: 'al', type: 'None', @@ -328,21 +331,22 @@ describe('NGSI-v2 - Attribute alias plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextAliasPlugin6.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAliasPlugin6.json') + ) + .query({ type: 'Light' }) .reply(204); }); - it('should rename the attributes as expected by the alias mappings' + - 'and cast values to JSON native types', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should rename the attributes as expected by the alias mappings and cast values to JSON native types', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -350,8 +354,8 @@ describe('NGSI-v2 - Attribute alias plugin', function() { }); }); - describe('When an update comes for attributes with aliases and Array type', function() { - var values = [ + describe('When an update comes for attributes with aliases and Array type', function () { + const values = [ { name: 'ta', type: 'Array', @@ -359,21 +363,22 @@ describe('NGSI-v2 - Attribute alias plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextAliasPlugin7.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAliasPlugin7.json') + ) + .query({ type: 'Light' }) .reply(204); }); - it('should rename the attributes as expected by the alias mappings' + - 'and cast values to JSON native types', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should rename the attributes as expected by the alias mappings and cast values to JSON native types', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -381,8 +386,8 @@ describe('NGSI-v2 - Attribute alias plugin', function() { }); }); - describe('When an update comes for attributes with aliases and Object type', function() { - var values = [ + describe('When an update comes for attributes with aliases and Object type', function () { + const values = [ { name: 'c', type: 'Object', @@ -390,21 +395,22 @@ describe('NGSI-v2 - Attribute alias plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextAliasPlugin8.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAliasPlugin8.json') + ) + .query({ type: 'Light' }) .reply(204); }); - it('should rename the attributes as expected by the alias mappings' + - 'and cast values to JSON native types', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should rename the attributes as expected by the alias mappings and cast values to JSON native types', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -412,9 +418,8 @@ describe('NGSI-v2 - Attribute alias plugin', function() { }); }); - - describe('When an update comes for attributes with aliases and Object type, but value is String', function() { - var values = [ + describe('When an update comes for attributes with aliases and Object type, but value is String', function () { + const values = [ { name: 'c', type: 'Object', @@ -422,21 +427,22 @@ describe('NGSI-v2 - Attribute alias plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextAliasPlugin9.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateContextAliasPlugin9.json') + ) + .query({ type: 'Light' }) .reply(204); }); - it('should rename the attributes as expected by the alias mappings' + - 'and cast values to JSON native types', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should rename the attributes as expected by the alias mappings and cast values to JSON native types', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); diff --git a/test/unit/ngsiv2/plugins/bidirectional-plugin_test.js b/test/unit/ngsiv2/plugins/bidirectional-plugin_test.js index fa5f985b0..b3569e975 100644 --- a/test/unit/ngsiv2/plugins/bidirectional-plugin_test.js +++ b/test/unit/ngsiv2/plugins/bidirectional-plugin_test.js @@ -23,85 +23,89 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - request = require('request'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041 - }, - types: { - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' - }; - -describe('NGSI-v2 - Bidirectional data plugin', function() { - var options = { +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +const request = require('request'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041 + }, + types: {}, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; + +describe('NGSI-v2 - Bidirectional data plugin', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', - json: - utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionBidirectionalDevice.json'), + json: utils.readExampleFile( + './test/unit/examples/deviceProvisioningRequests/provisionBidirectionalDevice.json' + ), headers: { 'fiware-service': 'smartGondor', 'fiware-servicepath': '/gardens' } }; - beforeEach(function(done) { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { - iotAgentLib.addDeviceProvisionMiddleware( - iotAgentLib.dataPlugins.bidirectionalData.deviceProvision); + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { + iotAgentLib.addDeviceProvisionMiddleware(iotAgentLib.dataPlugins.bidirectionalData.deviceProvision); iotAgentLib.addConfigurationProvisionMiddleware( - iotAgentLib.dataPlugins.bidirectionalData.groupProvision); - iotAgentLib.addNotificationMiddleware( - iotAgentLib.dataPlugins.bidirectionalData.notification); + iotAgentLib.dataPlugins.bidirectionalData.groupProvision + ); + iotAgentLib.addNotificationMiddleware(iotAgentLib.dataPlugins.bidirectionalData.notification); done(); }); }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When a new provisioning request arrives to the IoTA with bidirectionality', function() { - beforeEach(function() { + describe('When a new provisioning request arrives to the IoTA with bidirectionality', function () { + beforeEach(function () { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/subscriptions', utils.readExampleFile( - './test/unit/ngsiv2/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json')) - .reply(201, null, {'Location': '/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8'}); + .post( + '/v2/subscriptions', + utils.readExampleFile( + './test/unit/ngsiv2/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json' + ) + ) + .reply(201, null, { Location: '/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/createBidirectionalDevice.json')) + .post( + '/v2/entities?options=upsert', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/createBidirectionalDevice.json') + ) .reply(204); - }); - it('should subscribe to the modification of the combined attribute with all the variables', function(done) { - request(options, function(error, response, body) { + it('should subscribe to the modification of the combined attribute with all the variables', function (done) { + request(options, function (error, response, body) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -109,8 +113,8 @@ describe('NGSI-v2 - Bidirectional data plugin', function() { }); }); - describe('When a device with bidirectionality subscriptions is removed', function() { - var deleteRequest = { + describe('When a device with bidirectionality subscriptions is removed', function () { + const deleteRequest = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', method: 'DELETE', headers: { @@ -119,19 +123,25 @@ describe('NGSI-v2 - Bidirectional data plugin', function() { } }; - beforeEach(function() { + beforeEach(function () { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/subscriptions', utils.readExampleFile( - './test/unit/ngsiv2/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json')) - .reply(201, null, {'Location': '/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8'}); + .post( + '/v2/subscriptions', + utils.readExampleFile( + './test/unit/ngsiv2/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json' + ) + ) + .reply(201, null, { Location: '/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/createBidirectionalDevice.json')) + .post( + '/v2/entities?options=upsert', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/createBidirectionalDevice.json') + ) .reply(204); contextBrokerMock @@ -141,9 +151,9 @@ describe('NGSI-v2 - Bidirectional data plugin', function() { .reply(204); }); - it('should remove its subscriptions from the Context Broker', function(done) { - request(options, function(error, response, body) { - request(deleteRequest, function(error, response, body) { + it('should remove its subscriptions from the Context Broker', function (done) { + request(options, function (error, response, body) { + request(deleteRequest, function (error, response, body) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -152,40 +162,47 @@ describe('NGSI-v2 - Bidirectional data plugin', function() { }); }); - describe('When a notification arrives for a bidirectional attribute', function() { - var notificationOptions = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', - method: 'POST', - json: utils.readExampleFile('./test/unit/ngsiv2/examples/subscriptionRequests/' + - 'bidirectionalNotification.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - executedHandler = false; + describe('When a notification arrives for a bidirectional attribute', function () { + const notificationOptions = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', + method: 'POST', + json: utils.readExampleFile( + './test/unit/ngsiv2/examples/subscriptionRequests/bidirectionalNotification.json' + ), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + let executedHandler = false; - beforeEach(function() { + beforeEach(function () { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/subscriptions', utils.readExampleFile( - './test/unit/ngsiv2/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json')) - .reply(201, null, {'Location': '/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8'}); + .post( + '/v2/subscriptions', + utils.readExampleFile( + './test/unit/ngsiv2/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json' + ) + ) + .reply(201, null, { Location: '/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/createBidirectionalDevice.json')) + .post( + '/v2/entities?options=upsert', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/createBidirectionalDevice.json') + ) .reply(204); }); - afterEach(function() { + afterEach(function () { iotAgentLib.setNotificationHandler(); }); - it('should execute the original handler', function(done) { + it('should execute the original handler', function (done) { function mockedHandler(device, notification, callback) { executedHandler = true; callback(); @@ -193,8 +210,8 @@ describe('NGSI-v2 - Bidirectional data plugin', function() { iotAgentLib.setNotificationHandler(mockedHandler); - request(options, function(error, response, body) { - request(notificationOptions, function(error, response, body) { + request(options, function (error, response, body) { + request(notificationOptions, function (error, response, body) { executedHandler.should.equal(true); contextBrokerMock.done(); done(); @@ -202,7 +219,7 @@ describe('NGSI-v2 - Bidirectional data plugin', function() { }); }); - it('should return a 200 OK', function(done) { + it('should return a 200 OK', function (done) { function mockedHandler(device, notification, callback) { executedHandler = true; callback(); @@ -210,8 +227,8 @@ describe('NGSI-v2 - Bidirectional data plugin', function() { iotAgentLib.setNotificationHandler(mockedHandler); - request(options, function(error, response, body) { - request(notificationOptions, function(error, response, body) { + request(options, function (error, response, body) { + request(notificationOptions, function (error, response, body) { response.statusCode.should.equal(200); contextBrokerMock.done(); done(); @@ -219,14 +236,14 @@ describe('NGSI-v2 - Bidirectional data plugin', function() { }); }); - it('should return the transformed values', function(done) { - var transformedHandler = false; + it('should return the transformed values', function (done) { + let transformedHandler = false; function mockedHandler(device, values, callback) { - var latitudeFound = false, - longitudeFound = false; + let latitudeFound = false; + let longitudeFound = false; - for (var i = 0; i < values.length; i++) { + for (let i = 0; i < values.length; i++) { if (values[i].name === 'latitude' && values[i].type === 'string' && values[i].value === '-9.6') { latitudeFound = true; } @@ -236,14 +253,14 @@ describe('NGSI-v2 - Bidirectional data plugin', function() { } } - transformedHandler = (values.length >= 2 && longitudeFound && latitudeFound); + transformedHandler = values.length >= 2 && longitudeFound && latitudeFound; callback(); } iotAgentLib.setNotificationHandler(mockedHandler); - request(options, function(error, response, body) { - request(notificationOptions, function(error, response, body) { + request(options, function (error, response, body) { + request(notificationOptions, function (error, response, body) { contextBrokerMock.done(); transformedHandler.should.equal(true); done(); @@ -252,47 +269,52 @@ describe('NGSI-v2 - Bidirectional data plugin', function() { }); }); - describe('When a new Group provisioning request arrives with bidirectional attributes', function() { - var provisionGroup = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/services', - method: 'POST', - json: - utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/bidirectionalGroup.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - provisionDevice = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionDeviceBidirectionalGroup.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }; + describe('When a new Group provisioning request arrives with bidirectional attributes', function () { + const provisionGroup = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/services', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/bidirectionalGroup.json'), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + const provisionDevice = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile( + './test/unit/examples/deviceProvisioningRequests/provisionDeviceBidirectionalGroup.json' + ), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; - beforeEach(function() { + beforeEach(function () { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/subscriptions', utils.readExampleFile( - './test/unit/ngsiv2/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json')) - .reply(201, null, {'Location': '/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8'}); + .post( + '/v2/subscriptions', + utils.readExampleFile( + './test/unit/ngsiv2/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json' + ) + ) + .reply(201, null, { Location: '/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/createBidirectionalDevice.json')) + .post( + '/v2/entities?options=upsert', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/createBidirectionalDevice.json') + ) .reply(204); - }); - it('should subscribe to the modification of the combined attribute with all the variables', function(done) { - request(provisionGroup, function(error, response, body) { - request(provisionDevice, function(error, response, body) { + it('should subscribe to the modification of the combined attribute with all the variables', function (done) { + request(provisionGroup, function (error, response, body) { + request(provisionDevice, function (error, response, body) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -301,66 +323,73 @@ describe('NGSI-v2 - Bidirectional data plugin', function() { }); }); - describe('When a notification arrives for a bidirectional attribute in a Configuration Group', function() { - var provisionGroup = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/services', - method: 'POST', - json: - utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/bidirectionalGroup.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - notificationOptions = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', - method: 'POST', - json: utils.readExampleFile('./test/unit/ngsiv2/examples/subscriptionRequests/' + - 'bidirectionalNotification.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - provisionDevice = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionDeviceBidirectionalGroup.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }; + describe('When a notification arrives for a bidirectional attribute in a Configuration Group', function () { + const provisionGroup = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/services', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/bidirectionalGroup.json'), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + const notificationOptions = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', + method: 'POST', + json: utils.readExampleFile( + './test/unit/ngsiv2/examples/subscriptionRequests/bidirectionalNotification.json' + ), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + const provisionDevice = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile( + './test/unit/examples/deviceProvisioningRequests/provisionDeviceBidirectionalGroup.json' + ), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; - beforeEach(function() { + beforeEach(function () { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/subscriptions', utils.readExampleFile( - './test/unit/ngsiv2/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json')) - .reply(201, null, {'Location': '/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8'}); + .post( + '/v2/subscriptions', + utils.readExampleFile( + './test/unit/ngsiv2/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json' + ) + ) + .reply(201, null, { Location: '/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/createBidirectionalDevice.json')) + .post( + '/v2/entities?options=upsert', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/createBidirectionalDevice.json') + ) .reply(204); }); - afterEach(function() { + afterEach(function () { iotAgentLib.setNotificationHandler(); }); - it('should return the transformed values', function(done) { - var transformedHandler = false; + it('should return the transformed values', function (done) { + let transformedHandler = false; function mockedHandler(device, values, callback) { - var latitudeFound = false, - longitudeFound = false; + let latitudeFound = false; + let longitudeFound = false; - for (var i = 0; i < values.length; i++) { + for (let i = 0; i < values.length; i++) { if (values[i].name === 'latitude' && values[i].type === 'string' && values[i].value === '-9.6') { latitudeFound = true; } @@ -370,15 +399,15 @@ describe('NGSI-v2 - Bidirectional data plugin', function() { } } - transformedHandler = (values.length >= 2 && longitudeFound && latitudeFound); + transformedHandler = values.length >= 2 && longitudeFound && latitudeFound; callback(); } iotAgentLib.setNotificationHandler(mockedHandler); - request(provisionGroup, function(error, response, body) { - request(provisionDevice, function(error, response, body) { - request(notificationOptions, function(error, response, body) { + request(provisionGroup, function (error, response, body) { + request(provisionDevice, function (error, response, body) { + request(notificationOptions, function (error, response, body) { transformedHandler.should.equal(true); done(); }); @@ -388,66 +417,70 @@ describe('NGSI-v2 - Bidirectional data plugin', function() { }); }); -describe('NGSI-v2 - Bidirectional data plugin and CB is defined using environment variables', function() { - var options = { +describe('NGSI-v2 - Bidirectional data plugin and CB is defined using environment variables', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', - json: - utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionBidirectionalDevice.json'), + json: utils.readExampleFile( + './test/unit/examples/deviceProvisioningRequests/provisionBidirectionalDevice.json' + ), headers: { 'fiware-service': 'smartGondor', 'fiware-servicepath': '/gardens' } }; - beforeEach(function(done) { + beforeEach(function (done) { logger.setLevel('FATAL'); process.env.IOTA_CB_HOST = 'cbhost'; - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { - iotAgentLib.addDeviceProvisionMiddleware( - iotAgentLib.dataPlugins.bidirectionalData.deviceProvision); + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { + iotAgentLib.addDeviceProvisionMiddleware(iotAgentLib.dataPlugins.bidirectionalData.deviceProvision); iotAgentLib.addConfigurationProvisionMiddleware( - iotAgentLib.dataPlugins.bidirectionalData.groupProvision); - iotAgentLib.addNotificationMiddleware( - iotAgentLib.dataPlugins.bidirectionalData.notification); + iotAgentLib.dataPlugins.bidirectionalData.groupProvision + ); + iotAgentLib.addNotificationMiddleware(iotAgentLib.dataPlugins.bidirectionalData.notification); done(); }); }); }); - afterEach(function(done) { + afterEach(function (done) { process.env.IOTA_CB_HOST = ''; - iotAgentLib.clearAll(function() { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When a new provisioning request arrives to the IoTA with bidirectionality', function() { - beforeEach(function() { + describe('When a new provisioning request arrives to the IoTA with bidirectionality', function () { + beforeEach(function () { contextBrokerMock = nock('http://cbhost:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/subscriptions', utils.readExampleFile( - './test/unit/ngsiv2/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json')) - .reply(201, null, {'Location': '/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8'}); + .post( + '/v2/subscriptions', + utils.readExampleFile( + './test/unit/ngsiv2/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json' + ) + ) + .reply(201, null, { Location: '/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/createBidirectionalDevice.json')) + .post( + '/v2/entities?options=upsert', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/createBidirectionalDevice.json') + ) .reply(204); - }); - it('should subscribe to the modification of the combined attribute with all the variables', function(done) { - request(options, function(error, response, body) { + it('should subscribe to the modification of the combined attribute with all the variables', function (done) { + request(options, function (error, response, body) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - }); diff --git a/test/unit/ngsiv2/plugins/compress-timestamp-plugin_test.js b/test/unit/ngsiv2/plugins/compress-timestamp-plugin_test.js index 9a3ff883e..89fe36775 100644 --- a/test/unit/ngsiv2/plugins/compress-timestamp-plugin_test.js +++ b/test/unit/ngsiv2/plugins/compress-timestamp-plugin_test.js @@ -23,108 +23,105 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - server: { - port: 4041 + BrokenLight: { + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'BrokenLight': { - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'Termometer': { - type: 'Termometer', - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ] - }, - 'Humidity': { - type: 'Humidity', - cbHost: 'http://192.168.1.1:3024', - commands: [], - lazy: [], - active: [ - { - name: 'humidity', - type: 'percentage' - } - ] - }, - 'Motion': { - type: 'Motion', - commands: [], - lazy: [], - staticAttributes: [ - { - 'name': 'location', - 'type': 'Vector', - 'value': '(123,523)' - } - ], - active: [ - { - name: 'humidity', - type: 'percentage' - } - ] - } + Termometer: { + type: 'Termometer', + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [] }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' - }; - -describe('NGSI-v2 - Timestamp compression plugin', function() { - beforeEach(function(done) { + Humidity: { + type: 'Humidity', + cbHost: 'http://192.168.1.1:3024', + commands: [], + lazy: [], + active: [ + { + name: 'humidity', + type: 'percentage' + } + ] + }, + Motion: { + type: 'Motion', + commands: [], + lazy: [], + staticAttributes: [ + { + name: 'location', + type: 'Vector', + value: '(123,523)' + } + ], + active: [ + { + name: 'humidity', + type: 'percentage' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; + +describe('NGSI-v2 - Timestamp compression plugin', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.compressTimestamp.updateNgsi2); iotAgentLib.addQueryMiddleware(iotAgentLib.dataPlugins.compressTimestamp.queryNgsi2); done(); @@ -132,13 +129,13 @@ describe('NGSI-v2 - Timestamp compression plugin', function() { }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When an update comes with a timestamp through the plugin', function() { - var values = [ + describe('When an update comes with a timestamp through the plugin', function () { + const values = [ { name: 'state', type: 'Boolean', @@ -151,20 +148,24 @@ describe('NGSI-v2 - Timestamp compression plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextCompressTimestamp1.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextCompressTimestamp1.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - it('should return an entity with all its timestamps expanded to have separators', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should return an entity with all its timestamps expanded to have separators', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -172,19 +173,18 @@ describe('NGSI-v2 - Timestamp compression plugin', function() { }); }); - describe('When an update comes with a timestamp through the plugin with metadata.', function() { - var values = [ + describe('When an update comes with a timestamp through the plugin with metadata.', function () { + const values = [ { name: 'state', type: 'Boolean', value: true, metadata: { - TimeInstant: { + TimeInstant: { type: 'DateTime', value: '20071103T131805' } } - }, { name: 'TheTargetValue', @@ -193,20 +193,24 @@ describe('NGSI-v2 - Timestamp compression plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextCompressTimestamp2.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextCompressTimestamp2.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - it('should return an entity with all its timestamps expanded to have separators', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should return an entity with all its timestamps expanded to have separators', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -214,25 +218,26 @@ describe('NGSI-v2 - Timestamp compression plugin', function() { }); }); - describe('When a query comes for a timestamp through the plugin', function() { - var values = [ - 'state', - 'TheTargetValue' - ]; + describe('When a query comes for a timestamp through the plugin', function () { + const values = ['state', 'TheTargetValue']; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .get('/v2/entities/light1/attrs?attrs=state,TheTargetValue&type=Light') - .reply(200, utils.readExampleFile( - './test/unit/ngsiv2/examples/contextResponses/queryContextCompressTimestamp1Success.json')); + .reply( + 200, + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextResponses/queryContextCompressTimestamp1Success.json' + ) + ); }); - it('should return an entity with all its timestamps without separators (basic format)', function(done) { - iotAgentLib.query('light1', 'Light', '', values, function(error, response) { + it('should return an entity with all its timestamps without separators (basic format)', function (done) { + iotAgentLib.query('light1', 'Light', '', values, function (error, response) { should.not.exist(error); should.exist(response); should.exist(response.TheTargetValue); @@ -242,5 +247,4 @@ describe('NGSI-v2 - Timestamp compression plugin', function() { }); }); }); - }); diff --git a/test/unit/ngsiv2/plugins/event-plugin_test.js b/test/unit/ngsiv2/plugins/event-plugin_test.js index 0fe9a242d..f30565b5d 100644 --- a/test/unit/ngsiv2/plugins/event-plugin_test.js +++ b/test/unit/ngsiv2/plugins/event-plugin_test.js @@ -23,51 +23,49 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' - }; - -describe('NGSI-v2 - Event plugin', function() { - beforeEach(function(done) { +describe('NGSI-v2 - Event plugin', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.addEvents.update); iotAgentLib.addQueryMiddleware(iotAgentLib.dataPlugins.addEvents.query); done(); @@ -75,13 +73,13 @@ describe('NGSI-v2 - Event plugin', function() { }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When an update comes with an event to the plugin', function() { - var values = [ + describe('When an update comes with an event to the plugin', function () { + const values = [ { name: 'state', type: 'Boolean', @@ -94,23 +92,23 @@ describe('NGSI-v2 - Event plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', function(body) { - var dateRegex = /\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d.\d{3}Z/; + .post('/v2/entities/light1/attrs', function (body) { + const dateRegex = /\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d.\d{3}Z/; return body.activation.value.match(dateRegex); }) - .query({type: 'Light'}) + .query({ type: 'Light' }) .reply(204); }); - it('should return an entity with all its timestamps expanded to have separators', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should return an entity with all its timestamps expanded to have separators', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); diff --git a/test/unit/ngsiv2/plugins/multientity-plugin_test.js b/test/unit/ngsiv2/plugins/multientity-plugin_test.js index 3be0b0772..ddfc43192 100644 --- a/test/unit/ngsiv2/plugins/multientity-plugin_test.js +++ b/test/unit/ngsiv2/plugins/multientity-plugin_test.js @@ -22,218 +22,216 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -/* jshint camelcase: false */ - -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - moment = require('moment'), - timekeeper = require('timekeeper'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041 - }, - types: { - 'WeatherStation': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm' - }, - { - object_id: 'h', - name: 'humidity', - type: 'Percentage', - entity_name: 'Higro2000', - entity_type: 'Higrometer', - metadata:{ - unitCode:{ - type: 'Text', value : 'Hgmm' - } + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +const moment = require('moment'); +const timekeeper = require('timekeeper'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041 + }, + types: { + WeatherStation: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm' + }, + { + object_id: 'h', + name: 'humidity', + type: 'Percentage', + entity_name: 'Higro2000', + entity_type: 'Higrometer', + metadata: { + unitCode: { + type: 'Text', + value: 'Hgmm' } } - ] - }, - 'WeatherStation2': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm' - }, - { - object_id: 'h', - name: 'humidity', - type: 'Percentage', - entity_name: 'Higro2000', - } - ] - }, - 'WeatherStation3': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm' - }, - { - object_id: 'h', - name: 'humidity', - type: 'Percentage', - entity_name: 'Station Number ${@sn * 10}', - } - ] - }, - 'WeatherStation5': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm' - }, - { - object_id: 'h', - name: 'pressure', - type: 'Hgmm', - entity_name: 'Higro2000', - entity_type: 'Higrometer' - } - ] - }, - 'WeatherStation6': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm', - entity_name: 'Higro2002', - entity_type: 'Higrometer' - }, - { - object_id: 'h', - name: 'pressure', - type: 'Hgmm', - entity_name: 'Higro2000', - entity_type: 'Higrometer' - } - ] - }, - 'WeatherStation7': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm', - metadata: { - unitCode:{type: 'Text', value :'Hgmm'} - }, - entity_name: 'Higro2002', - entity_type: 'Higrometer' - }, - { - object_id: 'h', - name: 'pressure', - type: 'Hgmm', - entity_name: 'Higro2000', - entity_type: 'Higrometer' - } - ] - }, - 'Sensor001': { - commands: [], - type: 'Sensor', - lazy: [], - active: [ - { - type : 'number', - name : 'vol', - object_id : 'cont1', - entity_name : 'SO1', - entity_type : 'WM' - }, - { - type : 'number', - name : 'vol', - object_id : 'cont2', - entity_name : 'SO2', - entity_type : 'WM' - }, - { - type : 'number', - name : 'vol', - object_id : 'cont3', - entity_name : 'SO3', - entity_type : 'WM' - }, - { - type : 'number', - name : 'vol', - object_id : 'cont4', - entity_name : 'SO4', - entity_type : 'WM' + } + ] + }, + WeatherStation2: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm' + }, + { + object_id: 'h', + name: 'humidity', + type: 'Percentage', + entity_name: 'Higro2000' + } + ] + }, + WeatherStation3: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm' + }, + { + object_id: 'h', + name: 'humidity', + type: 'Percentage', + entity_name: 'Station Number ${@sn * 10}' + } + ] + }, + WeatherStation5: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm' + }, + { + object_id: 'h', + name: 'pressure', + type: 'Hgmm', + entity_name: 'Higro2000', + entity_type: 'Higrometer' + } + ] + }, + WeatherStation6: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm', + entity_name: 'Higro2002', + entity_type: 'Higrometer' + }, + { + object_id: 'h', + name: 'pressure', + type: 'Hgmm', + entity_name: 'Higro2000', + entity_type: 'Higrometer' + } + ] + }, + WeatherStation7: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm', + metadata: { + unitCode: { type: 'Text', value: 'Hgmm' } }, - { - type : 'number', - name : 'vol', - object_id : 'cont5', - entity_name : 'SO5', - entity_type : 'WM' - } - ] - - }, - 'SensorCommand':{ - commands: [ - { - name: 'PING', - type: 'command' - } - ], - type: 'SensorCommand', - lazy: [] - } - + entity_name: 'Higro2002', + entity_type: 'Higrometer' + }, + { + object_id: 'h', + name: 'pressure', + type: 'Hgmm', + entity_name: 'Higro2000', + entity_type: 'Higrometer' + } + ] }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' - }; - -describe('NGSI-v2 - Multi-entity plugin', function() { - beforeEach(function(done) { + Sensor001: { + commands: [], + type: 'Sensor', + lazy: [], + active: [ + { + type: 'number', + name: 'vol', + object_id: 'cont1', + entity_name: 'SO1', + entity_type: 'WM' + }, + { + type: 'number', + name: 'vol', + object_id: 'cont2', + entity_name: 'SO2', + entity_type: 'WM' + }, + { + type: 'number', + name: 'vol', + object_id: 'cont3', + entity_name: 'SO3', + entity_type: 'WM' + }, + { + type: 'number', + name: 'vol', + object_id: 'cont4', + entity_name: 'SO4', + entity_type: 'WM' + }, + { + type: 'number', + name: 'vol', + object_id: 'cont5', + entity_name: 'SO5', + entity_type: 'WM' + } + ] + }, + SensorCommand: { + commands: [ + { + name: 'PING', + type: 'command' + } + ], + type: 'SensorCommand', + lazy: [] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; + +describe('NGSI-v2 - Multi-entity plugin', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.attributeAlias.update); iotAgentLib.addQueryMiddleware(iotAgentLib.dataPlugins.attributeAlias.query); iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.multiEntity.update); @@ -242,14 +240,14 @@ describe('NGSI-v2 - Multi-entity plugin', function() { }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When an update comes for a multientity measurement', function() { - var values = [ + describe('When an update comes for a multientity measurement', function () { + const values = [ { name: 'p', type: 'centigrades', @@ -262,19 +260,23 @@ describe('NGSI-v2 - Multi-entity plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/op/update', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextMultientityPlugin1.json')) + .post( + '/v2/op/update', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextMultientityPlugin1.json' + ) + ) .reply(204); }); - it('should send two context elements, one for each entity', function(done) { - iotAgentLib.update('ws4', 'WeatherStation', '', values, function(error) { + it('should send two context elements, one for each entity', function (done) { + iotAgentLib.update('ws4', 'WeatherStation', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -282,8 +284,8 @@ describe('NGSI-v2 - Multi-entity plugin', function() { }); }); - describe('When an update comes for a multientity measurement with same attribute name', function() { - var values = [ + describe('When an update comes for a multientity measurement with same attribute name', function () { + const values = [ { name: 'h', type: 'Hgmm', @@ -291,19 +293,23 @@ describe('NGSI-v2 - Multi-entity plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/op/update', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextMultientityPlugin4.json')) + .post( + '/v2/op/update', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextMultientityPlugin4.json' + ) + ) .reply(204); }); - it('should send context elements', function(done) { - iotAgentLib.update('ws5', 'WeatherStation5', '', values, function(error) { + it('should send context elements', function (done) { + iotAgentLib.update('ws5', 'WeatherStation5', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -311,8 +317,8 @@ describe('NGSI-v2 - Multi-entity plugin', function() { }); }); - describe('When an update comes for a multientity multi measurement with same attribute name', function() { - var values = [ + describe('When an update comes for a multientity multi measurement with same attribute name', function () { + const values = [ { name: 'h', type: 'Hgmm', @@ -325,19 +331,23 @@ describe('NGSI-v2 - Multi-entity plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/op/update', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextMultientityPlugin5.json')) + .post( + '/v2/op/update', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextMultientityPlugin5.json' + ) + ) .reply(204); }); - it('should send context elements', function(done) { - iotAgentLib.update('ws6', 'WeatherStation6', '', values, function(error) { + it('should send context elements', function (done) { + iotAgentLib.update('ws6', 'WeatherStation6', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -346,8 +356,8 @@ describe('NGSI-v2 - Multi-entity plugin', function() { }); /* jshint maxlen: 200 */ - describe('When an update comes for a multientity multi measurement with metadata and the same attribute name', function() { - var values = [ + describe('When an update comes for a multientity multi measurement with metadata and the same attribute name', function () { + const values = [ { name: 'h', type: 'Hgmm', @@ -360,19 +370,23 @@ describe('NGSI-v2 - Multi-entity plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/op/update', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextMultientityPlugin8.json')) + .post( + '/v2/op/update', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextMultientityPlugin8.json' + ) + ) .reply(204); }); - it('should send context elements', function(done) { - iotAgentLib.update('ws7', 'WeatherStation7', '', values, function(error) { + it('should send context elements', function (done) { + iotAgentLib.update('ws7', 'WeatherStation7', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -380,9 +394,8 @@ describe('NGSI-v2 - Multi-entity plugin', function() { }); }); - - describe('When an update comes for a multientity defined with an expression', function() { - var values = [ + describe('When an update comes for a multientity defined with an expression', function () { + const values = [ { name: 'p', type: 'centigrades', @@ -400,19 +413,23 @@ describe('NGSI-v2 - Multi-entity plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/op/update', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextMultientityPlugin3.json')) + .post( + '/v2/op/update', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextMultientityPlugin3.json' + ) + ) .reply(204); }); - it('should send the update value to the resulting value of the expression', function(done) { - iotAgentLib.update('ws4', 'WeatherStation3', '', values, function(error) { + it('should send the update value to the resulting value of the expression', function (done) { + iotAgentLib.update('ws4', 'WeatherStation3', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -420,8 +437,8 @@ describe('NGSI-v2 - Multi-entity plugin', function() { }); }); - describe('When an update comes for a multientity measurement without type for one entity', function() { - var values = [ + describe('When an update comes for a multientity measurement without type for one entity', function () { + const values = [ { name: 'p', type: 'centigrades', @@ -434,19 +451,23 @@ describe('NGSI-v2 - Multi-entity plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/op/update', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextMultientityPlugin2.json')) + .post( + '/v2/op/update', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextMultientityPlugin2.json' + ) + ) .reply(204); }); - it('should use the device type as a default value', function(done) { - iotAgentLib.update('ws4', 'WeatherStation2', '', values, function(error) { + it('should use the device type as a default value', function (done) { + iotAgentLib.update('ws4', 'WeatherStation2', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -454,90 +475,103 @@ describe('NGSI-v2 - Multi-entity plugin', function() { }); }); - describe('When an update comes for a multientity measurement and there are attributes with' + - ' the same name but different alias and mapped to different CB entities', function() { - var values = [ - { - name: 'cont1', - type: 'number', - value: '38' - } - ]; - - beforeEach(function() { - nock.cleanAll(); - - contextBrokerMock = nock('http://192.168.1.1:1026') - .matchHeader('fiware-service', 'smartGondor') - .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/op/update', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextMultientityPlugin6.json')) - .reply(204); - }); + describe( + 'When an update comes for a multientity measurement and there are attributes with' + + ' the same name but different alias and mapped to different CB entities', + function () { + const values = [ + { + name: 'cont1', + type: 'number', + value: '38' + } + ]; - it('should update only the appropriate CB entity', function(done) { - iotAgentLib.update('Sensor', 'Sensor001', '', values, function(error) { - should.not.exist(error); - contextBrokerMock.done(); - done(); + beforeEach(function () { + nock.cleanAll(); + + contextBrokerMock = nock('http://192.168.1.1:1026') + .matchHeader('fiware-service', 'smartGondor') + .matchHeader('fiware-servicepath', 'gardens') + .post( + '/v2/op/update', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextMultientityPlugin6.json' + ) + ) + .reply(204); }); - }); - }); - - describe('When an update comes for a multientity multi measurement and there are attributes with' + - ' the same name but different alias and mapped to different CB entities', function() { - var values = [ - { - name: 'cont1', - type: 'number', - value: '38' - }, - { - name: 'cont2', - type: 'number', - value: '39' - }, - { - name: 'cont3', - type: 'number', - value: '40' - }, - { - name: 'cont5', - type: 'number', - value: '42' - } - ]; - beforeEach(function() { - nock.cleanAll(); + it('should update only the appropriate CB entity', function (done) { + iotAgentLib.update('Sensor', 'Sensor001', '', values, function (error) { + should.not.exist(error); + contextBrokerMock.done(); + done(); + }); + }); + } + ); + + describe( + 'When an update comes for a multientity multi measurement and there are attributes with' + + ' the same name but different alias and mapped to different CB entities', + function () { + const values = [ + { + name: 'cont1', + type: 'number', + value: '38' + }, + { + name: 'cont2', + type: 'number', + value: '39' + }, + { + name: 'cont3', + type: 'number', + value: '40' + }, + { + name: 'cont5', + type: 'number', + value: '42' + } + ]; - contextBrokerMock = nock('http://192.168.1.1:1026') - .matchHeader('fiware-service', 'smartGondor') - .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/op/update', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextMultientityPlugin7.json')) - .reply(204); - }); + beforeEach(function () { + nock.cleanAll(); + + contextBrokerMock = nock('http://192.168.1.1:1026') + .matchHeader('fiware-service', 'smartGondor') + .matchHeader('fiware-servicepath', 'gardens') + .post( + '/v2/op/update', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextMultientityPlugin7.json' + ) + ) + .reply(204); + }); - it('should update only the appropriate CB entity', function(done) { - iotAgentLib.update('Sensor', 'Sensor001', '', values, function(error) { - should.not.exist(error); - contextBrokerMock.done(); - done(); + it('should update only the appropriate CB entity', function (done) { + iotAgentLib.update('Sensor', 'Sensor001', '', values, function (error) { + should.not.exist(error); + contextBrokerMock.done(); + done(); + }); }); - }); - }); - + } + ); }); -describe('NGSI-v2 - Multi-entity plugin is executed before timestamp process plugin', function() { - beforeEach(function(done) { +describe('NGSI-v2 - Multi-entity plugin is executed before timestamp process plugin', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); iotAgentConfig.timestamp = true; - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.attributeAlias.update); iotAgentLib.addQueryMiddleware(iotAgentLib.dataPlugins.attributeAlias.query); iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.multiEntity.update); @@ -547,14 +581,14 @@ describe('NGSI-v2 - Multi-entity plugin is executed before timestamp process plu }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When an update comes for a multientity measurement and timestamp is enabled in config file', function() { - var values = [ + describe('When an update comes for a multientity measurement and timestamp is enabled in config file', function () { + const values = [ { name: 'p', type: 'centigrades', @@ -572,7 +606,7 @@ describe('NGSI-v2 - Multi-entity plugin is executed before timestamp process plu } ]; - var singleValue = [ + const singleValue = [ { name: 'h', type: 'Percentage', @@ -580,101 +614,99 @@ describe('NGSI-v2 - Multi-entity plugin is executed before timestamp process plu } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); }); - it('should send two context elements, one for each entity', function(done) { - + it('should send two context elements, one for each entity', function (done) { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/op/update', function(body) { - var expectedBody = utils.readExampleFile('./test/unit/ngsiv2/examples' + - '/contextRequests/updateContextMultientityTimestampPlugin1.json'); + .post('/v2/op/update', function (body) { + const expectedBody = utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextMultientityTimestampPlugin1.json' + ); // Note that TimeInstant fields are not included in the json used by this mock as they are dynamic // fields. The following code just checks that TimeInstant fields are present. - if (!body.entities[1].TimeInstant || !body.entities[1].humidity.metadata.TimeInstant) - { + if (!body.entities[1].TimeInstant || !body.entities[1].humidity.metadata.TimeInstant) { return false; } - else { - var timeInstantEntity = body.entities[1].TimeInstant; - var timeInstantAtt = body.entities[1].humidity.metadata.TimeInstant; - if (moment(timeInstantEntity, 'YYYY-MM-DDTHH:mm:ss.SSSZ').isValid && - moment(timeInstantAtt, 'YYYY-MM-DDTHH:mm:ss.SSSZ').isValid) { - delete body.entities[1].TimeInstant; - delete body.entities[1].humidity.metadata.TimeInstant; - - delete expectedBody.entities[1].TimeInstant; - delete expectedBody.entities[1].humidity.metadata.TimeInstant; - return JSON.stringify(body) === JSON.stringify(expectedBody); - - } else { - return false; - } + const timeInstantEntity = body.entities[1].TimeInstant; + const timeInstantAtt = body.entities[1].humidity.metadata.TimeInstant; + if ( + moment(timeInstantEntity, 'YYYY-MM-DDTHH:mm:ss.SSSZ').isValid && + moment(timeInstantAtt, 'YYYY-MM-DDTHH:mm:ss.SSSZ').isValid + ) { + delete body.entities[1].TimeInstant; + delete body.entities[1].humidity.metadata.TimeInstant; + + delete expectedBody.entities[1].TimeInstant; + delete expectedBody.entities[1].humidity.metadata.TimeInstant; + return JSON.stringify(body) === JSON.stringify(expectedBody); } + return false; }) .reply(204); - iotAgentLib.update('ws4', 'WeatherStation', '', values, function(error) { + iotAgentLib.update('ws4', 'WeatherStation', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); - it('should send two context elements, one for each entity', function(done) { + it('should send two context elements, one for each entity', function (done) { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/op/update', function(body) { - var expectedBody = utils.readExampleFile('./test/unit/ngsiv2/examples' + - '/contextRequests/updateContextMultientityTimestampPlugin2.json'); + .post('/v2/op/update', function (body) { + const expectedBody = utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextMultientityTimestampPlugin2.json' + ); // Note that TimeInstant fields are not included in the json used by this mock as they are dynamic // fields. The following code just checks that TimeInstant fields are present. - if (!body.entities[1].TimeInstant || - !body.entities[1].humidity.metadata.TimeInstant) - { + if (!body.entities[1].TimeInstant || !body.entities[1].humidity.metadata.TimeInstant) { return false; } - else { - var timeInstantEntity2 = body.entities[1].TimeInstant; - var timeInstantAtt = body.entities[1].humidity.metadata.TimeInstant; - if (moment(timeInstantEntity2, 'YYYY-MM-DDTHH:mm:ss.SSSZ').isValid && - moment(timeInstantAtt, 'YYYY-MM-DDTHH:mm:ss.SSSZ').isValid) { - - delete body.entities[1].TimeInstant; - delete body.entities[1].humidity.metadata.TimeInstant; - delete expectedBody.entities[1].TimeInstant; - delete expectedBody.entities[1].humidity.metadata.TimeInstant; - return JSON.stringify(body) === JSON.stringify(expectedBody); - - } else { - return false; - } + const timeInstantEntity2 = body.entities[1].TimeInstant; + const timeInstantAtt = body.entities[1].humidity.metadata.TimeInstant; + if ( + moment(timeInstantEntity2, 'YYYY-MM-DDTHH:mm:ss.SSSZ').isValid && + moment(timeInstantAtt, 'YYYY-MM-DDTHH:mm:ss.SSSZ').isValid + ) { + delete body.entities[1].TimeInstant; + delete body.entities[1].humidity.metadata.TimeInstant; + + delete expectedBody.entities[1].TimeInstant; + delete expectedBody.entities[1].humidity.metadata.TimeInstant; + return JSON.stringify(body) === JSON.stringify(expectedBody); } + return false; }) .reply(204); - iotAgentLib.update('ws4', 'WeatherStation', '', singleValue, function(error) { + iotAgentLib.update('ws4', 'WeatherStation', '', singleValue, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); - it('should propagate user provider timestamp to mapped entities', function(done) { + it('should propagate user provider timestamp to mapped entities', function (done) { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/op/update', utils.readExampleFile('./test/unit/ngsiv2/examples' + - '/contextRequests/updateContextMultientityTimestampPlugin3.json')) + .post( + '/v2/op/update', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextMultientityTimestampPlugin3.json' + ) + ) .reply(204); - var tsValue = [ + const tsValue = [ { name: 'h', type: 'Percentage', @@ -688,7 +720,7 @@ describe('NGSI-v2 - Multi-entity plugin is executed before timestamp process plu } ]; - iotAgentLib.update('ws5', 'WeatherStation', '', tsValue, function(error) { + iotAgentLib.update('ws5', 'WeatherStation', '', tsValue, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -698,14 +730,14 @@ describe('NGSI-v2 - Multi-entity plugin is executed before timestamp process plu }); describe('NGSI-v2 - Multi-entity plugin is executed for a command update for a regular entity ', function () { - beforeEach(function(done) { + beforeEach(function (done) { logger.setLevel('FATAL'); iotAgentConfig.timestamp = true; - var time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 + const time = new Date(1438760101468); // 2015-08-05T07:35:01.468+00:00 timekeeper.freeze(time); - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.attributeAlias.update); iotAgentLib.addQueryMiddleware(iotAgentLib.dataPlugins.attributeAlias.query); iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.multiEntity.update); @@ -715,38 +747,41 @@ describe('NGSI-v2 - Multi-entity plugin is executed for a command update for a r }); }); - afterEach(function(done) { + afterEach(function (done) { timekeeper.reset(); - iotAgentLib.clearAll(function() { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - it('Should send the update to the context broker', function(done) { - + it('Should send the update to the context broker', function (done) { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/op/update', utils.readExampleFile('./test/unit/ngsiv2/examples' + - '/contextRequests/updateContextMultientityTimestampPlugin4.json')) + .post( + '/v2/op/update', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextMultientityTimestampPlugin4.json' + ) + ) .reply(204); - var commands = [ + const commands = [ { name: 'PING_status', type: 'commandStatus', - value: 'OK', + value: 'OK' }, { name: 'PING_info', type: 'commandResult', - value:'1234567890' + value: '1234567890' } ]; - iotAgentLib.update('sensorCommand', 'SensorCommand', '', commands, function(error) { + iotAgentLib.update('sensorCommand', 'SensorCommand', '', commands, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); -}); \ No newline at end of file +}); diff --git a/test/unit/ngsiv2/plugins/timestamp-processing-plugin_test.js b/test/unit/ngsiv2/plugins/timestamp-processing-plugin_test.js index ff5b9ed1d..42a8f2446 100644 --- a/test/unit/ngsiv2/plugins/timestamp-processing-plugin_test.js +++ b/test/unit/ngsiv2/plugins/timestamp-processing-plugin_test.js @@ -23,65 +23,63 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' - }; - -describe('NGSI-v2 - Timestamp processing plugin', function() { - beforeEach(function(done) { +describe('NGSI-v2 - Timestamp processing plugin', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.timestampProcess.update); done(); }); }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When an update comes with a timestamp through the plugin', function() { - var values = [ + describe('When an update comes with a timestamp through the plugin', function () { + const values = [ { name: 'state', type: 'Boolean', @@ -94,20 +92,24 @@ describe('NGSI-v2 - Timestamp processing plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/light1/attrs', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateContextProcessTimestamp.json')) - .query({type: 'Light'}) + .post( + '/v2/entities/light1/attrs', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateContextProcessTimestamp.json' + ) + ) + .query({ type: 'Light' }) .reply(204); }); - it('should return an entity with all its timestamps expanded to have separators', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should return an entity with all its timestamps expanded to have separators', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); diff --git a/test/unit/ngsiv2/provisioning/device-provisioning-api_test.js b/test/unit/ngsiv2/provisioning/device-provisioning-api_test.js index 61ac3dba9..221464ab1 100644 --- a/test/unit/ngsiv2/provisioning/device-provisioning-api_test.js +++ b/test/unit/ngsiv2/provisioning/device-provisioning-api_test.js @@ -22,44 +22,49 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - should = require('should'), - nock = require('nock'), - request = require('request'), - moment = require('moment'), - contextBrokerMock, - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041, - baseRoot: '/' - }, - types: {}, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - explicitAttrs: false - }; - -describe('NGSI-v2 - Device provisioning API: Provision devices', function() { - beforeEach(function(done) { + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const nock = require('nock'); +const request = require('request'); +const moment = require('moment'); +let contextBrokerMock; +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041, + baseRoot: '/' + }, + types: {}, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + explicitAttrs: false +}; + +describe('NGSI-v2 - Device provisioning API: Provision devices', function () { + beforeEach(function (done) { nock.cleanAll(); - iotAgentLib.activate(iotAgentConfig, function() { + iotAgentLib.activate(iotAgentConfig, function () { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/registrations', utils.readExampleFile('./test/unit/ngsiv2/examples' + - '/contextAvailabilityRequests/registerProvisionedDevice.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .post( + '/v2/registrations', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerProvisionedDevice.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under @@ -74,31 +79,37 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { }); }); - afterEach(function(done) { + afterEach(function (done) { nock.cleanAll(); iotAgentLib.setProvisioningHandler(); iotAgentLib.deactivate(done); }); - describe('When a device provisioning request with all the required data arrives to the IoT Agent', function() { - beforeEach(function() { + describe('When a device provisioning request with all the required data arrives to the IoT Agent', function () { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/registrations', utils.readExampleFile('./test/unit/ngsiv2/examples' + - '/contextAvailabilityRequests/registerProvisionedDevice.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .post( + '/v2/registrations', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerProvisionedDevice.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/createProvisionedDevice.json')) + .post( + '/v2/entities?options=upsert', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/createProvisionedDevice.json') + ) .reply(204); }); - var options = { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json'), @@ -108,36 +119,36 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { } }; - it('should add the device to the devices list', function(done) { - request(options, function(error, response, body) { + it('should add the device to the devices list', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(201); - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { results.devices.length.should.equal(1); done(); }); }); }); - it('should call the device provisioning handler if present', function(done) { - var handlerCalled = false; + it('should call the device provisioning handler if present', function (done) { + let handlerCalled = false; - iotAgentLib.setProvisioningHandler(function(device, callback) { + iotAgentLib.setProvisioningHandler(function (device, callback) { handlerCalled = true; callback(null, device); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { handlerCalled.should.equal(true); done(); }); }); - it('should store the device with the provided entity id, name and type', function(done) { - request(options, function(error, response, body) { + it('should store the device with the provided entity id, name and type', function (done) { + request(options, function (error, response, body) { response.statusCode.should.equal(201); - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { results.devices[0].id.should.equal('Light1'); results.devices[0].name.should.equal('TheFirstLight'); results.devices[0].type.should.equal('TheLightType'); @@ -145,10 +156,10 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { }); }); }); - it('should store the device with the per device information', function(done) { - request(options, function(error, response, body) { + it('should store the device with the per device information', function (done) { + request(options, function (error, response, body) { response.statusCode.should.equal(201); - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { should.exist(results.devices[0].timezone); results.devices[0].timezone.should.equal('America/Santiago'); should.exist(results.devices[0].endpoint); @@ -175,11 +186,11 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { }); }); - it('should store fill the device ID in case only the name is provided', function(done) { + it('should store fill the device ID in case only the name is provided', function (done) { /* jshint camelcase:false */ - request(options, function(error, response, body) { + request(options, function (error, response, body) { response.statusCode.should.equal(201); - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { results.devices[0].lazy[0].object_id.should.equal('luminance'); results.devices[0].commands[0].object_id.should.equal('commandAttr'); results.devices[0].active[0].object_id.should.equal('attr_name'); @@ -188,10 +199,10 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { }); }); - it('should store service and subservice info from the headers along with the device data', function(done) { - request(options, function(error, response, body) { + it('should store service and subservice info from the headers along with the device data', function (done) { + request(options, function (error, response, body) { response.statusCode.should.equal(201); - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { should.exist(results.devices[0].service); results.devices[0].service.should.equal('smartGondor'); should.exist(results.devices[0].subservice); @@ -201,18 +212,18 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { }); }); - it('should create the initial entity in the Context Broker', function(done) { - request(options, function(error, response, body) { + it('should create the initial entity in the Context Broker', function (done) { + request(options, function (error, response, body) { response.statusCode.should.equal(201); - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { contextBrokerMock.done(); done(); }); }); }); }); - describe('When a device provisioning request with a TimeInstant attribute arrives to the IoTA', function() { - var options = { + describe('When a device provisioning request with a TimeInstant attribute arrives to the IoTA', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionTimeInstant.json'), @@ -222,40 +233,41 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { } }; - beforeEach(function(done) { - iotAgentLib.deactivate(function() { + beforeEach(function (done) { + iotAgentLib.deactivate(function () { iotAgentConfig.timestamp = true; iotAgentLib.activate(iotAgentConfig, done); }); }); - afterEach(function() { + afterEach(function () { iotAgentConfig.timestamp = false; }); - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/createTimeinstantDevice.json')) + .post( + '/v2/entities?options=upsert', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/createTimeinstantDevice.json') + ) .reply(204); done(); }); - it('should send the appropriate requests to the Context Broker', function(done) { - request(options, function(error, response, body) { + it('should send the appropriate requests to the Context Broker', function (done) { + request(options, function (error, response, body) { contextBrokerMock.done(); done(); }); }); }); - - describe('When a device provisioning request with a timestamp provision attribute arrives to the IoTA', function() { - var options = { + describe('When a device provisioning request with a timestamp provision attribute arrives to the IoTA', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionTimeInstant2.json'), @@ -265,40 +277,41 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { } }; - beforeEach(function(done) { - iotAgentLib.deactivate(function() { + beforeEach(function (done) { + iotAgentLib.deactivate(function () { iotAgentConfig.timestamp = false; iotAgentLib.activate(iotAgentConfig, done); }); }); - afterEach(function() { + afterEach(function () { iotAgentConfig.timestamp = false; }); - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/createTimeinstantDevice.json')) + .post( + '/v2/entities?options=upsert', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/createTimeinstantDevice.json') + ) .reply(204); done(); }); - it('should send the appropriate requests to the Context Broker', function(done) { - request(options, function(error, response, body) { + it('should send the appropriate requests to the Context Broker', function (done) { + request(options, function (error, response, body) { contextBrokerMock.done(); done(); }); }); }); - - describe('When a device provisioning request with explicitAttrs'+ - ' provision attribute arrives to the IoTA', function () { - var options = { + + describe('When a device provisioning request with explicitAttrs provision attribute arrives to the IoTA', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionExplicitAttrs.json'), @@ -324,8 +337,10 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/createExplicitAttrsDevice.json')) + .post( + '/v2/entities?options=upsert', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/createExplicitAttrsDevice.json') + ) .reply(204); done(); @@ -348,370 +363,423 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { }); }); - describe('When a device provisioning request without explicitAttrs provision attribute arrives to the IoTA'+ - ' and explicitAttrs is not configured at group level', function () { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }; + describe( + 'When a device provisioning request without explicitAttrs provision attribute arrives to the IoTA' + + ' and explicitAttrs is not configured at group level', + function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile( + './test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json' + ), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; - beforeEach(function (done) { - iotAgentLib.deactivate(function () { - iotAgentConfig.explicitAttrs = false; - iotAgentLib.activate(iotAgentConfig, done); + beforeEach(function (done) { + iotAgentLib.deactivate(function () { + iotAgentConfig.explicitAttrs = false; + iotAgentLib.activate(iotAgentConfig, done); + }); }); - }); - afterEach(function () { - iotAgentConfig.explicitAttrs = false; - }); - - beforeEach(function (done) { - nock.cleanAll(); - contextBrokerMock = nock('http://192.168.1.1:1026') - .matchHeader('fiware-service', 'smartGondor') - .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', - utils.readExampleFile('./test/unit/ngsiv2/examples/' + - 'contextRequests/createMinimumProvisionedDevice.json')) - .reply(204); + afterEach(function () { + iotAgentConfig.explicitAttrs = false; + }); - done(); - }); + beforeEach(function (done) { + nock.cleanAll(); + contextBrokerMock = nock('http://192.168.1.1:1026') + .matchHeader('fiware-service', 'smartGondor') + .matchHeader('fiware-servicepath', '/gardens') + .post( + '/v2/entities?options=upsert', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/createMinimumProvisionedDevice.json' + ) + ) + .reply(204); - it('should send the appropriate requests to the Context Broker', function (done) { - request(options, function (error, response, body) { - contextBrokerMock.done(); done(); }); - }); - it('should store the device with explicitAttrs value provided in configuration', function (done) { - request(options, function (error, response, body) { - iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { - should.exist(results.devices[0].explicitAttrs); - results.devices[0].explicitAttrs.should.equal(false); + + it('should send the appropriate requests to the Context Broker', function (done) { + request(options, function (error, response, body) { + contextBrokerMock.done(); done(); }); }); - }); - }); - - describe('When a device provisioning request without explicitAttrs provision attribute arrives to the IoTA'+ - ' and explicitAttrs is configured at group level', function () { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - groupCreation = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: { - services: [ - { - resource: '/Thing', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', - /*jshint camelcase: false */ - entity_type: 'MicroLights', - cbroker: 'http://192.168.1.1:1026', - explicitAttrs: true - } - ] - }, - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }; - - beforeEach(function (done) { - nock.cleanAll(); - contextBrokerMock = nock('http://192.168.1.1:1026') - .matchHeader('fiware-service', 'smartGondor') - .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', - utils.readExampleFile('./test/unit/ngsiv2/examples/' + - 'contextRequests/createMinimumProvisionedDevice.json')) - .reply(204); - - done(); - }); - - it('should store the device with explicitAttrs value provided in configuration', function (done) { - request(groupCreation, function (error, response, body) { + it('should store the device with explicitAttrs value provided in configuration', function (done) { request(options, function (error, response, body) { iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { should.exist(results.devices[0].explicitAttrs); - results.devices[0].explicitAttrs.should.equal(true); + results.devices[0].explicitAttrs.should.equal(false); done(); }); }); }); - }); - }); - - describe('When a device provisioning request without static attributes arrives to the IoTA'+ - ' and static attribute is configured at group level', function () { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - groupCreation = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: { - services: [ - { - resource: '/Thing', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', - /*jshint camelcase: false */ - entity_type: 'MicroLights', - cbroker: 'http://192.168.1.1:1026', - explicitAttrs: true, - static_attributes: [{ - 'name': 'bootstrapServer', - 'type': 'Address', - 'value': '127.0.0.1' - }] - } - ] - }, - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }; + } + ); + + describe( + 'When a device provisioning request without explicitAttrs provision attribute arrives to the IoTA' + + ' and explicitAttrs is configured at group level', + function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile( + './test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json' + ), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + const groupCreation = { + url: 'http://localhost:4041/iot/services', + method: 'POST', + json: { + services: [ + { + resource: '/Thing', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', + /*jshint camelcase: false */ + entity_type: 'MicroLights', + cbroker: 'http://192.168.1.1:1026', + explicitAttrs: true + } + ] + }, + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; - beforeEach(function (done) { - nock.cleanAll(); - contextBrokerMock = nock('http://192.168.1.1:1026') - .matchHeader('fiware-service', 'smartGondor') - .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', - utils.readExampleFile('./test/unit/ngsiv2/examples/' + - 'contextRequests/createStaticAttributesProvisionDevice.json')) - .reply(204); + beforeEach(function (done) { + nock.cleanAll(); + contextBrokerMock = nock('http://192.168.1.1:1026') + .matchHeader('fiware-service', 'smartGondor') + .matchHeader('fiware-servicepath', '/gardens') + .post( + '/v2/entities?options=upsert', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/createMinimumProvisionedDevice.json' + ) + ) + .reply(204); - done(); - }); + done(); + }); - it('should store the device with static attributes'+ - ' provided in configuration', function (done) { - request(groupCreation, function (error, response, body) { - request(options, function (error, response, body) { - iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { - should.exist(results.devices[0].staticAttributes); - results.devices[0].staticAttributes[0].name.should.equal('bootstrapServer'); - done(); + it('should store the device with explicitAttrs value provided in configuration', function (done) { + request(groupCreation, function (error, response, body) { + request(options, function (error, response, body) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { + should.exist(results.devices[0].explicitAttrs); + results.devices[0].explicitAttrs.should.equal(true); + done(); + }); }); }); }); - }); - }); - describe('When a device provisioning request with static attributes arrives to the IoTA'+ - ' and static attribute is not configured at group level', function () { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests'+ - '/provisionStaticAttrsDevice.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - groupCreation = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: { - services: [ - { - resource: '/Thing', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', - /*jshint camelcase: false */ - entity_type: 'MicroLights', - cbroker: 'http://192.168.1.1:1026', - explicitAttrs: true - } - ] - }, - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }; + } + ); + + describe( + 'When a device provisioning request without static attributes arrives to the IoTA' + + ' and static attribute is configured at group level', + function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile( + './test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json' + ), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + const groupCreation = { + url: 'http://localhost:4041/iot/services', + method: 'POST', + json: { + services: [ + { + resource: '/Thing', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', + /*jshint camelcase: false */ + entity_type: 'MicroLights', + cbroker: 'http://192.168.1.1:1026', + explicitAttrs: true, + static_attributes: [ + { + name: 'bootstrapServer', + type: 'Address', + value: '127.0.0.1' + } + ] + } + ] + }, + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; - beforeEach(function (done) { - nock.cleanAll(); - contextBrokerMock = nock('http://192.168.1.1:1026') - .matchHeader('fiware-service', 'smartGondor') - .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', - utils.readExampleFile('./test/unit/ngsiv2/examples/' + - 'contextRequests/createStaticAttributesProvisionDevice.json')) - .reply(204); + beforeEach(function (done) { + nock.cleanAll(); + contextBrokerMock = nock('http://192.168.1.1:1026') + .matchHeader('fiware-service', 'smartGondor') + .matchHeader('fiware-servicepath', '/gardens') + .post( + '/v2/entities?options=upsert', + utils.readExampleFile( + './test/unit/ngsiv2/examples/' + + 'contextRequests/createStaticAttributesProvisionDevice.json' + ) + ) + .reply(204); - done(); - }); + done(); + }); - it('should store the device with static attributes provided in device', function (done) { - request(groupCreation, function (error, response, body) { - request(options, function (error, response, body) { - iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { - should.exist(results.devices[0].staticAttributes); - results.devices[0].staticAttributes[0].name.should.equal('bootstrapServer'); - done(); + it('should store the device with static attributes provided in configuration', function (done) { + request(groupCreation, function (error, response, body) { + request(options, function (error, response, body) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { + should.exist(results.devices[0].staticAttributes); + results.devices[0].staticAttributes[0].name.should.equal('bootstrapServer'); + done(); + }); }); }); }); - }); - }); - - describe('When a device provisioning request with static attributes arrives to the IoTA'+ - ' and static attribute is also configured at group level', function () { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests'+ - '/provisionStaticAttrsDevice2.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - groupCreation = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: { - services: [ - { - resource: '/Thing', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', - /*jshint camelcase: false */ - entity_type: 'MicroLights', - cbroker: 'http://192.168.1.1:1026', - explicitAttrs: true, - static_attributes: [{ - 'name': 'bootstrapServer', - 'type': 'Address', - 'value': '127.0.0.1' - }] - } - ] - }, - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }; + } + ); + describe( + 'When a device provisioning request with static attributes arrives to the IoTA' + + ' and static attribute is not configured at group level', + function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile( + './test/unit/examples/deviceProvisioningRequests/provisionStaticAttrsDevice.json' + ), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + const groupCreation = { + url: 'http://localhost:4041/iot/services', + method: 'POST', + json: { + services: [ + { + resource: '/Thing', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', + /*jshint camelcase: false */ + entity_type: 'MicroLights', + cbroker: 'http://192.168.1.1:1026', + explicitAttrs: true + } + ] + }, + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; - beforeEach(function (done) { - nock.cleanAll(); - contextBrokerMock = nock('http://192.168.1.1:1026') - .matchHeader('fiware-service', 'smartGondor') - .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', - utils.readExampleFile('./test/unit/ngsiv2/examples/' + - 'contextRequests/createStaticAttributesProvisionDevice2.json')) - .reply(204); + beforeEach(function (done) { + nock.cleanAll(); + contextBrokerMock = nock('http://192.168.1.1:1026') + .matchHeader('fiware-service', 'smartGondor') + .matchHeader('fiware-servicepath', '/gardens') + .post( + '/v2/entities?options=upsert', + utils.readExampleFile( + './test/unit/ngsiv2/examples/' + + 'contextRequests/createStaticAttributesProvisionDevice.json' + ) + ) + .reply(204); - done(); - }); + done(); + }); - it('should store the device with static attributes provided in'+ - ' configuration as well as device', function (done) { - request(groupCreation, function (error, response, body) { - request(options, function (error, response, body) { - iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { - should.exist(results.devices[0].staticAttributes); - results.devices[0].staticAttributes.length.should.equal(2); - done(); + it('should store the device with static attributes provided in device', function (done) { + request(groupCreation, function (error, response, body) { + request(options, function (error, response, body) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { + should.exist(results.devices[0].staticAttributes); + results.devices[0].staticAttributes[0].name.should.equal('bootstrapServer'); + done(); + }); }); }); }); - }); - }); + } + ); + + describe( + 'When a device provisioning request with static attributes arrives to the IoTA' + + ' and static attribute is also configured at group level', + function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile( + './test/unit/examples/deviceProvisioningRequests/provisionStaticAttrsDevice2.json' + ), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + const groupCreation = { + url: 'http://localhost:4041/iot/services', + method: 'POST', + json: { + services: [ + { + resource: '/Thing', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', + /*jshint camelcase: false */ + entity_type: 'MicroLights', + cbroker: 'http://192.168.1.1:1026', + explicitAttrs: true, + static_attributes: [ + { + name: 'bootstrapServer', + type: 'Address', + value: '127.0.0.1' + } + ] + } + ] + }, + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; - describe('When a device provisioning request with static attributes arrives to the IoTA'+ - ' and same static attribute is also configured at group level', function () { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests'+ - '/provisionStaticAttrsDevice3.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - groupCreation = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: { - services: [ - { - resource: '/Thing', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', - /*jshint camelcase: false */ - entity_type: 'MicroLights', - cbroker: 'http://192.168.1.1:1026', - explicitAttrs: true, - static_attributes: [{ - 'name': 'bootstrapServer', - 'type': 'Address', - 'value': '127.0.0.1' - }] - } - ] - }, - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }; + beforeEach(function (done) { + nock.cleanAll(); + contextBrokerMock = nock('http://192.168.1.1:1026') + .matchHeader('fiware-service', 'smartGondor') + .matchHeader('fiware-servicepath', '/gardens') + .post( + '/v2/entities?options=upsert', + utils.readExampleFile( + './test/unit/ngsiv2/examples/' + + 'contextRequests/createStaticAttributesProvisionDevice2.json' + ) + ) + .reply(204); - beforeEach(function (done) { - nock.cleanAll(); - contextBrokerMock = nock('http://192.168.1.1:1026') - .matchHeader('fiware-service', 'smartGondor') - .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', - utils.readExampleFile('./test/unit/ngsiv2/examples/' + - 'contextRequests/createStaticAttributesProvisionDevice3.json')) - .reply(204); + done(); + }); - done(); - }); + it('should store the device with static attributes provided in configuration as well as device', function (done) { + request(groupCreation, function (error, response, body) { + request(options, function (error, response, body) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { + should.exist(results.devices[0].staticAttributes); + results.devices[0].staticAttributes.length.should.equal(2); + done(); + }); + }); + }); + }); + } + ); + + describe( + 'When a device provisioning request with static attributes arrives to the IoTA' + + ' and same static attribute is also configured at group level', + function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile( + './test/unit/examples/deviceProvisioningRequests/provisionStaticAttrsDevice3.json' + ), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + const groupCreation = { + url: 'http://localhost:4041/iot/services', + method: 'POST', + json: { + services: [ + { + resource: '/Thing', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', + /*jshint camelcase: false */ + entity_type: 'MicroLights', + cbroker: 'http://192.168.1.1:1026', + explicitAttrs: true, + static_attributes: [ + { + name: 'bootstrapServer', + type: 'Address', + value: '127.0.0.1' + } + ] + } + ] + }, + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; - it('should store the device with static attributes provided in device', function (done) { - request(groupCreation, function (error, response, body) { - request(options, function (error, response, body) { - iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { - should.exist(results.devices[0].staticAttributes); - results.devices[0].staticAttributes[0].value.should.equal('127.0.0.2'); - done(); + beforeEach(function (done) { + nock.cleanAll(); + contextBrokerMock = nock('http://192.168.1.1:1026') + .matchHeader('fiware-service', 'smartGondor') + .matchHeader('fiware-servicepath', '/gardens') + .post( + '/v2/entities?options=upsert', + utils.readExampleFile( + './test/unit/ngsiv2/examples/' + + 'contextRequests/createStaticAttributesProvisionDevice3.json' + ) + ) + .reply(204); + + done(); + }); + + it('should store the device with static attributes provided in device', function (done) { + request(groupCreation, function (error, response, body) { + request(options, function (error, response, body) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { + should.exist(results.devices[0].staticAttributes); + results.devices[0].staticAttributes[0].value.should.equal('127.0.0.2'); + done(); + }); }); }); }); - }); - }); + } + ); - describe('When a device provisioning request with a autoprovision attribute arrives to the IoTA', function() { - var options = { + describe('When a device provisioning request with a autoprovision attribute arrives to the IoTA', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionAutoprovision.json'), @@ -721,39 +789,40 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { } }; - beforeEach(function(done) { - iotAgentLib.deactivate(function() { + beforeEach(function (done) { + iotAgentLib.deactivate(function () { iotAgentConfig.appendMode = false; iotAgentLib.activate(iotAgentConfig, done); }); }); - afterEach(function() { + afterEach(function () { iotAgentConfig.appendMode = false; }); - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', - utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/createAutoprovisionDevice.json')) + .post( + '/v2/entities?options=upsert', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/createAutoprovisionDevice.json') + ) .reply(204); done(); }); - it('should send the appropriate requests to the Context Broker', function(done) { - request(options, function(error, response, body) { + it('should send the appropriate requests to the Context Broker', function (done) { + request(options, function (error, response, body) { contextBrokerMock.done(); done(); }); }); }); - describe('When a device provisioning request arrives to the IoTA' + - 'and timestamp is enabled in configuration', function() { - var options = { + describe('When a device provisioning request arrives to the IoTAand timestamp is enabled in configuration', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), @@ -763,32 +832,30 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { } }; - beforeEach(function(done) { - iotAgentLib.deactivate(function() { + beforeEach(function (done) { + iotAgentLib.deactivate(function () { iotAgentConfig.timestamp = true; iotAgentLib.activate(iotAgentConfig, done); }); }); - afterEach(function() { + afterEach(function () { iotAgentConfig.timestamp = false; }); - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', function(body) { - var expectedBody = utils.readExampleFile('./test/unit/ngsiv2/examples/' + - 'contextRequests/createTimeInstantMinimumDevice.json'); - if (!body.TimeInstant.value) - { + .post('/v2/entities?options=upsert', function (body) { + const expectedBody = utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/createTimeInstantMinimumDevice.json' + ); + if (!body.TimeInstant.value) { return false; - } - else if (moment(body.TimeInstant.value, 'YYYY-MM-DDTHH:mm:ss.SSSZ').isValid()) - { - var timeInstantDiff = moment().diff(body.TimeInstant.value, 'milliseconds'); + } else if (moment(body.TimeInstant.value, 'YYYY-MM-DDTHH:mm:ss.SSSZ').isValid()) { + const timeInstantDiff = moment().diff(body.TimeInstant.value, 'milliseconds'); if (timeInstantDiff < 500) { delete body.TimeInstant; @@ -796,8 +863,7 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { } return false; - } - else { + } else { return false; } }) @@ -806,16 +872,16 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { done(); }); - it('should send the appropriate requests to the Context Broker', function(done) { - request(options, function(error, response, body) { + it('should send the appropriate requests to the Context Broker', function (done) { + request(options, function (error, response, body) { contextBrokerMock.done(); done(); }); }); }); - describe('When a device provisioning request with the minimum required data arrives to the IoT Agent', function() { - var options = { + describe('When a device provisioning request with the minimum required data arrives to the IoT Agent', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), @@ -825,42 +891,45 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', - utils.readExampleFile('./test/unit/ngsiv2/examples/' + - 'contextRequests/createMinimumProvisionedDevice.json')) + .post( + '/v2/entities?options=upsert', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/createMinimumProvisionedDevice.json' + ) + ) .reply(204); done(); }); - it('should send the appropriate requests to the Context Broker', function(done) { - request(options, function(error, response, body) { + it('should send the appropriate requests to the Context Broker', function (done) { + request(options, function (error, response, body) { contextBrokerMock.done(); done(); }); }); - it('should add the device to the devices list', function(done) { - request(options, function(error, response, body) { + it('should add the device to the devices list', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(201); - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { results.devices.length.should.equal(1); done(); }); }); }); - it('should store the device with the provided entity id, name and type', function(done) { - request(options, function(error, response, body) { + it('should store the device with the provided entity id, name and type', function (done) { + request(options, function (error, response, body) { response.statusCode.should.equal(201); - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { results.devices[0].id.should.equal('MicroLight1'); results.devices[0].name.should.equal('FirstMicroLight'); results.devices[0].type.should.equal('MicroLights'); @@ -870,8 +939,8 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { }); }); - describe('When a device provisioning request with geo:point attributes arrives', function() { - var options = { + describe('When a device provisioning request with geo:point attributes arrives', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionGeopointDevice.json'), @@ -881,29 +950,32 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', + .post( + '/v2/entities?options=upsert', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/createGeopointProvisionedDevice.json')) + './test/unit/ngsiv2/examples/contextRequests/createGeopointProvisionedDevice.json' + ) + ) .reply(204); done(); }); - it('should send the appropriate initial values to the Context Broker', function(done) { - request(options, function(error, response, body) { + it('should send the appropriate initial values to the Context Broker', function (done) { + request(options, function (error, response, body) { contextBrokerMock.done(); done(); }); }); }); - describe('When a device provisioning request with DateTime attributes arrives', function() { - var options = { + describe('When a device provisioning request with DateTime attributes arrives', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionDatetimeDevice.json'), @@ -913,87 +985,92 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', + .post( + '/v2/entities?options=upsert', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/createDatetimeProvisionedDevice.json')) + './test/unit/ngsiv2/examples/contextRequests/createDatetimeProvisionedDevice.json' + ) + ) .reply(204); done(); }); - it('should send the appropriate initial values to the Context Broker', function(done) { - request(options, function(error, response, body) { + it('should send the appropriate initial values to the Context Broker', function (done) { + request(options, function (error, response, body) { contextBrokerMock.done(); done(); }); }); }); + describe('When two devices with the same ID but different services arrive to the agent', function () { + const options1 = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + const options2 = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), + headers: { + 'fiware-service': 'smartMordor', + 'fiware-servicepath': '/electricity' + } + }; - describe('When two devices with the same ID but different services arrive to the agent', function() { - var options1 = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - options2 = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), - headers: { - 'fiware-service': 'smartMordor', - 'fiware-servicepath': '/electricity' - } - }; - - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') - .post('/v2/entities?options=upsert', - utils.readExampleFile('./test/unit/ngsiv2/examples/' + - 'contextRequests/createMinimumProvisionedDevice.json')) + .post( + '/v2/entities?options=upsert', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/createMinimumProvisionedDevice.json' + ) + ) .reply(204); - contextBrokerMock - .post('/v2/entities?options=upsert', - utils.readExampleFile('./test/unit/ngsiv2/examples/' + - 'contextRequests/createMinimumProvisionedDevice.json')) + .post( + '/v2/entities?options=upsert', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/createMinimumProvisionedDevice.json' + ) + ) .reply(204); done(); }); - it('should accept both creations', function(done) { - request(options1, function(error, response, body) { + it('should accept both creations', function (done) { + request(options1, function (error, response, body) { response.statusCode.should.equal(201); - request(options2, function(error, response, body) { + request(options2, function (error, response, body) { response.statusCode.should.equal(201); done(); }); }); }); - it('should show the new device in each list', function(done) { - request(options1, function(error, response, body) { - request(options2, function(error, response, body) { - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + it('should show the new device in each list', function (done) { + request(options1, function (error, response, body) { + request(options2, function (error, response, body) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { results.devices.length.should.equal(1); results.devices[0].id.should.equal('MicroLight1'); - iotAgentLib.listDevices('smartMordor', '/electricity', function(error, results) { + iotAgentLib.listDevices('smartMordor', '/electricity', function (error, results) { results.devices.length.should.equal(1); results.devices[0].id.should.equal('MicroLight1'); done(); @@ -1004,8 +1081,8 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { }); }); - describe('When there is a connection error with a String code connecting the CB', function() { - var options = { + describe('When there is a connection error with a String code connecting the CB', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), @@ -1015,14 +1092,14 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v2/registrations') - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under @@ -1031,13 +1108,13 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v2/entities?options=upsert') - .replyWithError({'message': 'Description of the error', 'code': 'STRING_CODE'}); + .replyWithError({ message: 'Description of the error', code: 'STRING_CODE' }); done(); }); - it('should return a valid return code', function(done) { - request(options, function(error, response, body) { + it('should return a valid return code', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(500); @@ -1046,8 +1123,8 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { }); }); - describe('When there is a connection error with a Number code connecting the CB', function() { - var options = { + describe('When there is a connection error with a Number code connecting the CB', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), @@ -1057,14 +1134,14 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v2/registrations') - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under @@ -1073,13 +1150,13 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v2/entities?options=upsert') - .replyWithError({'message': 'Description of the error', 'code': 123456789}); + .replyWithError({ message: 'Description of the error', code: 123456789 }); done(); }); - it('should return a valid return code (three character number)', function(done) { - request(options, function(error, response, body) { + it('should return a valid return code (three character number)', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(500); @@ -1088,8 +1165,8 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { }); }); - describe('When a device provisioning request with missing data arrives to the IoT Agent', function() { - var options = { + describe('When a device provisioning request with missing data arrives to the IoT Agent', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', headers: { @@ -1097,11 +1174,12 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { 'fiware-servicepath': '/gardens' }, json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionDeviceMissingParameters.json') + './test/unit/examples/deviceProvisioningRequests/provisionDeviceMissingParameters.json' + ) }; - it('should raise a MISSING_ATTRIBUTES error, indicating the missing attributes', function(done) { - request(options, function(error, response, body) { + it('should raise a MISSING_ATTRIBUTES error, indicating the missing attributes', function (done) { + request(options, function (error, response, body) { should.exist(body); response.statusCode.should.equal(400); body.name.should.equal('MISSING_ATTRIBUTES'); @@ -1110,8 +1188,8 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { }); }); }); - describe('When two device provisioning requests with the same service and Device ID arrive', function() { - var options = { + describe('When two device provisioning requests with the same service and Device ID arrive', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json'), @@ -1121,12 +1199,12 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v2/registrations') - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under @@ -1140,9 +1218,9 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { done(); }); - it('should raise a DUPLICATE_ID error, indicating the ID was already in use', function(done) { - request(options, function(error, response, body) { - request(options, function(error, response, body) { + it('should raise a DUPLICATE_ID error, indicating the ID was already in use', function (done) { + request(options, function (error, response, body) { + request(options, function (error, response, body) { should.exist(body); response.statusCode.should.equal(409); body.name.should.equal('DUPLICATE_DEVICE_ID'); @@ -1151,21 +1229,22 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { }); }); }); - describe('When a device provisioning request is malformed', function() { - var options = { + describe('When a device provisioning request is malformed', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionNewDeviceMalformed1.json'), + './test/unit/examples/deviceProvisioningRequests/provisionNewDeviceMalformed1.json' + ), headers: { 'fiware-service': 'smartGondor', 'fiware-servicepath': '/gardens' } }; - it('should raise a WRONG_SYNTAX exception', function(done) { - request(options, function(error, response, body) { - request(options, function(error, response, body) { + it('should raise a WRONG_SYNTAX exception', function (done) { + request(options, function (error, response, body) { + request(options, function (error, response, body) { should.exist(body); response.statusCode.should.equal(400); body.name.should.equal('WRONG_SYNTAX'); @@ -1174,8 +1253,8 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { }); }); }); - describe('When an agent is activated with a different base root', function() { - var options = { + describe('When an agent is activated with a different base root', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/newBaseRoot/iot/devices', method: 'POST', headers: { @@ -1185,40 +1264,41 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json') }; - beforeEach(function(done) { - iotAgentLib.deactivate(function() { + beforeEach(function (done) { + iotAgentLib.deactivate(function () { iotAgentConfig.server.baseRoot = '/newBaseRoot'; iotAgentLib.activate(iotAgentConfig, done); }); }); - afterEach(function() { + afterEach(function () { iotAgentConfig.server.baseRoot = '/'; }); - it('should listen to requests in the new root', function(done) { - request(options, function(error, response, body) { + it('should listen to requests in the new root', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(201); - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { results.devices.length.should.equal(1); done(); }); }); }); }); - describe('When a device provisioning request without the mandatory headers arrives to the Agent', function() { - var options = { + describe('When a device provisioning request without the mandatory headers arrives to the Agent', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', headers: {}, json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionDeviceMissingParameters.json') + './test/unit/examples/deviceProvisioningRequests/provisionDeviceMissingParameters.json' + ) }; - it('should raise a MISSING_HEADERS error, indicating the missing attributes', function(done) { - request(options, function(error, response, body) { + it('should raise a MISSING_HEADERS error, indicating the missing attributes', function (done) { + request(options, function (error, response, body) { should.exist(body); response.statusCode.should.equal(400); body.name.should.equal('MISSING_HEADERS'); @@ -1226,22 +1306,22 @@ describe('NGSI-v2 - Device provisioning API: Provision devices', function() { }); }); }); - describe('When a device delete request arrives to the Agent for a not existing device', function() { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light84', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - }, - method: 'DELETE' - }; - - it('should return a 404 error', function(done) { - request(options, function(error, response, body) { - should.not.exist(error); - response.statusCode.should.equal(404); - done(); - }); - }); + describe('When a device delete request arrives to the Agent for a not existing device', function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light84', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + }, + method: 'DELETE' + }; + + it('should return a 404 error', function (done) { + request(options, function (error, response, body) { + should.not.exist(error); + response.statusCode.should.equal(404); + done(); + }); + }); }); }); diff --git a/test/unit/ngsiv2/provisioning/device-registration_test.js b/test/unit/ngsiv2/provisioning/device-registration_test.js index d1f8c9bec..e28e2ccbb 100644 --- a/test/unit/ngsiv2/provisioning/device-registration_test.js +++ b/test/unit/ngsiv2/provisioning/device-registration_test.js @@ -22,80 +22,80 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - async = require('async'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ], - service: 'smartGondor', - subservice: 'gardens' - }, - 'Termometer': { - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ], - service: 'smartGondor', - subservice: 'gardens' - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +const async = require('async'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' }, - device1 = { - id: 'light1', - type: 'Light', - service: 'smartGondor', - subservice: 'gardens' + server: { + port: 4041 }, - device2 = { - id: 'term2', - type: 'Termometer', - service: 'smartGondor', - subservice: 'gardens' - }; - -describe('NGSI-v2 - IoT Agent Device Registration', function() { - beforeEach(function() { + types: { + Light: { + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ], + service: 'smartGondor', + subservice: 'gardens' + }, + Termometer: { + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [], + service: 'smartGondor', + subservice: 'gardens' + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; +const device1 = { + id: 'light1', + type: 'Light', + service: 'smartGondor', + subservice: 'gardens' +}; +const device2 = { + id: 'term2', + type: 'Termometer', + service: 'smartGondor', + subservice: 'gardens' +}; + +describe('NGSI-v2 - IoT Agent Device Registration', function () { + beforeEach(function () { logger.setLevel('FATAL'); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { // We need to remove the registrationId so that the library does not consider next operatios as updates. delete device1.registrationId; delete device2.registrationId; @@ -103,8 +103,8 @@ describe('NGSI-v2 - IoT Agent Device Registration', function() { }); }); - describe('When a new device is connected to the IoT Agent', function() { - beforeEach(function(done) { + describe('When a new device is connected to the IoT Agent', function () { + beforeEach(function (done) { nock.cleanAll(); // This mock does not check the payload since the aim of the test is not to verify @@ -116,48 +116,49 @@ describe('NGSI-v2 - IoT Agent Device Registration', function() { .post('/v2/entities?options=upsert') .reply(204); - var nockBody = utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json'); + const nockBody = utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json' + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v2/registrations', nockBody) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); - - iotAgentLib.activate(iotAgentConfig, function(error) { + iotAgentLib.activate(iotAgentConfig, function (error) { iotAgentLib.clearAll(done); }); }); - it('should register as ContextProvider of its lazy attributes', function(done) { - iotAgentLib.register(device1, function(error) { - should.not.exist(error); - contextBrokerMock.done(); - done(); + it('should register as ContextProvider of its lazy attributes', function (done) { + iotAgentLib.register(device1, function (error) { + should.not.exist(error); + contextBrokerMock.done(); + done(); }); }); }); - describe('When the Context Broker returns a NGSI error while registering a device', function() { - beforeEach(function(done) { + describe('When the Context Broker returns a NGSI error while registering a device', function () { + beforeEach(function (done) { nock.cleanAll(); - var nockBody = utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json'); + const nockBody = utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json' + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v2/registrations', nockBody) .reply(404); - iotAgentLib.activate(iotAgentConfig, function(error) { + iotAgentLib.activate(iotAgentConfig, function (error) { iotAgentLib.clearAll(done); }); }); - it('should register as ContextProvider of its lazy attributes', function(done) { - iotAgentLib.register(device1, function(error) { + it('should register as ContextProvider of its lazy attributes', function (done) { + iotAgentLib.register(device1, function (error) { should.exist(error); error.name.should.equal('BAD_REQUEST'); contextBrokerMock.done(); @@ -166,25 +167,26 @@ describe('NGSI-v2 - IoT Agent Device Registration', function() { }); }); - describe('When the Context Broker returns an HTTP transport error while registering a device', function() { - beforeEach(function(done) { + describe('When the Context Broker returns an HTTP transport error while registering a device', function () { + beforeEach(function (done) { nock.cleanAll(); - var nockBody = utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json'); + const nockBody = utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json' + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v2/registrations', nockBody) .reply(500); - iotAgentLib.activate(iotAgentConfig, function(error) { + iotAgentLib.activate(iotAgentConfig, function (error) { iotAgentLib.clearAll(done); }); }); it('should not register the device in the internal registry'); - it('should return a REGISTRATION_ERROR error to the caller', function(done) { - iotAgentLib.register(device1, function(error) { + it('should return a REGISTRATION_ERROR error to the caller', function (done) { + iotAgentLib.register(device1, function (error) { should.exist(error); should.exist(error.name); error.name.should.equal('REGISTRATION_ERROR'); @@ -194,17 +196,18 @@ describe('NGSI-v2 - IoT Agent Device Registration', function() { }); }); - describe('When a device is requested to the library using its ID', function() { - beforeEach(function(done) { + describe('When a device is requested to the library using its ID', function () { + beforeEach(function (done) { nock.cleanAll(); - var nockBody = utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json'); + const nockBody = utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json' + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v2/registrations', nockBody) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under @@ -215,14 +218,14 @@ describe('NGSI-v2 - IoT Agent Device Registration', function() { .post('/v2/entities?options=upsert') .reply(204); - iotAgentLib.activate(iotAgentConfig, function(error) { + iotAgentLib.activate(iotAgentConfig, function (error) { iotAgentLib.clearAll(done); }); }); - it('should return all the device\'s information', function(done) { - iotAgentLib.register(device1, function(error) { - iotAgentLib.getDevice('light1', 'smartGondor', 'gardens', function(error, data) { + it("should return all the device's information", function (done) { + iotAgentLib.register(device1, function (error) { + iotAgentLib.getDevice('light1', 'smartGondor', 'gardens', function (error, data) { should.not.exist(error); should.exist(data); data.type.should.equal('Light'); @@ -233,26 +236,27 @@ describe('NGSI-v2 - IoT Agent Device Registration', function() { }); }); - describe('When an unexistent device is requested to the library using its ID', function() { - beforeEach(function(done) { + describe('When an unexistent device is requested to the library using its ID', function () { + beforeEach(function (done) { nock.cleanAll(); - var nockBody = utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json'); + const nockBody = utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerIoTAgent1.json' + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v2/registrations', nockBody) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); - iotAgentLib.activate(iotAgentConfig, function(error) { + iotAgentLib.activate(iotAgentConfig, function (error) { iotAgentLib.clearAll(done); }); }); - it('should return a ENTITY_NOT_FOUND error', function(done) { - iotAgentLib.register(device1, function(error) { - iotAgentLib.getDevice('lightUnexistent', 'smartGondor', 'gardens', function(error, data) { + it('should return a ENTITY_NOT_FOUND error', function (done) { + iotAgentLib.register(device1, function (error) { + iotAgentLib.getDevice('lightUnexistent', 'smartGondor', 'gardens', function (error, data) { should.exist(error); should.not.exist(data); error.code.should.equal(404); @@ -263,48 +267,45 @@ describe('NGSI-v2 - IoT Agent Device Registration', function() { }); }); - describe('When a device is removed from the IoT Agent', function() { - beforeEach(function(done) { - + describe('When a device is removed from the IoT Agent', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .post('/v2/registrations') - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under // provisioning folder - contextBrokerMock - .post('/v2/entities?options=upsert') - .reply(204); + contextBrokerMock.post('/v2/entities?options=upsert').reply(204); contextBrokerMock .post('/v2/registrations') - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under // provisioning folder - contextBrokerMock - .post('/v2/entities?options=upsert') - .reply(204); + contextBrokerMock.post('/v2/entities?options=upsert').reply(204); contextBrokerMock .delete('/v2/registrations/6319a7f5254b05844116584d') - .reply(204, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); - - - iotAgentLib.activate(iotAgentConfig, function(error) { - async.series([ - async.apply(iotAgentLib.clearAll), - async.apply(iotAgentLib.register, device1), - async.apply(iotAgentLib.register, device2) - ], done); + .reply(204, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); + + iotAgentLib.activate(iotAgentConfig, function (error) { + async.series( + [ + async.apply(iotAgentLib.clearAll), + async.apply(iotAgentLib.register, device1), + async.apply(iotAgentLib.register, device2) + ], + done + ); }); }); - it('should update the devices information in Context Broker', function(done) { - iotAgentLib.unregister(device1.id, 'smartGondor', 'gardens', function(error) { + it('should update the devices information in Context Broker', function (done) { + iotAgentLib.unregister(device1.id, 'smartGondor', 'gardens', function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -312,47 +313,44 @@ describe('NGSI-v2 - IoT Agent Device Registration', function() { }); }); - describe('When the Context Broker returns an error while unregistering a device', function() { - beforeEach(function(done) { + describe('When the Context Broker returns an error while unregistering a device', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .post('/v2/registrations') - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under // provisioning folder - contextBrokerMock - .post('/v2/entities?options=upsert') - .reply(204); + contextBrokerMock.post('/v2/entities?options=upsert').reply(204); contextBrokerMock = nock('http://192.168.1.1:1026') .post('/v2/registrations') - .reply(201, null, {'Location': '/v2/registrations/8254b65a7d11650f45844319'}); + .reply(201, null, { Location: '/v2/registrations/8254b65a7d11650f45844319' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under // provisioning folder - contextBrokerMock - .post('/v2/entities?options=upsert') - .reply(204); - - contextBrokerMock - .delete('/v2/registrations/6319a7f5254b05844116584d') - .reply(500); - - iotAgentLib.activate(iotAgentConfig, function(error) { - async.series([ - async.apply(iotAgentLib.clearAll), - async.apply(iotAgentLib.register, device1), - async.apply(iotAgentLib.register, device2) - ], done); + contextBrokerMock.post('/v2/entities?options=upsert').reply(204); + + contextBrokerMock.delete('/v2/registrations/6319a7f5254b05844116584d').reply(500); + + iotAgentLib.activate(iotAgentConfig, function (error) { + async.series( + [ + async.apply(iotAgentLib.clearAll), + async.apply(iotAgentLib.register, device1), + async.apply(iotAgentLib.register, device2) + ], + done + ); }); }); it('should not remove the device from the internal registry'); - it('should return a UNREGISTRATION_ERROR error to the caller', function(done) { - iotAgentLib.unregister(device1.id, 'smartGondor', 'gardens', function(error) { + it('should return a UNREGISTRATION_ERROR error to the caller', function (done) { + iotAgentLib.unregister(device1.id, 'smartGondor', 'gardens', function (error) { should.exist(error); should.exist(error.name); error.name.should.equal('UNREGISTRATION_ERROR'); diff --git a/test/unit/ngsiv2/provisioning/device-update-registration_test.js b/test/unit/ngsiv2/provisioning/device-update-registration_test.js index 0d7b96240..166b64b64 100644 --- a/test/unit/ngsiv2/provisioning/device-update-registration_test.js +++ b/test/unit/ngsiv2/provisioning/device-update-registration_test.js @@ -22,119 +22,119 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ], - service: 'smartGondor', - subservice: 'gardens' - }, - 'Termometer': { - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ], - service: 'smartGondor', - subservice: 'gardens' - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' - }, - device1 = { - id: 'light1', - type: 'Light', - service: 'smartGondor', - subservice: 'gardens', +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' }, - deviceUpdated = { - id: 'light1', - type: 'Light', - name: 'light1', - service: 'smartGondor', - subservice: 'gardens', - internalId: 'newInternalId', - lazy: [ - { - name: 'pressure', - type: 'Hgmm' - } - ], - active: [ - { - name: 'temperature', - type: 'centigrades' - } - ] + server: { + port: 4041 }, - deviceCommandUpdated = { - id: 'light1', - type: 'Light', - name: 'light1', - service: 'smartGondor', - subservice: 'gardens', - internalId: 'newInternalId', - commands: [ - { - name: 'move', - type: 'command' - } - ], - active: [ - { - name: 'temperature', - type: 'centigrades' - } - ] + types: { + Light: { + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ], + service: 'smartGondor', + subservice: 'gardens' + }, + Termometer: { + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [], + service: 'smartGondor', + subservice: 'gardens' + } }, - unknownDevice = { - id: 'rotationSensor4', - type: 'Rotation', - name: 'Rotation4', - service: 'dumbMordor', - subservice: 'gardens', - internalId: 'unknownInternalId', + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; +const device1 = { + id: 'light1', + type: 'Light', + service: 'smartGondor', + subservice: 'gardens' +}; +const deviceUpdated = { + id: 'light1', + type: 'Light', + name: 'light1', + service: 'smartGondor', + subservice: 'gardens', + internalId: 'newInternalId', + lazy: [ + { + name: 'pressure', + type: 'Hgmm' + } + ], + active: [ + { + name: 'temperature', + type: 'centigrades' + } + ] +}; +const deviceCommandUpdated = { + id: 'light1', + type: 'Light', + name: 'light1', + service: 'smartGondor', + subservice: 'gardens', + internalId: 'newInternalId', + commands: [ + { + name: 'move', + type: 'command' + } + ], + active: [ + { + name: 'temperature', + type: 'centigrades' + } + ] +}; +const unknownDevice = { + id: 'rotationSensor4', + type: 'Rotation', + name: 'Rotation4', + service: 'dumbMordor', + subservice: 'gardens', + internalId: 'unknownInternalId', - lazy: [], - active: [] - }; + lazy: [], + active: [] +}; -describe('NGSI-v2 - IoT Agent Device Update Registration', function() { - beforeEach(function(done) { +describe('NGSI-v2 - IoT Agent Device Update Registration', function () { + beforeEach(function (done) { delete device1.registrationId; logger.setLevel('FATAL'); @@ -143,8 +143,8 @@ describe('NGSI-v2 - IoT Agent Device Update Registration', function() { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/registrations') - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .post('/v2/registrations') + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under @@ -155,27 +155,31 @@ describe('NGSI-v2 - IoT Agent Device Update Registration', function() { .post('/v2/entities?options=upsert') .reply(204); - iotAgentLib.activate(iotAgentConfig, function(error) { - iotAgentLib.register(device1, function(error) { + iotAgentLib.activate(iotAgentConfig, function (error) { + iotAgentLib.register(device1, function (error) { done(); }); }); }); - afterEach(function(done) { + afterEach(function (done) { nock.cleanAll(); - iotAgentLib.clearAll(function() { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When a device is preregistered and its registration information updated', function() { - beforeEach(function() { + describe('When a device is preregistered and its registration information updated', function () { + beforeEach(function () { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/Light:light1/attrs?type=Light', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateProvisionActiveAttributes1.json')) + .post( + '/v2/entities/Light:light1/attrs?type=Light', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateProvisionActiveAttributes1.json' + ) + ) .reply(204); // FIXME: When https://github.com/telefonicaid/fiware-orion/issues/3007 is merged into master branch, @@ -190,22 +194,25 @@ describe('NGSI-v2 - IoT Agent Device Update Registration', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/registrations', utils.readExampleFile('./test/unit/ngsiv2/examples' + - '/contextAvailabilityRequests/updateIoTAgent1.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); - + .post( + '/v2/registrations', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/updateIoTAgent1.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); }); - it('should register as ContextProvider of its lazy attributes', function(done) { - iotAgentLib.updateRegister(deviceUpdated, function(error) { + it('should register as ContextProvider of its lazy attributes', function (done) { + iotAgentLib.updateRegister(deviceUpdated, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); - it('should store the new values in the registry', function(done) { - iotAgentLib.updateRegister(deviceUpdated, function(error, data) { - iotAgentLib.getDevice(deviceUpdated.id, 'smartGondor', 'gardens', function(error, deviceResult) { + it('should store the new values in the registry', function (done) { + iotAgentLib.updateRegister(deviceUpdated, function (error, data) { + iotAgentLib.getDevice(deviceUpdated.id, 'smartGondor', 'gardens', function (error, deviceResult) { should.not.exist(error); should.exist(deviceResult); deviceResult.internalId.should.equal(deviceUpdated.internalId); @@ -217,15 +224,16 @@ describe('NGSI-v2 - IoT Agent Device Update Registration', function() { }); }); - describe('When a device is preregistered and it is updated with new commands', function() { - beforeEach(function() { - + describe('When a device is preregistered and it is updated with new commands', function () { + beforeEach(function () { delete deviceCommandUpdated.registrationId; contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/entities/Light:light1/attrs?type=Light', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateProvisionCommands1.json')) + .post( + '/v2/entities/Light:light1/attrs?type=Light', + utils.readExampleFile('./test/unit/ngsiv2/examples/contextRequests/updateProvisionCommands1.json') + ) .reply(204); // FIXME: When https://github.com/telefonicaid/fiware-orion/issues/3007 is merged into master branch, @@ -241,21 +249,28 @@ describe('NGSI-v2 - IoT Agent Device Update Registration', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v2/registrations', utils.readExampleFile('./test/unit/ngsiv2/examples' + - '/contextAvailabilityRequests/updateCommands1.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .post( + '/v2/registrations', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/updateCommands1.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); }); - it('should register as ContextProvider of its commands and create the additional attributes', function(done) { - iotAgentLib.updateRegister(deviceCommandUpdated, function(error) { + it('should register as ContextProvider of its commands and create the additional attributes', function (done) { + iotAgentLib.updateRegister(deviceCommandUpdated, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); - it('should store the new values in the registry', function(done) { - iotAgentLib.updateRegister(deviceCommandUpdated, function(error, data) { - iotAgentLib.getDevice(deviceCommandUpdated.id, 'smartGondor', 'gardens', function(error, deviceResult) { + it('should store the new values in the registry', function (done) { + iotAgentLib.updateRegister(deviceCommandUpdated, function (error, data) { + iotAgentLib.getDevice(deviceCommandUpdated.id, 'smartGondor', 'gardens', function ( + error, + deviceResult + ) { should.not.exist(error); should.exist(deviceResult); deviceResult.internalId.should.equal(deviceUpdated.internalId); @@ -267,25 +282,21 @@ describe('NGSI-v2 - IoT Agent Device Update Registration', function() { }); }); - describe('When a update action is executed in a non registered device', function() { - - it('should return a DEVICE_NOT_FOUND error', function(done) { - iotAgentLib.updateRegister(unknownDevice, function(error) { + describe('When a update action is executed in a non registered device', function () { + it('should return a DEVICE_NOT_FOUND error', function (done) { + iotAgentLib.updateRegister(unknownDevice, function (error) { should.exist(error); error.name.should.equal('DEVICE_NOT_FOUND'); done(); }); }); }); - describe('When a device register is updated in the Context Broker and the request fail to connect', function() { - beforeEach(function() { - + describe('When a device register is updated in the Context Broker and the request fail to connect', function () { + beforeEach(function () { // FIXME: When https://github.com/telefonicaid/fiware-orion/issues/3007 is merged into master branch, // this function should use the new API. This is just a temporary solution which implies deleting the // registration and creating a new one. - contextBrokerMock - .delete('/v2/registrations/6319a7f5254b05844116584d') - .reply(500, {}); + contextBrokerMock.delete('/v2/registrations/6319a7f5254b05844116584d').reply(500, {}); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') @@ -294,15 +305,15 @@ describe('NGSI-v2 - IoT Agent Device Update Registration', function() { .reply(204); }); - it('should return a REGISTRATION_ERROR error in the update action', function(done) { - iotAgentLib.updateRegister(deviceUpdated, function(error) { + it('should return a REGISTRATION_ERROR error in the update action', function (done) { + iotAgentLib.updateRegister(deviceUpdated, function (error) { should.exist(error); error.name.should.equal('UNREGISTRATION_ERROR'); done(); }); }); }); - describe('When a device register is updated in the Context Broker and the registration is not found', function() { + describe('When a device register is updated in the Context Broker and the registration is not found', function () { it('should create the registration anew'); }); }); diff --git a/test/unit/ngsiv2/provisioning/listProvisionedDevices-test.js b/test/unit/ngsiv2/provisioning/listProvisionedDevices-test.js index f8b89a70c..31db6727d 100644 --- a/test/unit/ngsiv2/provisioning/listProvisionedDevices-test.js +++ b/test/unit/ngsiv2/provisioning/listProvisionedDevices-test.js @@ -23,41 +23,39 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ - /* jshint camelcase: false */ - -'use strict'; - -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - should = require('should'), - nock = require('nock'), - async = require('async'), - request = require('request'), - contextBrokerMock, - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041, - baseRoot: '/' - }, - types: {}, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' - }; - -describe('NGSI-v2 - Device provisioning API: List provisioned devices', function() { - var provisioning1Options, - provisioning2Options, - provisioning3Options, - provisioning4Options; - - beforeEach(function(done) { +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const nock = require('nock'); +const async = require('async'); +const request = require('request'); +let contextBrokerMock; +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041, + baseRoot: '/' + }, + types: {}, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; + +describe('NGSI-v2 - Device provisioning API: List provisioned devices', function () { + let provisioning1Options; + let provisioning2Options; + let provisioning3Options; + let provisioning4Options; + + beforeEach(function (done) { provisioning1Options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', @@ -88,57 +86,54 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionFullDevice.json') }; - iotAgentLib.activate(iotAgentConfig, function() { + iotAgentLib.activate(iotAgentConfig, function () { contextBrokerMock = nock('http://192.168.1.1:1026') .post('/v2/registrations') - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under // provisioning folder - contextBrokerMock - .post('/v2/entities?options=upsert') - .reply(204); + contextBrokerMock.post('/v2/entities?options=upsert').reply(204); contextBrokerMock .post('/v2/registrations') - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under // provisioning folder - contextBrokerMock - .post('/v2/entities?options=upsert') - .reply(204); + contextBrokerMock.post('/v2/entities?options=upsert').reply(204); contextBrokerMock .post('/v2/registrations') - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under // provisioning folder - contextBrokerMock - .post('/v2/entities?options=upsert') - .reply(204); - - async.series([ - iotAgentLib.clearAll, - async.apply(request, provisioning1Options), - async.apply(request, provisioning2Options), - async.apply(request, provisioning4Options) - ], function(error, results) { - done(); - }); + contextBrokerMock.post('/v2/entities?options=upsert').reply(204); + + async.series( + [ + iotAgentLib.clearAll, + async.apply(request, provisioning1Options), + async.apply(request, provisioning2Options), + async.apply(request, provisioning4Options) + ], + function (error, results) { + done(); + } + ); }); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); }); - describe('When a request for the list of provisioned devices arrive', function() { - var options = { + describe('When a request for the list of provisioned devices arrive', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', headers: { 'fiware-service': 'smartGondor', @@ -147,9 +142,9 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function method: 'GET' }; - it('should return all the provisioned devices', function(done) { - request(options, function(error, response, body) { - var parsedBody = JSON.parse(body); + it('should return all the provisioned devices', function (done) { + request(options, function (error, response, body) { + const parsedBody = JSON.parse(body); should.not.exist(error); should.exist(parsedBody.devices); response.statusCode.should.equal(200); @@ -159,11 +154,11 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function }); }); - it('should return all the appropriate field names', function(done) { + it('should return all the appropriate field names', function (done) { /* jshint camelcase:false */ - request(options, function(error, response, body) { - var parsedBody = JSON.parse(body); + request(options, function (error, response, body) { + const parsedBody = JSON.parse(body); should.exist(parsedBody.devices[0].attributes); parsedBody.devices[0].attributes.length.should.equal(1); @@ -184,10 +179,9 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function }); }); - it('should return all the plugin attributes', function(done) { - request(options, function(error, response, body) { - var parsedBody = JSON.parse(body); - + it('should return all the plugin attributes', function (done) { + request(options, function (error, response, body) { + const parsedBody = JSON.parse(body); should.exist(parsedBody.devices[2].attributes[0].entity_name); should.exist(parsedBody.devices[2].attributes[0].entity_type); @@ -201,8 +195,8 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function }); }); }); - describe('When a request for the information about a specific device arrives', function() { - var options = { + describe('When a request for the information about a specific device arrives', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', headers: { 'fiware-service': 'smartGondor', @@ -211,31 +205,23 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function method: 'GET' }; - it('should return all the information on that particular device', function(done) { - request(options, function(error, response, body) { - /* jshint camelcase:false */ - - var parsedBody; - + it('should return all the information on that particular device', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(200); - parsedBody = JSON.parse(body); + const parsedBody = JSON.parse(body); parsedBody.entity_name.should.equal('TheFirstLight'); parsedBody.device_id.should.equal('Light1'); done(); }); }); - it('should return the appropriate attribute fields', function(done) { - request(options, function(error, response, body) { - /* jshint camelcase:false */ - - var parsedBody; - + it('should return the appropriate attribute fields', function (done) { + request(options, function (error, response, body) { should.not.exist(error); - parsedBody = JSON.parse(body); + const parsedBody = JSON.parse(body); should.exist(parsedBody.attributes[0].object_id); parsedBody.attributes[0].object_id.should.equal('attr_name'); parsedBody.attributes[0].name.should.equal('attr_name'); @@ -244,8 +230,8 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function }); }); }); - describe('When a request for a device with plugin attributes arrives', function() { - var options = { + describe('When a request for a device with plugin attributes arrives', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/LightFull', headers: { 'fiware-service': 'smartGondor', @@ -254,15 +240,11 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function method: 'GET' }; - it('should return the appropriate attribute fields', function(done) { - request(options, function(error, response, body) { - /* jshint camelcase:false */ - - var parsedBody; - + it('should return the appropriate attribute fields', function (done) { + request(options, function (error, response, body) { should.not.exist(error); - parsedBody = JSON.parse(body); + const parsedBody = JSON.parse(body); should.exist(parsedBody.attributes[0].entity_name); should.exist(parsedBody.attributes[0].entity_type); should.exist(parsedBody.attributes[1].expression); @@ -275,8 +257,8 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function }); }); }); - describe('When a request for an unexistent device arrives', function() { - var options = { + describe('When a request for an unexistent device arrives', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light84', headers: { 'fiware-service': 'smartGondor', @@ -285,8 +267,8 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function method: 'GET' }; - it('should return a 404 error', function(done) { - request(options, function(error, response, body) { + it('should return a 404 error', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(404); done(); @@ -294,8 +276,8 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function }); }); - describe('When a request for listing all the devices with a limit of 3 arrives', function() { - var options = { + describe('When a request for listing all the devices with a limit of 3 arrives', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices?limit=3', headers: { 'fiware-service': 'smartGondor', @@ -307,7 +289,7 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function function createDeviceRequest(i, callback) { /* jshint camelcase: false */ - var provisioningDeviceOptions = { + const provisioningDeviceOptions = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', headers: { @@ -323,7 +305,7 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function request(provisioningDeviceOptions, callback); } - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') @@ -331,35 +313,32 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function .matchHeader('fiware-servicepath', '/gardens') .post('/v2/registrations') .times(10) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under // provisioning folder - contextBrokerMock - .post('/v2/entities?options=upsert') - .times(10) - .reply(204); + contextBrokerMock.post('/v2/entities?options=upsert').times(10).reply(204); - iotAgentLib.clearAll(function() { - async.times(10, createDeviceRequest, function(error, results) { + iotAgentLib.clearAll(function () { + async.times(10, createDeviceRequest, function (error, results) { done(); }); }); }); - it('should return just 3 devices', function(done) { - request(options, function(error, response, body) { - var parsedBody = JSON.parse(body); + it('should return just 3 devices', function (done) { + request(options, function (error, response, body) { + const parsedBody = JSON.parse(body); should.not.exist(error); parsedBody.devices.length.should.equal(3); done(); }); }); - it('should return a count with the complete number of devices', function(done) { - request(options, function(error, response, body) { - var parsedBody = JSON.parse(body); + it('should return a count with the complete number of devices', function (done) { + request(options, function (error, response, body) { + const parsedBody = JSON.parse(body); should.not.exist(error); parsedBody.count.should.equal(10); done(); @@ -367,8 +346,8 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function }); }); - describe('When a request for listing all the devices with a offset of 3 arrives', function() { - var options = { + describe('When a request for listing all the devices with a offset of 3 arrives', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices?offset=3', headers: { 'fiware-service': 'smartGondor', @@ -378,7 +357,7 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function }; function createDeviceRequest(i, callback) { - var provisioningDeviceOptions = { + const provisioningDeviceOptions = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', headers: { @@ -391,12 +370,12 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function provisioningDeviceOptions.json.devices[0].device_id = provisioningDeviceOptions.json.devices[0].device_id + '_' + i; - request(provisioningDeviceOptions, function(error, response, body) { + request(provisioningDeviceOptions, function (error, response, body) { callback(); }); } - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') @@ -404,21 +383,21 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function .matchHeader('fiware-servicepath', '/gardens') .post('/v2/registrations') .times(10) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); - iotAgentLib.clearAll(function() { - async.timesSeries(10, createDeviceRequest, function(error, results) { + iotAgentLib.clearAll(function () { + async.timesSeries(10, createDeviceRequest, function (error, results) { done(); }); }); }); - it('should skip the first 3 devices', function(done) { - request(options, function(error, response, body) { - var parsedBody = JSON.parse(body); + it('should skip the first 3 devices', function (done) { + request(options, function (error, response, body) { + const parsedBody = JSON.parse(body); should.not.exist(error); - for (var i = 0; i < parsedBody.devices.length; i++) { + for (let i = 0; i < parsedBody.devices.length; i++) { ['Light1_0', 'Light1_1', 'Light1_2'].indexOf(parsedBody.devices[i].id).should.equal(-1); } @@ -427,8 +406,8 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function }); }); - describe('When a listing request arrives and there are devices in other service and servicepath', function() { - var options = { + describe('When a listing request arrives and there are devices in other service and servicepath', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', headers: { 'fiware-service': 'smartGondor', @@ -437,7 +416,7 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function method: 'GET' }; - beforeEach(function(done) { + beforeEach(function (done) { provisioning3Options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', @@ -446,21 +425,22 @@ describe('NGSI-v2 - Device provisioning API: List provisioned devices', function 'fiware-servicepath': '/gardens' }, json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionYetAnotherDevice.json') + './test/unit/examples/deviceProvisioningRequests/provisionYetAnotherDevice.json' + ) }; contextBrokerMock .post('/v2/registrations') - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); - request(provisioning3Options, function(error) { + request(provisioning3Options, function (error) { done(); }); }); - it('should return just the ones in the selected service', function(done) { - request(options, function(error, response, body) { - var parsedBody = JSON.parse(body); + it('should return just the ones in the selected service', function (done) { + request(options, function (error, response, body) { + const parsedBody = JSON.parse(body); should.not.exist(error); response.statusCode.should.equal(200); parsedBody.devices.length.should.equal(3); diff --git a/test/unit/ngsiv2/provisioning/provisionDeviceMultientity-test.js b/test/unit/ngsiv2/provisioning/provisionDeviceMultientity-test.js index 2c2750cd7..760feb4ee 100644 --- a/test/unit/ngsiv2/provisioning/provisionDeviceMultientity-test.js +++ b/test/unit/ngsiv2/provisioning/provisionDeviceMultientity-test.js @@ -22,90 +22,96 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), +/* eslint-disable no-unused-vars */ - should = require('should'), - nock = require('nock'), - request = require('request'), - contextBrokerMock, - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041, - baseRoot: '/' - }, - types: {}, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' - }; +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const nock = require('nock'); +const request = require('request'); +let contextBrokerMock; +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041, + baseRoot: '/' + }, + types: {}, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; -describe('NGSI-v2 - Device provisioning API: Provision devices', function() { - beforeEach(function(done) { +describe('NGSI-v2 - Device provisioning API: Provision devices', function () { + beforeEach(function (done) { nock.cleanAll(); - iotAgentLib.activate(iotAgentConfig, function() { + iotAgentLib.activate(iotAgentConfig, function () { iotAgentLib.clearAll(done); }); }); - afterEach(function(done) { + afterEach(function (done) { nock.cleanAll(); iotAgentLib.setProvisioningHandler(); iotAgentLib.deactivate(done); }); - describe('When a device provisioning request with all the required data arrives to the IoT Agent', function() { - beforeEach(function() { + describe('When a device provisioning request with all the required data arrives to the IoT Agent', function () { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/registrations', utils.readExampleFile('./test/unit/ngsiv2/examples' + - '/contextAvailabilityRequests/registerProvisionedDevice.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .post( + '/v2/registrations', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerProvisionedDevice.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/createProvisionedDeviceMultientity.json')) + .post( + '/v2/entities?options=upsert', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/createProvisionedDeviceMultientity.json' + ) + ) .reply(204); }); - var options = { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', - json: utils.readExampleFile('./test/unit/examples/' + - 'deviceProvisioningRequests/provisionNewDeviceMultientity.json'), + json: utils.readExampleFile( + './test/unit/examples/deviceProvisioningRequests/provisionNewDeviceMultientity.json' + ), headers: { 'fiware-service': 'smartGondor', 'fiware-servicepath': '/gardens' } }; - it('should add the device to the devices list', function(done) { - request(options, function(error, response, body) { + it('should add the device to the devices list', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(201); - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { results.devices.length.should.equal(1); done(); }); }); }); - }); }); - - diff --git a/test/unit/ngsiv2/provisioning/removeProvisionedDevice-test.js b/test/unit/ngsiv2/provisioning/removeProvisionedDevice-test.js index b6104b4e0..3c6297f14 100644 --- a/test/unit/ngsiv2/provisioning/removeProvisionedDevice-test.js +++ b/test/unit/ngsiv2/provisioning/removeProvisionedDevice-test.js @@ -22,71 +22,72 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - should = require('should'), - nock = require('nock'), - async = require('async'), - request = require('request'), - contextBrokerMock, - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041, - baseRoot: '/' + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const nock = require('nock'); +const async = require('async'); +const request = require('request'); +let contextBrokerMock; +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041, + baseRoot: '/' + }, + types: {}, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; + +describe('NGSI-v2 - Device provisioning API: Remove provisioned devices', function () { + const provisioning1Options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' }, - types: {}, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json') }; - -describe('NGSI-v2 - Device provisioning API: Remove provisioned devices', function() { - var provisioning1Options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - }, - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json') + const provisioning2Options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' }, - provisioning2Options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - }, - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionAnotherDevice.json') + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionAnotherDevice.json') + }; + const provisioning3Options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' }, - provisioning3Options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - }, - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/' + - 'provisionDeviceActiveAtts.json') - }; + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionDeviceActiveAtts.json') + }; - beforeEach(function(done) { - iotAgentLib.activate(iotAgentConfig, function() { - var nockBody = utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerProvisionedDevice.json'); + beforeEach(function (done) { + iotAgentLib.activate(iotAgentConfig, function () { + const nockBody = utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerProvisionedDevice.json' + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v2/registrations', nockBody) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under @@ -97,13 +98,14 @@ describe('NGSI-v2 - Device provisioning API: Remove provisioned devices', functi .post('/v2/entities?options=upsert') .reply(204); - var nockBody2 = utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerProvisionedDevice2.json'); + const nockBody2 = utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerProvisionedDevice2.json' + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v2/registrations', nockBody2) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under @@ -129,23 +131,26 @@ describe('NGSI-v2 - Device provisioning API: Remove provisioned devices', functi .post('/v2/entities?options=upsert') .reply(204); - async.series([ - iotAgentLib.clearAll, - async.apply(request, provisioning1Options), - async.apply(request, provisioning2Options), - async.apply(request, provisioning3Options) - ], function(error, results) { - done(); - }); + async.series( + [ + iotAgentLib.clearAll, + async.apply(request, provisioning1Options), + async.apply(request, provisioning2Options), + async.apply(request, provisioning3Options) + ], + function (error, results) { + done(); + } + ); }); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); }); - describe('When a request to remove a provision device arrives', function() { - var options = { + describe('When a request to remove a provision device arrives', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', headers: { 'fiware-service': 'smartGondor', @@ -154,17 +159,17 @@ describe('NGSI-v2 - Device provisioning API: Remove provisioned devices', functi method: 'DELETE' }; - it('should return a 200 OK and no errors', function(done) { - request(options, function(error, response, body) { + it('should return a 200 OK and no errors', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(204); done(); }); }); - it('should remove the device from the provisioned devices list', function(done) { - request(options, function(error, response, body) { - var options = { + it('should remove the device from the provisioned devices list', function (done) { + request(options, function (error, response, body) { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', headers: { 'fiware-service': 'smartGondor', @@ -173,17 +178,17 @@ describe('NGSI-v2 - Device provisioning API: Remove provisioned devices', functi method: 'GET' }; - request(options, function(error, response, body) { - var parsedBody = JSON.parse(body); + request(options, function (error, response, body) { + const parsedBody = JSON.parse(body); parsedBody.devices.length.should.equal(2); done(); }); }); }); - it('should return a 404 error when asking for the particular device', function(done) { - request(options, function(error, response, body) { - var options = { + it('should return a 404 error when asking for the particular device', function (done) { + request(options, function (error, response, body) { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', headers: { 'fiware-service': 'smartGondor', @@ -192,7 +197,7 @@ describe('NGSI-v2 - Device provisioning API: Remove provisioned devices', functi method: 'GET' }; - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(404); done(); @@ -200,23 +205,23 @@ describe('NGSI-v2 - Device provisioning API: Remove provisioned devices', functi }); }); - it('should call the device remove handler if present', function(done) { - var handlerCalled = false; + it('should call the device remove handler if present', function (done) { + let handlerCalled = false; - iotAgentLib.setRemoveDeviceHandler(function(device, callback) { + iotAgentLib.setRemoveDeviceHandler(function (device, callback) { handlerCalled = true; callback(null, device); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { handlerCalled.should.equal(true); done(); }); }); }); - describe('When a request to remove a provision device arrives. Device without lazy atts or commands', function() { - var options = { + describe('When a request to remove a provision device arrives. Device without lazy atts or commands', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light3', headers: { 'fiware-service': 'smartGondor', @@ -225,8 +230,8 @@ describe('NGSI-v2 - Device provisioning API: Remove provisioned devices', functi method: 'DELETE' }; - it('should return a 200 OK and no errors', function(done) { - request(options, function(error, response, body) { + it('should return a 200 OK and no errors', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(204); done(); diff --git a/test/unit/ngsiv2/provisioning/singleConfigurationMode-test.js b/test/unit/ngsiv2/provisioning/singleConfigurationMode-test.js index 3b0bad02a..db09313e4 100644 --- a/test/unit/ngsiv2/provisioning/singleConfigurationMode-test.js +++ b/test/unit/ngsiv2/provisioning/singleConfigurationMode-test.js @@ -22,70 +22,68 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -/* jshint camelcase: false */ - -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - - should = require('should'), - nock = require('nock'), - contextBrokerMock, - request = require('request'), - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041, - baseRoot: '/' - }, - types: {}, - service: 'smartGondor', - singleConfigurationMode: true, - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const nock = require('nock'); +let contextBrokerMock; +const request = require('request'); +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' }, - groupCreation = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionFullGroup.json'), - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - } + server: { + port: 4041, + baseRoot: '/' }, - deviceCreation = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json'), - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - } - }; - -describe('NGSI-v2 - Provisioning API: Single service mode', function() { - beforeEach(function(done) { + types: {}, + service: 'smartGondor', + singleConfigurationMode: true, + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; +const groupCreation = { + url: 'http://localhost:4041/iot/services', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionFullGroup.json'), + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } +}; +const deviceCreation = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json'), + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } +}; + +describe('NGSI-v2 - Provisioning API: Single service mode', function () { + beforeEach(function (done) { nock.cleanAll(); - iotAgentLib.activate(iotAgentConfig, function() { + iotAgentLib.activate(iotAgentConfig, function () { iotAgentLib.clearAll(done); }); }); - afterEach(function(done) { + afterEach(function (done) { nock.cleanAll(); iotAgentLib.setProvisioningHandler(); iotAgentLib.deactivate(done); }); - describe('When a new configuration arrives to an already configured subservice', function() { - var groupCreationDuplicated = { + describe('When a new configuration arrives to an already configured subservice', function () { + const groupCreationDuplicated = { url: 'http://localhost:4041/iot/services', method: 'POST', json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionDuplicateGroup.json'), @@ -95,12 +93,12 @@ describe('NGSI-v2 - Provisioning API: Single service mode', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { request(groupCreation, done); }); - it('should raise a DUPLICATE_GROUP error', function(done) { - request(groupCreationDuplicated, function(error, response, body) { + it('should raise a DUPLICATE_GROUP error', function (done) { + request(groupCreationDuplicated, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(409); should.exist(body.name); @@ -109,8 +107,8 @@ describe('NGSI-v2 - Provisioning API: Single service mode', function() { }); }); }); - describe('When a device is provisioned with an ID that already exists in the configuration', function() { - var deviceCreationDuplicated = { + describe('When a device is provisioned with an ID that already exists in the configuration', function () { + const deviceCreationDuplicated = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionDuplicatedDev.json'), @@ -120,14 +118,14 @@ describe('NGSI-v2 - Provisioning API: Single service mode', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://unexistentHost:1026') .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') .post('/v2/registrations') - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under @@ -138,15 +136,15 @@ describe('NGSI-v2 - Provisioning API: Single service mode', function() { .post('/v2/entities?options=upsert') .reply(204); - request(groupCreation, function(error) { - request(deviceCreation, function(error, response, body) { + request(groupCreation, function (error) { + request(deviceCreation, function (error, response, body) { done(); }); }); }); - it('should raise a DUPLICATE_DEVICE_ID error', function(done) { - request(deviceCreationDuplicated, function(error, response, body) { + it('should raise a DUPLICATE_DEVICE_ID error', function (done) { + request(deviceCreationDuplicated, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(409); should.exist(body.name); @@ -155,34 +153,34 @@ describe('NGSI-v2 - Provisioning API: Single service mode', function() { }); }); }); - describe('When a device is provisioned with an ID that exists globally but not in the configuration', function() { - var alternativeDeviceCreation = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json'), - headers: { - 'fiware-service': 'AlternateService', - 'fiware-servicepath': '/testingPath' - } - }, - alternativeGroupCreation = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionFullGroup.json'), - headers: { - 'fiware-service': 'AlternateService', - 'fiware-servicepath': '/testingPath' - } - }; - - beforeEach(function(done) { + describe('When a device is provisioned with an ID that exists globally but not in the configuration', function () { + const alternativeDeviceCreation = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json'), + headers: { + 'fiware-service': 'AlternateService', + 'fiware-servicepath': '/testingPath' + } + }; + const alternativeGroupCreation = { + url: 'http://localhost:4041/iot/services', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionFullGroup.json'), + headers: { + 'fiware-service': 'AlternateService', + 'fiware-servicepath': '/testingPath' + } + }; + + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') .post('/v2/registrations') - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under @@ -197,7 +195,7 @@ describe('NGSI-v2 - Provisioning API: Single service mode', function() { .matchHeader('fiware-service', 'AlternateService') .matchHeader('fiware-servicepath', '/testingPath') .post('/v2/registrations') - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under @@ -208,42 +206,42 @@ describe('NGSI-v2 - Provisioning API: Single service mode', function() { .post('/v2/entities?options=upsert') .reply(204); - request(groupCreation, function(error) { - request(deviceCreation, function(error, response, body) { - request(alternativeGroupCreation, function(error, response, body) { + request(groupCreation, function (error) { + request(deviceCreation, function (error, response, body) { + request(alternativeGroupCreation, function (error, response, body) { done(); }); }); }); }); - it('should return a 201 OK', function(done) { - request(alternativeDeviceCreation, function(error, response, body) { + it('should return a 201 OK', function (done) { + request(alternativeDeviceCreation, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(201); done(); }); }); }); - describe('When a device is provisioned without a type and with a default configuration type', function() { - var getDevice = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', - method: 'GET', - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - } - }, - oldType; - - beforeEach(function(done) { + describe('When a device is provisioned without a type and with a default configuration type', function () { + const getDevice = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', + method: 'GET', + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } + }; + let oldType; + + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://unexistentHost:1026') .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') .post('/v2/registrations') - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under @@ -259,16 +257,14 @@ describe('NGSI-v2 - Provisioning API: Single service mode', function() { request(groupCreation, done); }); - afterEach(function() { + afterEach(function () { deviceCreation.json.devices[0].entity_type = oldType; }); - it('should be provisioned with the default type', function(done) { - request(deviceCreation, function(error, response, body) { - request(getDevice, function(error, response, body) { - var parsedBody; - - parsedBody = JSON.parse(body); + it('should be provisioned with the default type', function (done) { + request(deviceCreation, function (error, response, body) { + request(getDevice, function (error, response, body) { + const parsedBody = JSON.parse(body); parsedBody.entity_type.should.equal('SensorMachine'); @@ -277,40 +273,48 @@ describe('NGSI-v2 - Provisioning API: Single service mode', function() { }); }); }); - describe('When a device is provisioned for a configuration', function() { - beforeEach(function(done) { + describe('When a device is provisioned for a configuration', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://unexistentHost:1026') .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') - .post('/v2/registrations', utils.readExampleFile('./test/unit/ngsiv2/examples' + - '/contextAvailabilityRequests/registerProvisionedDeviceWithGroup.json')) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .post( + '/v2/registrations', + utils.readExampleFile( + './test/unit/ngsiv2/examples' + + '/contextAvailabilityRequests/registerProvisionedDeviceWithGroup.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); contextBrokerMock .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') - .post('/v2/entities?options=upsert', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/createProvisionedDeviceWithGroupAndStatic.json')) + .post( + '/v2/entities?options=upsert', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/createProvisionedDeviceWithGroupAndStatic.json' + ) + ) .reply(204); request(groupCreation, done); }); - it('should not raise any error', function(done) { - request(deviceCreation, function(error, response, body) { + it('should not raise any error', function (done) { + request(deviceCreation, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(201); done(); }); }); - it('should send the mixed data to the Context Broker', function(done) { - request(deviceCreation, function(error, response, body) { + it('should send the mixed data to the Context Broker', function (done) { + request(deviceCreation, function (error, response, body) { contextBrokerMock.done(); done(); }); }); - }); }); diff --git a/test/unit/ngsiv2/provisioning/updateProvisionedDevices-test.js b/test/unit/ngsiv2/provisioning/updateProvisionedDevices-test.js index 1f347ef3f..4edcd914a 100644 --- a/test/unit/ngsiv2/provisioning/updateProvisionedDevices-test.js +++ b/test/unit/ngsiv2/provisioning/updateProvisionedDevices-test.js @@ -22,80 +22,82 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var iotAgentLib = require('../../../../lib/fiware-iotagent-lib'), - utils = require('../../../tools/utils'), - should = require('should'), - nock = require('nock'), - async = require('async'), - request = require('request'), - contextBrokerMock, - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026', - ngsiVersion: 'v2' - }, - server: { - port: 4041, - baseRoot: '/' + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../../lib/fiware-iotagent-lib'); +const utils = require('../../../tools/utils'); +const should = require('should'); +const nock = require('nock'); +const async = require('async'); +const request = require('request'); +let contextBrokerMock; +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026', + ngsiVersion: 'v2' + }, + server: { + port: 4041, + baseRoot: '/' + }, + types: {}, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com' +}; + +describe('NGSI-v2 - Device provisioning API: Update provisioned devices', function () { + const provisioning1Options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' }, - types: {}, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com' + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json') }; - -describe('NGSI-v2 - Device provisioning API: Update provisioned devices', function() { - var provisioning1Options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - }, - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json') + const provisioning2Options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' }, - provisioning2Options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - }, - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionAnotherDevice.json') + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionAnotherDevice.json') + }; + const provisioning3Options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' }, - provisioning3Options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - }, - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice2.json') + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice2.json') + }; + const provisioning4Options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' }, - provisioning4Options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - }, - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionExplicitAttrs.json') - }; + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionExplicitAttrs.json') + }; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); - iotAgentLib.activate(iotAgentConfig, function() { - var nockBody = utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerProvisionedDevice.json'); + iotAgentLib.activate(iotAgentConfig, function () { + const nockBody = utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerProvisionedDevice.json' + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v2/registrations', nockBody) - .reply(201, null, {'Location': '/v2/registrations/6319a7f5254b05844116584d'}); + .reply(201, null, { Location: '/v2/registrations/6319a7f5254b05844116584d' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under @@ -106,14 +108,15 @@ describe('NGSI-v2 - Device provisioning API: Update provisioned devices', functi .post('/v2/entities?options=upsert') .reply(204); - var nockBody2 = utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerProvisionedDevice2.json'); + const nockBody2 = utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/registerProvisionedDevice2.json' + ); nockBody2.expires = /.+/i; contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v2/registrations', nockBody2) - .reply(201, null, {'Location': '/v2/registrations/6719a7f5254b058441165849'}); + .reply(201, null, { Location: '/v2/registrations/6719a7f5254b058441165849' }); // This mock does not check the payload since the aim of the test is not to verify // device provisioning functionality. Appropriate verification is done in tests under @@ -121,7 +124,7 @@ describe('NGSI-v2 - Device provisioning API: Update provisioned devices', functi contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities?options=upsert') + .post('/v2/entities?options=upsert') .reply(204); // FIXME: When https://github.com/telefonicaid/fiware-orion/issues/3007 is merged into master branch, @@ -133,31 +136,35 @@ describe('NGSI-v2 - Device provisioning API: Update provisioned devices', functi .delete('/v2/registrations/6719a7f5254b058441165849') .reply(204); - var nockBody3 = utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/updateIoTAgent2.json'); + const nockBody3 = utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/updateIoTAgent2.json' + ); nockBody3.expires = /.+/i; contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v2/registrations', nockBody3) - .reply(201, null, {'Location': '/v2/registrations/4419a7f5254b058441165849'}); - - async.series([ - iotAgentLib.clearAll, - async.apply(request, provisioning1Options), - async.apply(request, provisioning2Options) - ], done); + .reply(201, null, { Location: '/v2/registrations/4419a7f5254b058441165849' }); + + async.series( + [ + iotAgentLib.clearAll, + async.apply(request, provisioning1Options), + async.apply(request, provisioning2Options) + ], + done + ); }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When a request to update a provision device arrives', function() { - var optionsUpdate = { + describe('When a request to update a provision device arrives', function () { + const optionsUpdate = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', method: 'PUT', headers: { @@ -167,7 +174,7 @@ describe('NGSI-v2 - Device provisioning API: Update provisioned devices', functi json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/updateProvisionDevice.json') }; - beforeEach(function() { + beforeEach(function () { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') @@ -187,31 +194,37 @@ describe('NGSI-v2 - Device provisioning API: Update provisioned devices', functi contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/registrations', - utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/updateIoTAgent2.json')) - .reply(201, null, {'Location': '/v2/registrations/4419a7f5254b058441165849'}); + .post( + '/v2/registrations', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/updateIoTAgent2.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/4419a7f5254b058441165849' }); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/registrations', - utils.readExampleFile( - './test/unit/ngsiv2/examples/contextAvailabilityRequests/updateIoTAgent3.json')) - .reply(201, null, {'Location': '/v2/registrations/4419a7f52546658441165849'}); + .post( + '/v2/registrations', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextAvailabilityRequests/updateIoTAgent3.json' + ) + ) + .reply(201, null, { Location: '/v2/registrations/4419a7f52546658441165849' }); }); - it('should return a 200 OK and no errors', function(done) { - request(optionsUpdate, function(error, response, body) { + it('should return a 200 OK and no errors', function (done) { + request(optionsUpdate, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(204); done(); }); }); - it('should have updated the data when asking for the particular device', function(done) { - request(optionsUpdate, function(error, response, body) { - var options = { + it('should have updated the data when asking for the particular device', function (done) { + request(optionsUpdate, function (error, response, body) { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', headers: { 'fiware-service': 'smartGondor', @@ -220,10 +233,10 @@ describe('NGSI-v2 - Device provisioning API: Update provisioned devices', functi method: 'GET' }; - request(options, function(error, response, body) { + request(options, function (error, response, body) { /* jshint camelcase:false */ - var parsedBody = JSON.parse(body); + const parsedBody = JSON.parse(body); parsedBody.entity_name.should.equal('ANewLightName'); parsedBody.timezone.should.equal('Europe/Madrid'); done(); @@ -231,9 +244,9 @@ describe('NGSI-v2 - Device provisioning API: Update provisioned devices', functi }); }); - it('should not modify the attributes not present in the update request', function(done) { - request(optionsUpdate, function(error, response, body) { - var options = { + it('should not modify the attributes not present in the update request', function (done) { + request(optionsUpdate, function (error, response, body) { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', headers: { 'fiware-service': 'smartGondor', @@ -242,10 +255,10 @@ describe('NGSI-v2 - Device provisioning API: Update provisioned devices', functi method: 'GET' }; - request(options, function(error, response, body) { + request(options, function (error, response, body) { /* jshint camelcase:false */ - var parsedBody = JSON.parse(body); + const parsedBody = JSON.parse(body); parsedBody.entity_type.should.equal('TheLightType'); parsedBody.service.should.equal('smartGondor'); done(); @@ -253,8 +266,8 @@ describe('NGSI-v2 - Device provisioning API: Update provisioned devices', functi }); }); }); - describe('When an update request arrives with a new Device ID', function() { - var optionsUpdate = { + describe('When an update request arrives with a new Device ID', function () { + const optionsUpdate = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', method: 'PUT', headers: { @@ -262,19 +275,20 @@ describe('NGSI-v2 - Device provisioning API: Update provisioned devices', functi 'fiware-servicepath': '/gardens' }, json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/updateProvisionDeviceWithId.json') + './test/unit/examples/deviceProvisioningRequests/updateProvisionDeviceWithId.json' + ) }; - it('should raise a 400 error', function(done) { - request(optionsUpdate, function(error, response, body) { + it('should raise a 400 error', function (done) { + request(optionsUpdate, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(400); done(); }); }); }); - describe('When a wrong update request payload arrives', function() { - var optionsUpdate = { + describe('When a wrong update request payload arrives', function () { + const optionsUpdate = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', method: 'PUT', headers: { @@ -282,11 +296,12 @@ describe('NGSI-v2 - Device provisioning API: Update provisioned devices', functi 'fiware-servicepath': '/gardens' }, json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/updateProvisionDeviceWrong.json') + './test/unit/examples/deviceProvisioningRequests/updateProvisionDeviceWrong.json' + ) }; - it('should raise a 400 error', function(done) { - request(optionsUpdate, function(error, response, body) { + it('should raise a 400 error', function (done) { + request(optionsUpdate, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(400); done(); @@ -294,26 +309,26 @@ describe('NGSI-v2 - Device provisioning API: Update provisioned devices', functi }); }); - describe('When a device is provisioned without attributes and new ones are added through an update', function() { - var optionsUpdate = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/MicroLight2', - method: 'PUT', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - }, - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/updateMinimumDevice.json') + describe('When a device is provisioned without attributes and new ones are added through an update', function () { + const optionsUpdate = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/MicroLight2', + method: 'PUT', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' }, - optionsGetDevice = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/MicroLight2', - method: 'GET', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }; - - beforeEach(function(done) { + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/updateMinimumDevice.json') + }; + const optionsGetDevice = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/MicroLight2', + method: 'GET', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + + beforeEach(function (done) { nock.cleanAll(); // This mock does not check the payload since the aim of the test is not to verify @@ -328,31 +343,31 @@ describe('NGSI-v2 - Device provisioning API: Update provisioned devices', functi contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/SecondMicroLight/attrs?type=MicroLights', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateProvisionMinimumDevice.json')) + .post( + '/v2/entities/SecondMicroLight/attrs?type=MicroLights', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateProvisionMinimumDevice.json' + ) + ) .reply(204); - async.series([ - iotAgentLib.clearAll, - async.apply(request, provisioning3Options) - ], done); + async.series([iotAgentLib.clearAll, async.apply(request, provisioning3Options)], done); }); - it('should not raise any error', function(done) { - request(optionsUpdate, function(error, response, body) { + it('should not raise any error', function (done) { + request(optionsUpdate, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(204); done(); }); }); - it('should provision the attributes appropriately', function(done) { - request(optionsUpdate, function(error, response, body) { - request(optionsGetDevice, function(error, response, body) { - var parsedBody; + it('should provision the attributes appropriately', function (done) { + request(optionsUpdate, function (error, response, body) { + request(optionsGetDevice, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(200); - parsedBody = JSON.parse(body); + const parsedBody = JSON.parse(body); parsedBody.attributes.length.should.equal(1); parsedBody.attributes[0].name.should.equal('newAttribute'); @@ -360,8 +375,8 @@ describe('NGSI-v2 - Device provisioning API: Update provisioned devices', functi }); }); }); - it('should create the initial values for the attributes in the Context Broker', function(done) { - request(optionsUpdate, function(error, response, body) { + it('should create the initial values for the attributes in the Context Broker', function (done) { + request(optionsUpdate, function (error, response, body) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -369,28 +384,28 @@ describe('NGSI-v2 - Device provisioning API: Update provisioned devices', functi }); }); - describe('When a device is updated to add static attributes', function() { + describe('When a device is updated to add static attributes', function () { /* jshint camelcase: false */ - var optionsUpdate = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/MicroLight2', - method: 'PUT', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - }, - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/updateDeviceStatic.json') + const optionsUpdate = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/MicroLight2', + method: 'PUT', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' }, - optionsGetDevice = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/MicroLight2', - method: 'GET', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }; - - beforeEach(function(done) { + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/updateDeviceStatic.json') + }; + const optionsGetDevice = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/MicroLight2', + method: 'GET', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + + beforeEach(function (done) { nock.cleanAll(); // This mock does not check the payload since the aim of the test is not to verify @@ -405,24 +420,24 @@ describe('NGSI-v2 - Device provisioning API: Update provisioned devices', functi contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/SecondMicroLight/attrs?type=MicroLights', utils.readExampleFile( - './test/unit/ngsiv2/examples/contextRequests/updateProvisionDeviceStatic.json')) + .post( + '/v2/entities/SecondMicroLight/attrs?type=MicroLights', + utils.readExampleFile( + './test/unit/ngsiv2/examples/contextRequests/updateProvisionDeviceStatic.json' + ) + ) .reply(204); - async.series([ - iotAgentLib.clearAll, - async.apply(request, provisioning3Options) - ], done); + async.series([iotAgentLib.clearAll, async.apply(request, provisioning3Options)], done); }); - it('should provision the attributes appropriately', function(done) { - request(optionsUpdate, function(error, response, body) { - request(optionsGetDevice, function(error, response, body) { - var parsedBody; + it('should provision the attributes appropriately', function (done) { + request(optionsUpdate, function (error, response, body) { + request(optionsGetDevice, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(200); - parsedBody = JSON.parse(body); + const parsedBody = JSON.parse(body); parsedBody.static_attributes.length.should.equal(3); parsedBody.static_attributes[0].name.should.equal('cellID'); @@ -431,29 +446,30 @@ describe('NGSI-v2 - Device provisioning API: Update provisioned devices', functi }); }); }); - describe('When a device is updated to update explicitAttrs', function() { + describe('When a device is updated to update explicitAttrs', function () { /* jshint camelcase: false */ - var optionsUpdate = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/xxx014', - method: 'PUT', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - }, - json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/updateDeviceExplicitAttrs.json') + const optionsUpdate = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/xxx014', + method: 'PUT', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' }, - optionsGetDevice = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/xxx014', - method: 'GET', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }; - - beforeEach(function(done) { + json: utils.readExampleFile( + './test/unit/examples/deviceProvisioningRequests/updateDeviceExplicitAttrs.json' + ) + }; + const optionsGetDevice = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/xxx014', + method: 'GET', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + + beforeEach(function (done) { nock.cleanAll(); // This mock does not check the payload since the aim of the test is not to verify @@ -465,20 +481,16 @@ describe('NGSI-v2 - Device provisioning API: Update provisioned devices', functi .post('/v2/entities?options=upsert') .reply(204); - async.series([ - iotAgentLib.clearAll, - async.apply(request, provisioning4Options) - ], done); + async.series([iotAgentLib.clearAll, async.apply(request, provisioning4Options)], done); }); it('should provision the explicitAttrs attribute appropriately', function (done) { request(optionsUpdate, function (error, response, body) { request(optionsGetDevice, function (error, response, body) { - var parsedBody; should.not.exist(error); response.statusCode.should.equal(200); - parsedBody = JSON.parse(body); + const parsedBody = JSON.parse(body); parsedBody.explicitAttrs.should.equal(false); done(); }); diff --git a/test/unit/plugins/alias-plugin_test.js b/test/unit/plugins/alias-plugin_test.js index 035bc1f35..80cb4ab31 100644 --- a/test/unit/plugins/alias-plugin_test.js +++ b/test/unit/plugins/alias-plugin_test.js @@ -20,61 +20,58 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; -/* jshint camelcase: false */ +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + object_id: 't', + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm' + }, + { + object_id: 'l', + name: 'luminance', + type: 'lumens' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - object_id: 't', - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm' - }, - { - object_id: 'l', - name: 'luminance', - type: 'lumens' - } - ] - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }; - -describe('Attribute alias plugin', function() { - beforeEach(function(done) { +describe('Attribute alias plugin', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.attributeAlias.update); iotAgentLib.addQueryMiddleware(iotAgentLib.dataPlugins.attributeAlias.query); done(); @@ -82,13 +79,13 @@ describe('Attribute alias plugin', function() { }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When an update comes for attributes with aliases', function() { - var values = [ + describe('When an update comes for attributes with aliases', function () { + const values = [ { name: 't', type: 'centigrades', @@ -101,28 +98,32 @@ describe('Attribute alias plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextAliasPlugin.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextAliasPluginSuccess.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextAliasPlugin.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/updateContextAliasPluginSuccess.json') + ); }); - it('should rename the attributes as expected by the mappings', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should rename the attributes as expected by the mappings', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); }); - describe('When an update comes for attributes with aliases and a different type', function() { - var values = [ + describe('When an update comes for attributes with aliases and a different type', function () { + const values = [ { name: 'l', type: 'lums', @@ -130,20 +131,24 @@ describe('Attribute alias plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextAliasPlugin2.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextAliasPlugin2Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextAliasPlugin2.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/updateContextAliasPlugin2Success.json') + ); }); - it('should rename the attributes as expected by the mappings', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should rename the attributes as expected by the mappings', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); diff --git a/test/unit/plugins/bidirectional-plugin_test.js b/test/unit/plugins/bidirectional-plugin_test.js index 471df057f..6ec1cbe37 100644 --- a/test/unit/plugins/bidirectional-plugin_test.js +++ b/test/unit/plugins/bidirectional-plugin_test.js @@ -21,103 +21,114 @@ * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - request = require('request'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }; - -describe('NGSI-v1 - Bidirectional data plugin', function() { - var options = { +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +const request = require('request'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; + +describe('NGSI-v1 - Bidirectional data plugin', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', - json: - utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionBidirectionalDevice.json'), + json: utils.readExampleFile( + './test/unit/examples/deviceProvisioningRequests/provisionBidirectionalDevice.json' + ), headers: { 'fiware-service': 'smartGondor', 'fiware-servicepath': '/gardens' } }; - beforeEach(function(done) { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { - iotAgentLib.addDeviceProvisionMiddleware( - iotAgentLib.dataPlugins.bidirectionalData.deviceProvision); + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { + iotAgentLib.addDeviceProvisionMiddleware(iotAgentLib.dataPlugins.bidirectionalData.deviceProvision); iotAgentLib.addConfigurationProvisionMiddleware( - iotAgentLib.dataPlugins.bidirectionalData.groupProvision); - iotAgentLib.addNotificationMiddleware( - iotAgentLib.dataPlugins.bidirectionalData.notification); + iotAgentLib.dataPlugins.bidirectionalData.groupProvision + ); + iotAgentLib.addNotificationMiddleware(iotAgentLib.dataPlugins.bidirectionalData.notification); done(); }); }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When a new provisioning request arrives to the IoTA with bidirectionality', function() { - beforeEach(function() { + describe('When a new provisioning request arrives to the IoTA with bidirectionality', function () { + beforeEach(function () { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/subscribeContext', utils.readExampleFile( - './test/unit/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/subscriptionResponses/bidirectionalSubscriptionSuccess.json')); + .post( + '/v1/subscribeContext', + utils.readExampleFile( + './test/unit/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json' + ) + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/subscriptionResponses/bidirectionalSubscriptionSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/createBidirectionalDevice.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createBidirectionalDeviceSuccess.json')); - + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/createBidirectionalDevice.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createBidirectionalDeviceSuccess.json') + ); }); - it('should subscribe to the modification of the combined attribute with all the variables', function(done) { - request(options, function(error, response, body) { + it('should subscribe to the modification of the combined attribute with all the variables', function (done) { + request(options, function (error, response, body) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -125,8 +136,8 @@ describe('NGSI-v1 - Bidirectional data plugin', function() { }); }); - describe('When a device with bidirectionality subscriptions is removed', function() { - var deleteRequest = { + describe('When a device with bidirectionality subscriptions is removed', function () { + const deleteRequest = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', method: 'DELETE', headers: { @@ -135,35 +146,53 @@ describe('NGSI-v1 - Bidirectional data plugin', function() { } }; - beforeEach(function() { + beforeEach(function () { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/subscribeContext', utils.readExampleFile( - './test/unit/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/subscriptionResponses/bidirectionalSubscriptionSuccess.json')); + .post( + '/v1/subscribeContext', + utils.readExampleFile( + './test/unit/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json' + ) + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/subscriptionResponses/bidirectionalSubscriptionSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/createBidirectionalDevice.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createBidirectionalDeviceSuccess.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/createBidirectionalDevice.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createBidirectionalDeviceSuccess.json') + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/unsubscribeContext', utils.readExampleFile( - './test/unit/examples/subscriptionRequests/simpleSubscriptionRemove.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/subscriptionResponses/bidirectionalSubscriptionSuccess.json')); + .post( + '/v1/unsubscribeContext', + utils.readExampleFile('./test/unit/examples/subscriptionRequests/simpleSubscriptionRemove.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/subscriptionResponses/bidirectionalSubscriptionSuccess.json' + ) + ); }); - it('should remove its subscriptions from the Context Broker', function(done) { - request(options, function(error, response, body) { - request(deleteRequest, function(error, response, body) { + it('should remove its subscriptions from the Context Broker', function (done) { + request(options, function (error, response, body) { + request(deleteRequest, function (error, response, body) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -172,49 +201,67 @@ describe('NGSI-v1 - Bidirectional data plugin', function() { }); }); - describe('When a notification arrives for a bidirectional attribute', function() { - var notificationOptions = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/subscriptionRequests/bidirectionalNotification.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - executedHandler = false; + describe('When a notification arrives for a bidirectional attribute', function () { + const notificationOptions = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/subscriptionRequests/bidirectionalNotification.json'), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + let executedHandler = false; - beforeEach(function() { + beforeEach(function () { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/subscribeContext', utils.readExampleFile( - './test/unit/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/subscriptionResponses/bidirectionalSubscriptionSuccess.json')); + .post( + '/v1/subscribeContext', + utils.readExampleFile( + './test/unit/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json' + ) + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/subscriptionResponses/bidirectionalSubscriptionSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/createBidirectionalDevice.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createBidirectionalDeviceSuccess.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/createBidirectionalDevice.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createBidirectionalDeviceSuccess.json') + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/unsubscribeContext', utils.readExampleFile( - './test/unit/examples/subscriptionRequests/simpleSubscriptionRemove.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/subscriptionResponses/bidirectionalSubscriptionSuccess.json')); + .post( + '/v1/unsubscribeContext', + utils.readExampleFile('./test/unit/examples/subscriptionRequests/simpleSubscriptionRemove.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/subscriptionResponses/bidirectionalSubscriptionSuccess.json' + ) + ); }); - afterEach(function() { + afterEach(function () { iotAgentLib.setNotificationHandler(); }); - it('should execute the original handler', function(done) { + it('should execute the original handler', function (done) { function mockedHandler(device, notification, callback) { executedHandler = true; callback(); @@ -222,15 +269,15 @@ describe('NGSI-v1 - Bidirectional data plugin', function() { iotAgentLib.setNotificationHandler(mockedHandler); - request(options, function(error, response, body) { - request(notificationOptions, function(error, response, body) { + request(options, function (error, response, body) { + request(notificationOptions, function (error, response, body) { executedHandler.should.equal(true); done(); }); }); }); - it('should return a 200 OK', function(done) { + it('should return a 200 OK', function (done) { function mockedHandler(device, notification, callback) { executedHandler = true; callback(); @@ -238,22 +285,22 @@ describe('NGSI-v1 - Bidirectional data plugin', function() { iotAgentLib.setNotificationHandler(mockedHandler); - request(options, function(error, response, body) { - request(notificationOptions, function(error, response, body) { + request(options, function (error, response, body) { + request(notificationOptions, function (error, response, body) { response.statusCode.should.equal(200); done(); }); }); }); - it('should return the transformed values', function(done) { - var transformedHandler = false; + it('should return the transformed values', function (done) { + let transformedHandler = false; function mockedHandler(device, values, callback) { - var latitudeFound = false, - longitudeFound = false; + let latitudeFound = false; + let longitudeFound = false; - for (var i = 0; i < values.length; i++) { + for (let i = 0; i < values.length; i++) { if (values[i].name === 'latitude' && values[i].type === 'string' && values[i].value === '-9.6') { latitudeFound = true; } @@ -263,14 +310,14 @@ describe('NGSI-v1 - Bidirectional data plugin', function() { } } - transformedHandler = (values.length >= 2 && longitudeFound && latitudeFound); + transformedHandler = values.length >= 2 && longitudeFound && latitudeFound; callback(); } iotAgentLib.setNotificationHandler(mockedHandler); - request(options, function(error, response, body) { - request(notificationOptions, function(error, response, body) { + request(options, function (error, response, body) { + request(notificationOptions, function (error, response, body) { transformedHandler.should.equal(true); done(); }); @@ -278,49 +325,60 @@ describe('NGSI-v1 - Bidirectional data plugin', function() { }); }); - describe('When a new Group provisioning request arrives with bidirectional attributes', function() { - var provisionGroup = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/services', - method: 'POST', - json: - utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/bidirectionalGroup.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - provisionDevice = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionDeviceBidirectionalGroup.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }; + describe('When a new Group provisioning request arrives with bidirectional attributes', function () { + const provisionGroup = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/services', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/bidirectionalGroup.json'), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + const provisionDevice = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile( + './test/unit/examples/deviceProvisioningRequests/provisionDeviceBidirectionalGroup.json' + ), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; - beforeEach(function() { + beforeEach(function () { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/subscribeContext', utils.readExampleFile( - './test/unit/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/subscriptionResponses/bidirectionalSubscriptionSuccess.json')); + .post( + '/v1/subscribeContext', + utils.readExampleFile( + './test/unit/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json' + ) + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/subscriptionResponses/bidirectionalSubscriptionSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/createBidirectionalDevice.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createBidirectionalDeviceSuccess.json')); - + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/createBidirectionalDevice.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createBidirectionalDeviceSuccess.json') + ); }); - it('should subscribe to the modification of the combined attribute with all the variables', function(done) { - request(provisionGroup, function(error, response, body) { - request(provisionDevice, function(error, response, body) { + it('should subscribe to the modification of the combined attribute with all the variables', function (done) { + request(provisionGroup, function (error, response, body) { + request(provisionDevice, function (error, response, body) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -329,68 +387,79 @@ describe('NGSI-v1 - Bidirectional data plugin', function() { }); }); - describe('When a notification arrives for a bidirectional attribute in a Configuration Group', function() { - var provisionGroup = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/services', - method: 'POST', - json: - utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/bidirectionalGroup.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - notificationOptions = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/subscriptionRequests/bidirectionalNotification.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - provisionDevice = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionDeviceBidirectionalGroup.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }; + describe('When a notification arrives for a bidirectional attribute in a Configuration Group', function () { + const provisionGroup = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/services', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/bidirectionalGroup.json'), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + const notificationOptions = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/notify', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/subscriptionRequests/bidirectionalNotification.json'), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + const provisionDevice = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile( + './test/unit/examples/deviceProvisioningRequests/provisionDeviceBidirectionalGroup.json' + ), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; - beforeEach(function() { + beforeEach(function () { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/subscribeContext', utils.readExampleFile( - './test/unit/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/subscriptionResponses/bidirectionalSubscriptionSuccess.json')); + .post( + '/v1/subscribeContext', + utils.readExampleFile( + './test/unit/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json' + ) + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/subscriptionResponses/bidirectionalSubscriptionSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/createBidirectionalDevice.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createBidirectionalDeviceSuccess.json')); - + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/createBidirectionalDevice.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createBidirectionalDeviceSuccess.json') + ); }); - afterEach(function() { + afterEach(function () { iotAgentLib.setNotificationHandler(); }); - it('should return the transformed values', function(done) { - var transformedHandler = false; + it('should return the transformed values', function (done) { + let transformedHandler = false; function mockedHandler(device, values, callback) { - var latitudeFound = false, - longitudeFound = false; + let latitudeFound = false; + let longitudeFound = false; - for (var i = 0; i < values.length; i++) { + for (let i = 0; i < values.length; i++) { if (values[i].name === 'latitude' && values[i].type === 'string' && values[i].value === '-9.6') { latitudeFound = true; } @@ -400,15 +469,15 @@ describe('NGSI-v1 - Bidirectional data plugin', function() { } } - transformedHandler = (values.length >= 2 && longitudeFound && latitudeFound); + transformedHandler = values.length >= 2 && longitudeFound && latitudeFound; callback(); } iotAgentLib.setNotificationHandler(mockedHandler); - request(provisionGroup, function(error, response, body) { - request(provisionDevice, function(error, response, body) { - request(notificationOptions, function(error, response, body) { + request(provisionGroup, function (error, response, body) { + request(provisionDevice, function (error, response, body) { + request(notificationOptions, function (error, response, body) { transformedHandler.should.equal(true); done(); }); @@ -418,63 +487,74 @@ describe('NGSI-v1 - Bidirectional data plugin', function() { }); }); -describe('Bidirectional data plugin and CB is defined using environment variables', function() { - var options = { +describe('Bidirectional data plugin and CB is defined using environment variables', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', - json: - utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionBidirectionalDevice.json'), + json: utils.readExampleFile( + './test/unit/examples/deviceProvisioningRequests/provisionBidirectionalDevice.json' + ), headers: { 'fiware-service': 'smartGondor', 'fiware-servicepath': '/gardens' } }; - beforeEach(function(done) { + beforeEach(function (done) { logger.setLevel('FATAL'); process.env.IOTA_CB_HOST = 'cbhost'; - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { - iotAgentLib.addDeviceProvisionMiddleware( - iotAgentLib.dataPlugins.bidirectionalData.deviceProvision); + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { + iotAgentLib.addDeviceProvisionMiddleware(iotAgentLib.dataPlugins.bidirectionalData.deviceProvision); iotAgentLib.addConfigurationProvisionMiddleware( - iotAgentLib.dataPlugins.bidirectionalData.groupProvision); - iotAgentLib.addNotificationMiddleware( - iotAgentLib.dataPlugins.bidirectionalData.notification); + iotAgentLib.dataPlugins.bidirectionalData.groupProvision + ); + iotAgentLib.addNotificationMiddleware(iotAgentLib.dataPlugins.bidirectionalData.notification); done(); }); }); }); - afterEach(function(done) { + afterEach(function (done) { process.env.IOTA_CB_HOST = ''; - iotAgentLib.clearAll(function() { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When a new provisioning request arrives to the IoTA with bidirectionality', function() { - beforeEach(function() { + describe('When a new provisioning request arrives to the IoTA with bidirectionality', function () { + beforeEach(function () { contextBrokerMock = nock('http://cbhost:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/subscribeContext', utils.readExampleFile( - './test/unit/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/subscriptionResponses/bidirectionalSubscriptionSuccess.json')); + .post( + '/v1/subscribeContext', + utils.readExampleFile( + './test/unit/examples/subscriptionRequests/bidirectionalSubscriptionRequest.json' + ) + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/subscriptionResponses/bidirectionalSubscriptionSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/createBidirectionalDevice.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createBidirectionalDeviceSuccess.json')); - + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/createBidirectionalDevice.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createBidirectionalDeviceSuccess.json') + ); }); - it('should subscribe to the modification of the combined attribute with all the variables', function(done) { - request(options, function(error, response, body) { + it('should subscribe to the modification of the combined attribute with all the variables', function (done) { + request(options, function (error, response, body) { should.not.exist(error); contextBrokerMock.done(); done(); diff --git a/test/unit/plugins/capture-configuration-inPlugins_test.js b/test/unit/plugins/capture-configuration-inPlugins_test.js index d244162cc..20534adf8 100644 --- a/test/unit/plugins/capture-configuration-inPlugins_test.js +++ b/test/unit/plugins/capture-configuration-inPlugins_test.js @@ -21,155 +21,152 @@ * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; - -/* jshint camelcase: false */ - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - should = require('should'), - logger = require('logops'), - request = require('request'), - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - type: 'Light', +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const should = require('should'); +const logger = require('logops'); +const request = require('request'); +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; +const optionsCreation = { + url: 'http://localhost:4041/iot/services', + method: 'POST', + json: { + services: [ + { + resource: '/deviceTest', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', + entity_type: 'SensorMachine', + trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', + cbHost: 'http://unexistentHost:1026', + commands: [ + { + name: 'wheel1', + type: 'Wheel' + } + ], lazy: [ { - name: 'temperature', - type: 'centigrades' + name: 'luminescence', + type: 'Lumens' } ], - active: [ + attributes: [ { - name: 'pressure', - type: 'Hgmm' + name: 'status', + type: 'Boolean' + } + ], + static_attributes: [ + { + name: 'bootstrapServer', + type: 'Address', + value: '127.0.0.1' } ] } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' + ] }, - optionsCreation = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: { - services: [ - { - resource: '/deviceTest', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', - entity_type: 'SensorMachine', - trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', - cbHost: 'http://unexistentHost:1026', - commands: [ - { - name: 'wheel1', - type: 'Wheel' - } - ], - lazy: [ - { - name: 'luminescence', - type: 'Lumens' - } - ], - attributes: [ - { - name: 'status', - type: 'Boolean' - } - ], - static_attributes: [ - { - name: 'bootstrapServer', - type: 'Address', - value: '127.0.0.1' - } - ] - } - ] - }, - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - } - }; - -describe('Data Mapping Plugins: configuration provision', function() { - beforeEach(function(done) { + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } +}; + +describe('Data Mapping Plugins: configuration provision', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfig, function(error) { + iotAgentLib.activate(iotAgentConfig, function (error) { iotAgentLib.clearAll(done); }); }); - - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When a configuration provision request arrives to a IoTA with configuration middleware', function() { - it('should execute the configuration provisioning middlewares', function(done) { - var handlerCalled = false; + describe('When a configuration provision request arrives to a IoTA with configuration middleware', function () { + it('should execute the configuration provisioning middlewares', function (done) { + let handlerCalled = false; - iotAgentLib.addConfigurationProvisionMiddleware(function(newConfiguration, callback) { + iotAgentLib.addConfigurationProvisionMiddleware(function (newConfiguration, callback) { handlerCalled = true; callback(null, newConfiguration); }); - request(optionsCreation, function(error, response, body) { + request(optionsCreation, function (error, response, body) { should.not.exist(error); handlerCalled.should.equal(true); done(); }); }); - it('should still execute the configuration handlers', function(done) { - var handlerCalled = false; + it('should still execute the configuration handlers', function (done) { + let handlerCalled = false; - iotAgentLib.addConfigurationProvisionMiddleware(function(newConfiguration, callback) { + iotAgentLib.addConfigurationProvisionMiddleware(function (newConfiguration, callback) { callback(null, newConfiguration); }); - iotAgentLib.setConfigurationHandler(function(newConfiguration, callback) { + iotAgentLib.setConfigurationHandler(function (newConfiguration, callback) { handlerCalled = true; callback(null, newConfiguration); }); - request(optionsCreation, function(error, response, body) { + request(optionsCreation, function (error, response, body) { handlerCalled.should.equal(true); done(); }); }); }); - describe('When a configuration middleware returns an error', function() { - it('should not execute the configuration handlers', function(done) { - var handlerCalled = false; + describe('When a configuration middleware returns an error', function () { + it('should not execute the configuration handlers', function (done) { + let handlerCalled = false; - iotAgentLib.addConfigurationProvisionMiddleware(function(newConfiguration, callback) { + iotAgentLib.addConfigurationProvisionMiddleware(function (newConfiguration, callback) { callback(new Error('This will prevent the handler from being executed')); }); - iotAgentLib.setConfigurationHandler(function(newConfiguration, callback) { + iotAgentLib.setConfigurationHandler(function (newConfiguration, callback) { handlerCalled = true; callback(null, newConfiguration); }); - request(optionsCreation, function(error, response, body) { + request(optionsCreation, function (error, response, body) { handlerCalled.should.equal(false); done(); }); diff --git a/test/unit/plugins/capture-provision-inPlugins_test.js b/test/unit/plugins/capture-provision-inPlugins_test.js index ad192f2ab..52e0b4d82 100644 --- a/test/unit/plugins/capture-provision-inPlugins_test.js +++ b/test/unit/plugins/capture-provision-inPlugins_test.js @@ -21,49 +21,49 @@ * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - request = require('request'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }; - -describe('Data Mapping Plugins: device provision', function() { - var options = { +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +const request = require('request'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; + +describe('Data Mapping Plugins: device provision', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json'), @@ -73,7 +73,7 @@ describe('Data Mapping Plugins: device provision', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { logger.setLevel('FATAL'); nock.cleanAll(); @@ -81,34 +81,43 @@ describe('Data Mapping Plugins: device provision', function() { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerProvisionedDevice.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerProvisionedDevice.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/createProvisionedDevice.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); - - iotAgentLib.activate(iotAgentConfig, function(error) { + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/createProvisionedDevice.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); + + iotAgentLib.activate(iotAgentConfig, function (error) { iotAgentLib.clearAll(done); }); }); - - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When a provision request arrives to a IoTA with provisioning middleware', function() { - it('should execute the translation middlewares', function(done) { - var executed = false; + describe('When a provision request arrives to a IoTA with provisioning middleware', function () { + it('should execute the translation middlewares', function (done) { + let executed = false; function testMiddleware(device, callback) { executed = true; @@ -117,28 +126,28 @@ describe('Data Mapping Plugins: device provision', function() { iotAgentLib.addDeviceProvisionMiddleware(testMiddleware); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); executed.should.equal(true); done(); }); }); - it('should continue with the registration process', function(done) { + it('should continue with the registration process', function (done) { function testMiddleware(device, callback) { callback(null, device); } iotAgentLib.addDeviceProvisionMiddleware(testMiddleware); - request(options, function(error, response, body) { + request(options, function (error, response, body) { contextBrokerMock.done(); done(); }); }); - it('should execute the device provisioning handlers', function(done) { - var executed = false; + it('should execute the device provisioning handlers', function (done) { + let executed = false; function testMiddleware(device, callback) { callback(null, device); @@ -152,30 +161,29 @@ describe('Data Mapping Plugins: device provision', function() { iotAgentLib.addDeviceProvisionMiddleware(testMiddleware); iotAgentLib.setProvisioningHandler(provisioningHandler); - request(options, function(error, response, body) { + request(options, function (error, response, body) { executed.should.equal(true); done(); }); - }); }); - describe('When a provisioning middleware returns an error', function() { - it('should not continue with the registration process', function(done) { + describe('When a provisioning middleware returns an error', function () { + it('should not continue with the registration process', function (done) { function testMiddleware(device, callback) { callback(new Error('This provisioning should not progress')); } iotAgentLib.addDeviceProvisionMiddleware(testMiddleware); - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.equal(contextBrokerMock.isDone(), false); done(); }); }); - it('should not execute the device provisioning handlers', function(done) { - var executed = false; + it('should not execute the device provisioning handlers', function (done) { + let executed = false; function testMiddleware(device, callback) { callback(new Error('This provisioning should not progress')); @@ -189,11 +197,10 @@ describe('Data Mapping Plugins: device provision', function() { iotAgentLib.addDeviceProvisionMiddleware(testMiddleware); iotAgentLib.setProvisioningHandler(provisioningHandler); - request(options, function(error, response, body) { + request(options, function (error, response, body) { executed.should.equal(false); done(); }); - }); }); }); diff --git a/test/unit/plugins/compress-timestamp-plugin_test.js b/test/unit/plugins/compress-timestamp-plugin_test.js index 699ed40d1..0ed645daf 100644 --- a/test/unit/plugins/compress-timestamp-plugin_test.js +++ b/test/unit/plugins/compress-timestamp-plugin_test.js @@ -21,109 +21,106 @@ * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - server: { - port: 4041 + BrokenLight: { + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'BrokenLight': { - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'Termometer': { - type: 'Termometer', - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ] - }, - 'Humidity': { - type: 'Humidity', - cbHost: 'http://192.168.1.1:3024', - commands: [], - lazy: [], - active: [ - { - name: 'humidity', - type: 'percentage' - } - ] - }, - 'Motion': { - type: 'Motion', - commands: [], - lazy: [], - staticAttributes: [ - { - 'name': 'location', - 'type': 'Vector', - 'value': '(123,523)' - } - ], - active: [ - { - name: 'humidity', - type: 'percentage' - } - ] - } + Termometer: { + type: 'Termometer', + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [] + }, + Humidity: { + type: 'Humidity', + cbHost: 'http://192.168.1.1:3024', + commands: [], + lazy: [], + active: [ + { + name: 'humidity', + type: 'percentage' + } + ] }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }; + Motion: { + type: 'Motion', + commands: [], + lazy: [], + staticAttributes: [ + { + name: 'location', + type: 'Vector', + value: '(123,523)' + } + ], + active: [ + { + name: 'humidity', + type: 'percentage' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; -describe('NGSI-v1 - Timestamp compression plugin', function() { - beforeEach(function(done) { +describe('NGSI-v1 - Timestamp compression plugin', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.compressTimestamp.update); iotAgentLib.addQueryMiddleware(iotAgentLib.dataPlugins.compressTimestamp.query); done(); @@ -131,13 +128,13 @@ describe('NGSI-v1 - Timestamp compression plugin', function() { }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When an update comes with a timestamp through the plugin', function() { - var values = [ + describe('When an update comes with a timestamp through the plugin', function () { + const values = [ { name: 'state', type: 'Boolean', @@ -150,20 +147,26 @@ describe('NGSI-v1 - Timestamp compression plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextCompressTimestamp1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextCompressTimestamp1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextCompressTimestamp1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextCompressTimestamp1Success.json' + ) + ); }); - it('should return an entity with all its timestamps expanded to have separators', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should return an entity with all its timestamps expanded to have separators', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -171,8 +174,8 @@ describe('NGSI-v1 - Timestamp compression plugin', function() { }); }); - describe('When an update comes with a timestamp through the plugin with metadatas', function() { - var values = [ + describe('When an update comes with a timestamp through the plugin with metadatas', function () { + const values = [ { name: 'state', type: 'Boolean', @@ -192,20 +195,26 @@ describe('NGSI-v1 - Timestamp compression plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextCompressTimestamp2.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextCompressTimestamp2Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextCompressTimestamp2.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextCompressTimestamp2Success.json' + ) + ); }); - it('should return an entity with all its timestamps expanded to have separators', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should return an entity with all its timestamps expanded to have separators', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -213,26 +222,29 @@ describe('NGSI-v1 - Timestamp compression plugin', function() { }); }); - describe('When a query comes for a timestamp through the plugin', function() { - var values = [ - 'state', - 'The Target Value' - ]; + describe('When a query comes for a timestamp through the plugin', function () { + const values = ['state', 'The Target Value']; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/queryContext', utils.readExampleFile( - './test/unit/examples/contextRequests/queryContextCompressTimestamp1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/queryContextCompressTimestamp1Success.json')); + .post( + '/v1/queryContext', + utils.readExampleFile('./test/unit/examples/contextRequests/queryContextCompressTimestamp1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/queryContextCompressTimestamp1Success.json' + ) + ); }); - it('should return an entity with all its timestamps without separators (basic format)', function(done) { - iotAgentLib.query('light1', 'Light', '', values, function(error, response) { + it('should return an entity with all its timestamps without separators (basic format)', function (done) { + iotAgentLib.query('light1', 'Light', '', values, function (error, response) { should.not.exist(error); should.exist(response); should.exist(response.contextResponses); diff --git a/test/unit/plugins/event-plugin_test.js b/test/unit/plugins/event-plugin_test.js index 69222e3bd..391427e5f 100644 --- a/test/unit/plugins/event-plugin_test.js +++ b/test/unit/plugins/event-plugin_test.js @@ -21,52 +21,50 @@ * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }; - -describe('NGSI-v1 - Event plugin', function() { - beforeEach(function(done) { +describe('NGSI-v1 - Event plugin', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.addEvents.update); iotAgentLib.addQueryMiddleware(iotAgentLib.dataPlugins.addEvents.query); done(); @@ -74,13 +72,13 @@ describe('NGSI-v1 - Event plugin', function() { }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When an update comes with an event to the plugin', function() { - var values = [ + describe('When an update comes with an event to the plugin', function () { + const values = [ { name: 'state', type: 'Boolean', @@ -93,23 +91,25 @@ describe('NGSI-v1 - Event plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', function(body) { - var dateRegex = /\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d.\d{3}Z/; + .post('/v1/updateContext', function (body) { + const dateRegex = /\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d.\d{3}Z/; return body.contextElements['0'].attributes['1'].value.match(dateRegex); }) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextEvents1Success.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/updateContextEvents1Success.json') + ); }); - it('should return an entity with all its timestamps expanded to have separators', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should return an entity with all its timestamps expanded to have separators', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); diff --git a/test/unit/plugins/multientity-plugin_test.js b/test/unit/plugins/multientity-plugin_test.js index 06ea97751..5be8ee5a9 100644 --- a/test/unit/plugins/multientity-plugin_test.js +++ b/test/unit/plugins/multientity-plugin_test.js @@ -20,93 +20,90 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; - -/* jshint camelcase: false */ - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + WeatherStation: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm' + }, + { + object_id: 'h', + name: 'humidity', + type: 'Percentage', + entity_name: 'Higro2000', + entity_type: 'Higrometer' + } + ] }, - types: { - 'WeatherStation': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm' - }, - { - object_id: 'h', - name: 'humidity', - type: 'Percentage', - entity_name: 'Higro2000', - entity_type: 'Higrometer' - } - ] - }, - 'WeatherStation2': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm' - }, - { - object_id: 'h', - name: 'humidity', - type: 'Percentage', - entity_name: 'Higro2000', - } - ] - }, - 'WeatherStation3': { - commands: [], - type: 'WeatherStation', - lazy: [], - active: [ - { - object_id: 'p', - name: 'pressure', - type: 'Hgmm' - }, - { - object_id: 'h', - name: 'humidity', - type: 'Percentage', - entity_name: 'Station Number ${@sn * 10}', - } - ] - } + WeatherStation2: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm' + }, + { + object_id: 'h', + name: 'humidity', + type: 'Percentage', + entity_name: 'Higro2000' + } + ] }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }; - -describe('NGSI-v1 - Multi-entity plugin', function() { - beforeEach(function(done) { + WeatherStation3: { + commands: [], + type: 'WeatherStation', + lazy: [], + active: [ + { + object_id: 'p', + name: 'pressure', + type: 'Hgmm' + }, + { + object_id: 'h', + name: 'humidity', + type: 'Percentage', + entity_name: 'Station Number ${@sn * 10}' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; + +describe('NGSI-v1 - Multi-entity plugin', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.attributeAlias.update); iotAgentLib.addQueryMiddleware(iotAgentLib.dataPlugins.attributeAlias.query); iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.multiEntity.update); @@ -115,14 +112,14 @@ describe('NGSI-v1 - Multi-entity plugin', function() { }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When an update comes for a multientity measurement', function() { - var values = [ + describe('When an update comes for a multientity measurement', function () { + const values = [ { name: 'p', type: 'centigrades', @@ -135,20 +132,26 @@ describe('NGSI-v1 - Multi-entity plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextMultientityPlugin1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextMultientityPlugin1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextMultientityPlugin1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextMultientityPlugin1Success.json' + ) + ); }); - it('should send two context elements, one for each entity', function(done) { - iotAgentLib.update('ws4', 'WeatherStation', '', values, function(error) { + it('should send two context elements, one for each entity', function (done) { + iotAgentLib.update('ws4', 'WeatherStation', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -156,11 +159,8 @@ describe('NGSI-v1 - Multi-entity plugin', function() { }); }); - - - - describe('When an update comes for a multientity defined with an expression', function() { - var values = [ + describe('When an update comes for a multientity defined with an expression', function () { + const values = [ { name: 'p', type: 'centigrades', @@ -178,20 +178,26 @@ describe('NGSI-v1 - Multi-entity plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextMultiEntityPlugin3.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextMultientityPlugin3Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextMultiEntityPlugin3.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextMultientityPlugin3Success.json' + ) + ); }); - it('should send the update value to the resulting value of the expression', function(done) { - iotAgentLib.update('ws4', 'WeatherStation3', '', values, function(error) { + it('should send the update value to the resulting value of the expression', function (done) { + iotAgentLib.update('ws4', 'WeatherStation3', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -199,9 +205,8 @@ describe('NGSI-v1 - Multi-entity plugin', function() { }); }); - - describe('When an update comes for a multientity measurement without type for one entity', function() { - var values = [ + describe('When an update comes for a multientity measurement without type for one entity', function () { + const values = [ { name: 'p', type: 'centigrades', @@ -214,20 +219,26 @@ describe('NGSI-v1 - Multi-entity plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextMultientityPlugin2.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextMultientityPlugin2Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextMultientityPlugin2.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextMultientityPlugin2Success.json' + ) + ); }); - it('should use the device type as a default value', function(done) { - iotAgentLib.update('ws4', 'WeatherStation2', '', values, function(error) { + it('should use the device type as a default value', function (done) { + iotAgentLib.update('ws4', 'WeatherStation2', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); diff --git a/test/unit/plugins/timestamp-processing-plugin_test.js b/test/unit/plugins/timestamp-processing-plugin_test.js index 2ad00aee3..46374d018 100644 --- a/test/unit/plugins/timestamp-processing-plugin_test.js +++ b/test/unit/plugins/timestamp-processing-plugin_test.js @@ -21,65 +21,63 @@ * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }; - -describe('NGSI-v1 - Timestamp processing plugin', function() { - beforeEach(function(done) { +describe('NGSI-v1 - Timestamp processing plugin', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfig, function() { - iotAgentLib.clearAll(function() { + iotAgentLib.activate(iotAgentConfig, function () { + iotAgentLib.clearAll(function () { iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.timestampProcess.update); done(); }); }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When an update comes with a timestamp through the plugin', function() { - var values = [ + describe('When an update comes with a timestamp through the plugin', function () { + const values = [ { name: 'state', type: 'Boolean', @@ -92,20 +90,26 @@ describe('NGSI-v1 - Timestamp processing plugin', function() { } ]; - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateContextProcessTimestamp1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateContextProcessTimestamp1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextProcessTimestamp1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextResponses/updateContextProcessTimestamp1Success.json' + ) + ); }); - it('should return an entity with all its timestamps expanded to have separators', function(done) { - iotAgentLib.update('light1', 'Light', '', values, function(error) { + it('should return an entity with all its timestamps expanded to have separators', function (done) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); diff --git a/test/unit/plugins/translation-inPlugins_test.js b/test/unit/plugins/translation-inPlugins_test.js index 620bf79cc..3450c4c1c 100644 --- a/test/unit/plugins/translation-inPlugins_test.js +++ b/test/unit/plugins/translation-inPlugins_test.js @@ -20,133 +20,134 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041 + }, + types: { + Light: { + commands: [], + type: 'Light', + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - server: { - port: 4041 + BrokenLight: { + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ] }, - types: { - 'Light': { - commands: [], - type: 'Light', - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'BrokenLight': { - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ] - }, - 'Termometer': { - type: 'Termometer', - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ] - }, - 'Humidity': { - type: 'Humidity', - cbHost: 'http://192.168.1.1:3024', - commands: [], - lazy: [], - active: [ - { - name: 'humidity', - type: 'percentage' - } - ] - }, - 'Motion': { - type: 'Motion', - commands: [], - lazy: [], - staticAttributes: [ - { - 'name': 'location', - 'type': 'Vector', - 'value': '(123,523)' - } - ], - active: [ - { - name: 'humidity', - type: 'percentage' - } - ] - } + Termometer: { + type: 'Termometer', + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [] }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }; + Humidity: { + type: 'Humidity', + cbHost: 'http://192.168.1.1:3024', + commands: [], + lazy: [], + active: [ + { + name: 'humidity', + type: 'percentage' + } + ] + }, + Motion: { + type: 'Motion', + commands: [], + lazy: [], + staticAttributes: [ + { + name: 'location', + type: 'Vector', + value: '(123,523)' + } + ], + active: [ + { + name: 'humidity', + type: 'percentage' + } + ] + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; -describe('Data Mapping Plugins: translation', function() { - beforeEach(function(done) { +describe('Data Mapping Plugins: translation', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); - iotAgentLib.activate(iotAgentConfig, function() { + iotAgentLib.activate(iotAgentConfig, function () { iotAgentLib.clearAll(done); }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When a new update translation middleware is added to the IoT Agent', function() { - beforeEach(function() { + describe('When a new update translation middleware is added to the IoT Agent', function () { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContextMiddleware1.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContextMiddleware1.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); }); - it('should execute the translation middlewares', function(done) { - var values = [ + it('should execute the translation middlewares', function (done) { + const values = [ { name: 'state', type: 'Boolean', @@ -159,7 +160,7 @@ describe('Data Mapping Plugins: translation', function() { } ]; - var executed = false; + let executed = false; function testMiddleware(entity, typeInformation, callback) { entity.contextElements[0].attributes[1].value = entity.contextElements[0].attributes[1].value + '%'; @@ -169,15 +170,15 @@ describe('Data Mapping Plugins: translation', function() { iotAgentLib.addUpdateMiddleware(testMiddleware); - iotAgentLib.update('light1', 'Light', '', values, function(error) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); executed.should.equal(true); done(); }); }); - it('should translate the appropriate attributes', function(done) { - var values = [ + it('should translate the appropriate attributes', function (done) { + const values = [ { name: 'state', type: 'Boolean', @@ -197,7 +198,7 @@ describe('Data Mapping Plugins: translation', function() { iotAgentLib.addUpdateMiddleware(testMiddleware); - iotAgentLib.update('light1', 'Light', '', values, function(error) { + iotAgentLib.update('light1', 'Light', '', values, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -205,27 +206,24 @@ describe('Data Mapping Plugins: translation', function() { }); }); + describe('When a new query translation middleware is added to the IoT Agent', function () { + const attributes = ['state', 'dimming']; - describe('When a new query translation middleware is added to the IoT Agent', function() { - var attributes = [ - 'state', - 'dimming' - ]; - - beforeEach(function() { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/queryContext', - utils.readExampleFile('./test/unit/examples/contextRequests/queryContext1.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/queryContext1Success.json')); + .post( + '/v1/queryContext', + utils.readExampleFile('./test/unit/examples/contextRequests/queryContext1.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/queryContext1Success.json')); }); - it('should call the middleware', function(done) { - var called = false; + it('should call the middleware', function (done) { + let called = false; function testMiddleware(entity, typeInformation, callback) { entity.contextResponses[0].contextElement.attributes[1].value = @@ -238,15 +236,14 @@ describe('Data Mapping Plugins: translation', function() { iotAgentLib.addQueryMiddleware(testMiddleware); - iotAgentLib.query('light1', 'Light', '', attributes, function(error, result) { + iotAgentLib.query('light1', 'Light', '', attributes, function (error, result) { should.not.exist(error); called.should.equal(true); done(); }); }); - it('should call the middleware', function(done) { - function testMiddleware(entity, typeInformation, - callback) { + it('should call the middleware', function (done) { + function testMiddleware(entity, typeInformation, callback) { entity.contextResponses[0].contextElement.attributes[1].value = entity.contextResponses[0].contextElement.attributes[1].value + '%'; @@ -255,7 +252,7 @@ describe('Data Mapping Plugins: translation', function() { iotAgentLib.addQueryMiddleware(testMiddleware); - iotAgentLib.query('light1', 'Light', '', attributes, function(error, result) { + iotAgentLib.query('light1', 'Light', '', attributes, function (error, result) { should.not.exist(error); result.contextResponses[0].contextElement.attributes[1].value.should.equal('23%'); done(); diff --git a/test/unit/provisioning/device-group-api-test.js b/test/unit/provisioning/device-group-api-test.js index 77a767518..df2bd7702 100644 --- a/test/unit/provisioning/device-group-api-test.js +++ b/test/unit/provisioning/device-group-api-test.js @@ -20,210 +20,208 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; - -/* jshint camelcase: false */ - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - _ = require('underscore'), - async = require('async'), - nock = require('nock'), - utils = require('../../tools/utils'), - groupRegistryMemory = require('../../../lib/services/groups/groupRegistryMemory'), - request = require('request'), - should = require('should'), - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - name: 'testAgent', - port: 4041, - baseRoot: '/' - }, - types: {}, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const _ = require('underscore'); +const async = require('async'); +const nock = require('nock'); +const utils = require('../../tools/utils'); +const groupRegistryMemory = require('../../../lib/services/groups/groupRegistryMemory'); +const request = require('request'); +const should = require('should'); +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026' }, - optionsCreation = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: { - services: [ - { - resource: '/deviceTest', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', - entity_type: 'SensorMachine', - trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', - cbHost: 'http://unexistentHost:1026', - commands: [ - { - name: 'wheel1', - type: 'Wheel' - } - ], - lazy: [ - { - name: 'luminescence', - type: 'Lumens' - } - ], - attributes: [ - { - name: 'status', - type: 'Boolean' - } - ], - static_attributes: [ - { - name: 'bootstrapServer', - type: 'Address', - value: '127.0.0.1' - } - ] - } - ] - }, - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - } + server: { + name: 'testAgent', + port: 4041, + baseRoot: '/' }, - optionsDeviceCreation = { - url: 'http://localhost:4041/iot/devices', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json'), - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - } + types: {}, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; +const optionsCreation = { + url: 'http://localhost:4041/iot/services', + method: 'POST', + json: { + services: [ + { + resource: '/deviceTest', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', + entity_type: 'SensorMachine', + trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', + cbHost: 'http://unexistentHost:1026', + commands: [ + { + name: 'wheel1', + type: 'Wheel' + } + ], + lazy: [ + { + name: 'luminescence', + type: 'Lumens' + } + ], + attributes: [ + { + name: 'status', + type: 'Boolean' + } + ], + static_attributes: [ + { + name: 'bootstrapServer', + type: 'Address', + value: '127.0.0.1' + } + ] + } + ] }, - optionsDelete = { - url: 'http://localhost:4041/iot/services', - method: 'DELETE', - json: {}, - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - }, - qs: { - resource: '/deviceTest', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732' - } + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } +}; +const optionsDeviceCreation = { + url: 'http://localhost:4041/iot/devices', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json'), + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } +}; +const optionsDelete = { + url: 'http://localhost:4041/iot/services', + method: 'DELETE', + json: {}, + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' }, - optionsDeleteDevice = { - url: 'http://localhost:4041/iot/services', - method: 'DELETE', - json: {}, - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - }, - qs: { - resource: '/deviceTest', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', - device: 'true' - } + qs: { + resource: '/deviceTest', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732' + } +}; +const optionsDeleteDevice = { + url: 'http://localhost:4041/iot/services', + method: 'DELETE', + json: {}, + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' }, - optionsUpdate = { - url: 'http://localhost:4041/iot/services', - method: 'PUT', - json: { - trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', - cbHost: 'http://anotherUnexistentHost:1026', - commands: [ - { - name: 'wheel1', - type: 'Wheel' - } - ], - lazy: [ - { - name: 'luminescence', - type: 'Lumens' - } - ], - attributes: [ - { - name: 'status', - type: 'Boolean' - } - ], - static_attributes: [ - { - name: 'identifier', - type: 'UUID', - value: 'WERTYUIOP234567890' - } - ] - }, - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - }, - qs: { - resource: '/deviceTest', - apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732' - } + qs: { + resource: '/deviceTest', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732', + device: 'true' + } +}; +const optionsUpdate = { + url: 'http://localhost:4041/iot/services', + method: 'PUT', + json: { + trust: '8970A9078A803H3BL98PINEQRW8342HBAMS', + cbHost: 'http://anotherUnexistentHost:1026', + commands: [ + { + name: 'wheel1', + type: 'Wheel' + } + ], + lazy: [ + { + name: 'luminescence', + type: 'Lumens' + } + ], + attributes: [ + { + name: 'status', + type: 'Boolean' + } + ], + static_attributes: [ + { + name: 'identifier', + type: 'UUID', + value: 'WERTYUIOP234567890' + } + ] }, - optionsList = { - url: 'http://localhost:4041/iot/services', - method: 'GET', - json: {}, - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/*' - } + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' }, - optionsGet = { - url: 'http://localhost:4041/iot/services', - method: 'GET', - json: {}, - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - } - }; - -describe('Device Group Configuration API', function() { - - beforeEach(function(done) { - iotAgentLib.activate(iotAgentConfig, function() { + qs: { + resource: '/deviceTest', + apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732' + } +}; +const optionsList = { + url: 'http://localhost:4041/iot/services', + method: 'GET', + json: {}, + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/*' + } +}; +const optionsGet = { + url: 'http://localhost:4041/iot/services', + method: 'GET', + json: {}, + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } +}; + +describe('Device Group Configuration API', function () { + beforeEach(function (done) { + iotAgentLib.activate(iotAgentConfig, function () { groupRegistryMemory.clear(done); }); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.setConfigurationHandler(); - iotAgentLib.deactivate(function() { + iotAgentLib.deactivate(function () { groupRegistryMemory.clear(done); }); }); - describe('When a new device group creation request arrives', function() { - it('should return a 200 OK', function(done) { - request(optionsCreation, function(error, response, body) { + describe('When a new device group creation request arrives', function () { + it('should return a 200 OK', function (done) { + request(optionsCreation, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(201); done(); }); }); - it('should store it in the DB', function(done) { - request(optionsCreation, function(error, response, body) { - request(optionsList, function(error, response, body) { + it('should store it in the DB', function (done) { + request(optionsCreation, function (error, response, body) { + request(optionsList, function (error, response, body) { body.count.should.equal(1); body.services[0].apikey.should.equal('801230BJKL23Y9090DSFL123HJK09H324HV8732'); done(); }); }); }); - it('should store attributes in the DB', function(done) { - request(optionsCreation, function(error, response, body) { - request(optionsList, function(error, response, body) { + it('should store attributes in the DB', function (done) { + request(optionsCreation, function (error, response, body) { + request(optionsList, function (error, response, body) { body.count.should.equal(1); should.exist(body.services[0].attributes); body.services[0].attributes.length.should.equal(1); @@ -245,9 +243,9 @@ describe('Device Group Configuration API', function() { }); }); }); - it('should store the service information from the headers into the DB', function(done) { - request(optionsCreation, function(error, response, body) { - request(optionsList, function(error, response, body) { + it('should store the service information from the headers into the DB', function (done) { + request(optionsCreation, function (error, response, body) { + request(optionsList, function (error, response, body) { body.count.should.equal(1); body.services[0].service.should.equal('TestService'); body.services[0].subservice.should.equal('/testingPath'); @@ -255,10 +253,10 @@ describe('Device Group Configuration API', function() { }); }); }); - it('should call the configuration creation handler', function(done) { - var handlerCalled = false; + it('should call the configuration creation handler', function (done) { + let handlerCalled = false; - iotAgentLib.setConfigurationHandler(function(newConfiguration, callback) { + iotAgentLib.setConfigurationHandler(function (newConfiguration, callback) { should.exist(newConfiguration); should.exist(callback); newConfiguration.apikey.should.equal('801230BJKL23Y9090DSFL123HJK09H324HV8732'); @@ -267,14 +265,14 @@ describe('Device Group Configuration API', function() { callback(); }); - request(optionsCreation, function(error, response, body) { + request(optionsCreation, function (error, response, body) { handlerCalled.should.equal(true); done(); }); }); }); - describe('When a new device group creation request arrives with explicitAttrs', function() { - var optionsCreation1 = { + describe('When a new device group creation request arrives with explicitAttrs', function () { + const optionsCreation1 = { url: 'http://localhost:4041/iot/services', method: 'POST', json: { @@ -294,16 +292,16 @@ describe('Device Group Configuration API', function() { 'fiware-servicepath': '/testingPath' } }; - it('should return a 200 OK', function(done) { - request(optionsCreation1, function(error, response, body) { + it('should return a 200 OK', function (done) { + request(optionsCreation1, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(201); done(); }); }); - it('should store it in the DB', function(done) { - request(optionsCreation1, function(error, response, body) { - request(optionsList, function(error, response, body) { + it('should store it in the DB', function (done) { + request(optionsCreation1, function (error, response, body) { + request(optionsList, function (error, response, body) { body.count.should.equal(1); body.services[0].apikey.should.equal('801230BJKL23Y9090DSFL123HJK09H324HV8732'); body.services[0].explicitAttrs.should.equal(true); @@ -312,10 +310,10 @@ describe('Device Group Configuration API', function() { }); }); }); - describe('When a new creation request arrives for a pair (resource, apiKey) already existant', function() { - it('should return a 400 DUPLICATE_GROUP error', function(done) { - request(optionsCreation, function(error, response, body) { - request(optionsCreation, function(error, response, body) { + describe('When a new creation request arrives for a pair (resource, apiKey) already existant', function () { + it('should return a 400 DUPLICATE_GROUP error', function (done) { + request(optionsCreation, function (error, response, body) { + request(optionsCreation, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(409); body.name.should.equal('DUPLICATE_GROUP'); @@ -324,17 +322,17 @@ describe('Device Group Configuration API', function() { }); }); }); - describe('When a creation request arrives without the fiware-service header', function() { - beforeEach(function() { + describe('When a creation request arrives without the fiware-service header', function () { + beforeEach(function () { delete optionsCreation.headers['fiware-service']; }); - afterEach(function() { + afterEach(function () { optionsCreation.headers['fiware-service'] = 'TestService'; }); - it('should fail with a 400 MISSING_HEADERS Error', function(done) { - request(optionsCreation, function(error, response, body) { + it('should fail with a 400 MISSING_HEADERS Error', function (done) { + request(optionsCreation, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(400); body.name.should.equal('MISSING_HEADERS'); @@ -342,17 +340,17 @@ describe('Device Group Configuration API', function() { }); }); }); - describe('When a creation request arrives without the fiware-servicepath header', function() { - beforeEach(function() { + describe('When a creation request arrives without the fiware-servicepath header', function () { + beforeEach(function () { delete optionsCreation.headers['fiware-servicepath']; }); - afterEach(function() { + afterEach(function () { optionsCreation.headers['fiware-servicepath'] = '/testingPath'; }); - it('should fail with a 400 MISSING_HEADERS Error', function(done) { - request(optionsCreation, function(error, response, body) { + it('should fail with a 400 MISSING_HEADERS Error', function (done) { + request(optionsCreation, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(400); body.name.should.equal('MISSING_HEADERS'); @@ -360,17 +358,17 @@ describe('Device Group Configuration API', function() { }); }); }); - describe('When a device group with a missing mandatory attribute in the payload arrives', function() { - beforeEach(function() { + describe('When a device group with a missing mandatory attribute in the payload arrives', function () { + beforeEach(function () { delete optionsCreation.json.services[0].resource; }); - afterEach(function() { + afterEach(function () { optionsCreation.json.services[0].resource = '/deviceTest'; }); - it('should fail with a 400 WRONG_SYNTAX error', function(done) { - request(optionsCreation, function(error, response, body) { + it('should fail with a 400 WRONG_SYNTAX error', function (done) { + request(optionsCreation, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(400); body.name.should.equal('WRONG_SYNTAX'); @@ -378,139 +376,166 @@ describe('Device Group Configuration API', function() { }); }); }); - describe('When a device group removal request arrives', function() { - beforeEach(function(done) { + describe('When a device group removal request arrives', function () { + beforeEach(function (done) { request(optionsCreation, done); }); - it('should return a 204 OK', function(done) { - request(optionsDelete, function(error, response, body) { + it('should return a 204 OK', function (done) { + request(optionsDelete, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(204); done(); }); }); - it('should remove it from the database', function(done) { - request(optionsDelete, function(error, response, body) { - request(optionsList, function(error, response, body) { + it('should remove it from the database', function (done) { + request(optionsDelete, function (error, response, body) { + request(optionsList, function (error, response, body) { body.count.should.equal(0); done(); }); }); }); - it('should remove it from the configuration', function(done) { - request(optionsDelete, function(error, response, body) { - /* jshint sub:true */ - - should.not.exist(iotAgentConfig.types['SensorMachine']); + it('should remove it from the configuration', function (done) { + request(optionsDelete, function (error, response, body) { + should.not.exist(iotAgentConfig.types.SensorMachine); done(); }); }); }); - describe('When a device group removal request arrives with device=true option', function() { - var contextBrokerMock; + describe('When a device group removal request arrives with device=true option', function () { + let contextBrokerMock; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/createProvisionedDevice.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/createProvisionedDevice.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); contextBrokerMock .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerProvisionedDevice.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile( + './test/unit/examples/contextAvailabilityRequests/registerProvisionedDevice.json' + ) + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/unregisterProvisionedDevice.json')) - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/unregisterDevice1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile( + './test/unit/examples/contextAvailabilityRequests/unregisterProvisionedDevice.json' + ) + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/unregisterDevice1Success.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/createProvisionedDevice.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); - - async.series([ - iotAgentLib.clearAll, - async.apply(request, optionsCreation), - async.apply(request, optionsDeviceCreation) - ], done); - }); - - it('should remove all associated devices', function(done) { - var options = { - url: 'http://localhost:4041/iot/devices/Light1', - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - }, - method: 'GET' - }; - - function test (error, response, body) { - response.statusCode.should.equal(404); - done(); - } - - async.series([ - async.apply(request, optionsDeleteDevice), - async.apply(request, options), - async.apply(request, options, test), - ], done); - }); - - it('should call the remove configuration handler', function(done) { - var handlerCalled = false; - - iotAgentLib.setRemoveConfigurationHandler(function(newConfiguration, callback) { + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/createProvisionedDevice.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); + + async.series( + [ + iotAgentLib.clearAll, + async.apply(request, optionsCreation), + async.apply(request, optionsDeviceCreation) + ], + done + ); + }); + + it('should remove all associated devices', function (done) { + const options = { + url: 'http://localhost:4041/iot/devices/Light1', + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + }, + method: 'GET' + }; + + function test(error, response, body) { + response.statusCode.should.equal(404); + done(); + } + + async.series( + [ + async.apply(request, optionsDeleteDevice), + async.apply(request, options), + async.apply(request, options, test) + ], + done + ); + }); + + it('should call the remove configuration handler', function (done) { + let handlerCalled = false; + + iotAgentLib.setRemoveConfigurationHandler(function (newConfiguration, callback) { should.exist(newConfiguration); should.exist(callback); handlerCalled = true; callback(); }); - request(optionsDeleteDevice, function(error, response, body) { + request(optionsDeleteDevice, function (error, response, body) { handlerCalled.should.equal(true); done(); }); }); - afterEach(function(done) { + afterEach(function (done) { nock.cleanAll(); done(); }); }); - describe('When a device group removal arrives declaring a different service', function() { - var optionsDeleteDifferentService = _.clone(optionsDelete); + describe('When a device group removal arrives declaring a different service', function () { + const optionsDeleteDifferentService = _.clone(optionsDelete); - beforeEach(function(done) { + beforeEach(function (done) { optionsDeleteDifferentService.headers['fiware-service'] = 'unexistentService'; request(optionsCreation, done); }); - afterEach(function(done) { + afterEach(function (done) { optionsDeleteDifferentService.headers['fiware-service'] = 'TestService'; done(); }); - it('should return a 403 MISMATCHED_SERVICE error', function(done) { - request(optionsDelete, function(error, response, body) { + it('should return a 403 MISMATCHED_SERVICE error', function (done) { + request(optionsDelete, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(403); body.name.should.equal('MISMATCHED_SERVICE'); @@ -519,21 +544,21 @@ describe('Device Group Configuration API', function() { }); }); - describe('When a device group removal arrives declaring a different subservice', function() { - var optionsDeleteDifferentService = _.clone(optionsDelete); + describe('When a device group removal arrives declaring a different subservice', function () { + const optionsDeleteDifferentService = _.clone(optionsDelete); - beforeEach(function(done) { + beforeEach(function (done) { optionsDeleteDifferentService.headers['fiware-servicepath'] = '/unexistentSubservice'; request(optionsCreation, done); }); - afterEach(function(done) { + afterEach(function (done) { optionsDeleteDifferentService.headers['fiware-servicepath'] = '/testingPath'; done(); }); - it('should return a 403 MISMATCHED_SERVICE error', function(done) { - request(optionsDelete, function(error, response, body) { + it('should return a 403 MISMATCHED_SERVICE error', function (done) { + request(optionsDelete, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(403); body.name.should.equal('MISMATCHED_SERVICE'); @@ -541,12 +566,12 @@ describe('Device Group Configuration API', function() { }); }); }); - - describe('When a device group removal arrives to a DB with three groups', function() { - beforeEach(function(done) { - var optionsCreation1 = _.clone(optionsCreation), - optionsCreation2 = _.clone(optionsCreation), - optionsCreation3 = _.clone(optionsCreation); + + describe('When a device group removal arrives to a DB with three groups', function () { + beforeEach(function (done) { + const optionsCreation1 = _.clone(optionsCreation); + const optionsCreation2 = _.clone(optionsCreation); + const optionsCreation3 = _.clone(optionsCreation); optionsCreation1.json = { services: [] }; optionsCreation3.json = { services: [] }; @@ -557,19 +582,22 @@ describe('Device Group Configuration API', function() { optionsCreation1.json.services[0].apikey = 'qwertyuiop'; optionsCreation3.json.services[0].apikey = 'lkjhgfds'; - async.series([ - async.apply(request, optionsCreation1), - async.apply(request, optionsCreation2), - async.apply(request, optionsCreation3) - ], done); + async.series( + [ + async.apply(request, optionsCreation1), + async.apply(request, optionsCreation2), + async.apply(request, optionsCreation3) + ], + done + ); }); - it('should remove just the selected group', function(done) { - request(optionsDelete, function(error, response, body) { - request(optionsList, function(error, response, body) { + it('should remove just the selected group', function (done) { + request(optionsDelete, function (error, response, body) { + request(optionsList, function (error, response, body) { body.count.should.equal(2); - for (var i = 0; i < body.services.length; i++) { + for (let i = 0; i < body.services.length; i++) { body.services[i].apikey.should.not.equal('801230BJKL23Y9090DSFL123HJK09H324HV8732'); } @@ -579,17 +607,17 @@ describe('Device Group Configuration API', function() { }); }); - describe('When a device group removal request arrives without the mandatory headers', function() { - beforeEach(function() { + describe('When a device group removal request arrives without the mandatory headers', function () { + beforeEach(function () { delete optionsDelete.headers['fiware-servicepath']; }); - afterEach(function() { + afterEach(function () { optionsDelete.headers['fiware-servicepath'] = '/testingPath'; }); - it('should fail with a 400 MISSING_HEADERS Error', function(done) { - request(optionsDelete, function(error, response, body) { + it('should fail with a 400 MISSING_HEADERS Error', function (done) { + request(optionsDelete, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(400); body.name.should.equal('MISSING_HEADERS'); @@ -598,20 +626,20 @@ describe('Device Group Configuration API', function() { }); }); - describe('When a device group removal request arrives without the mandatory parameters', function() { - beforeEach(function() { + describe('When a device group removal request arrives without the mandatory parameters', function () { + beforeEach(function () { delete optionsDelete.qs; }); - afterEach(function() { + afterEach(function () { optionsDelete.qs = { resource: '/deviceTest', apikey: '801230BJKL23Y9090DSFL123HJK09H324HV8732' }; }); - it('should fail with a 400 MISSING_HEADERS Error', function(done) { - request(optionsDelete, function(error, response, body) { + it('should fail with a 400 MISSING_HEADERS Error', function (done) { + request(optionsDelete, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(400); body.name.should.equal('MISSING_HEADERS'); @@ -620,12 +648,11 @@ describe('Device Group Configuration API', function() { }); }); - describe('When a device group update request arrives', function() { - beforeEach(function(done) { - var optionsCreation1 = _.clone(optionsCreation), - optionsCreation2 = _.clone(optionsCreation), - optionsCreation3 = _.clone(optionsCreation); - + describe('When a device group update request arrives', function () { + beforeEach(function (done) { + const optionsCreation1 = _.clone(optionsCreation); + const optionsCreation2 = _.clone(optionsCreation); + const optionsCreation3 = _.clone(optionsCreation); optionsCreation1.json = { services: [] }; optionsCreation3.json = { services: [] }; @@ -636,30 +663,35 @@ describe('Device Group Configuration API', function() { optionsCreation1.json.services[0].apikey = 'qwertyuiop'; optionsCreation3.json.services[0].apikey = 'lkjhgfds'; - async.series([ - async.apply(request, optionsCreation1), - async.apply(request, optionsCreation2), - async.apply(request, optionsCreation3) - ], done); + async.series( + [ + async.apply(request, optionsCreation1), + async.apply(request, optionsCreation2), + async.apply(request, optionsCreation3) + ], + done + ); }); - it('should return a 204 OK', function(done) { - request(optionsUpdate, function(error, response, body) { + it('should return a 204 OK', function (done) { + request(optionsUpdate, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(204); done(); }); }); - it('should update the appropriate values in the database', function(done) { - request(optionsUpdate, function(error, response, body) { - request(optionsList, function(error, response, body) { - var found = false; + it('should update the appropriate values in the database', function (done) { + request(optionsUpdate, function (error, response, body) { + request(optionsList, function (error, response, body) { + let found = false; body.count.should.equal(3); - for (var i = 0; i < body.services.length; i++) { - if (body.services[i].apikey === '801230BJKL23Y9090DSFL123HJK09H324HV8732' && - body.services[i].resource === '/deviceTest') { + for (let i = 0; i < body.services.length; i++) { + if ( + body.services[i].apikey === '801230BJKL23Y9090DSFL123HJK09H324HV8732' && + body.services[i].resource === '/deviceTest' + ) { body.services[i].cbHost.should.equal('http://anotherUnexistentHost:1026'); body.services[i].static_attributes.length.should.equal(1); found = true; @@ -671,10 +703,10 @@ describe('Device Group Configuration API', function() { }); }); }); - it('should call the configuration creation handler', function(done) { - var handlerCalled = false; + it('should call the configuration creation handler', function (done) { + let handlerCalled = false; - iotAgentLib.setConfigurationHandler(function(newConfiguration, callback) { + iotAgentLib.setConfigurationHandler(function (newConfiguration, callback) { should.exist(newConfiguration); should.exist(callback); newConfiguration.cbHost.should.equal('http://anotherUnexistentHost:1026'); @@ -687,26 +719,25 @@ describe('Device Group Configuration API', function() { callback(); }); - request(optionsUpdate, function(error, response, body) { + request(optionsUpdate, function (error, response, body) { handlerCalled.should.equal(true); done(); }); }); }); - describe('When a device group update request arrives declaring a different service', function() { - beforeEach(function(done) { + describe('When a device group update request arrives declaring a different service', function () { + beforeEach(function (done) { optionsUpdate.headers['fiware-service'] = 'UnexistentService'; request(optionsCreation, done); }); - afterEach(function() { + afterEach(function () { optionsUpdate.headers['fiware-service'] = 'TestService'; }); - - it('should return a 200 OK', function(done) { - request(optionsUpdate, function(error, response, body) { + it('should return a 200 OK', function (done) { + request(optionsUpdate, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(403); body.name.should.equal('MISMATCHED_SERVICE'); @@ -715,19 +746,18 @@ describe('Device Group Configuration API', function() { }); }); - describe('When a device group update request arrives declaring a different subservice', function() { - beforeEach(function(done) { + describe('When a device group update request arrives declaring a different subservice', function () { + beforeEach(function (done) { optionsUpdate.headers['fiware-servicepath'] = '/UnexistentServicepath'; request(optionsCreation, done); }); - afterEach(function() { + afterEach(function () { optionsUpdate.headers['fiware-servicepath'] = '/testingPath'; }); - - it('should return a 200 OK', function(done) { - request(optionsUpdate, function(error, response, body) { + it('should return a 200 OK', function (done) { + request(optionsUpdate, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(403); body.name.should.equal('MISMATCHED_SERVICE'); @@ -736,17 +766,17 @@ describe('Device Group Configuration API', function() { }); }); - describe('When a device group update request arrives without the mandatory headers', function() { - beforeEach(function() { + describe('When a device group update request arrives without the mandatory headers', function () { + beforeEach(function () { delete optionsUpdate.headers['fiware-servicepath']; }); - afterEach(function() { + afterEach(function () { optionsUpdate.headers['fiware-servicepath'] = '/testingPath'; }); - it('should fail with a 400 MISSING_HEADERS Error', function(done) { - request(optionsUpdate, function(error, response, body) { + it('should fail with a 400 MISSING_HEADERS Error', function (done) { + request(optionsUpdate, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(400); body.name.should.equal('MISSING_HEADERS'); @@ -755,17 +785,17 @@ describe('Device Group Configuration API', function() { }); }); - describe('When a device group update request arrives without the mandatory parameters', function() { - beforeEach(function() { + describe('When a device group update request arrives without the mandatory parameters', function () { + beforeEach(function () { delete optionsUpdate.qs.resource; }); - afterEach(function() { + afterEach(function () { optionsUpdate.qs.resource = '/deviceTest'; }); - it('should fail with a 400 MISSING_HEADERS Error', function(done) { - request(optionsUpdate, function(error, response, body) { + it('should fail with a 400 MISSING_HEADERS Error', function (done) { + request(optionsUpdate, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(400); body.name.should.equal('MISSING_HEADERS'); @@ -775,7 +805,7 @@ describe('Device Group Configuration API', function() { }); describe('When a device group update request arrives with a different explicitAttrs value', function () { - var optionsCreation1 = { + const optionsCreation1 = { url: 'http://localhost:4041/iot/services', method: 'POST', json: { @@ -794,12 +824,12 @@ describe('Device Group Configuration API', function() { 'fiware-service': 'TestService', 'fiware-servicepath': '/testingPath' } - }, - optionsUpdate1 = { + }; + const optionsUpdate1 = { url: 'http://localhost:4041/iot/services', method: 'PUT', json: { - 'explicitAttrs': false + explicitAttrs: false }, headers: { 'fiware-service': 'TestService', @@ -827,12 +857,11 @@ describe('Device Group Configuration API', function() { }); }); - describe('When a device group listing request arrives', function() { - beforeEach(function(done) { - var optionsCreation1 = _.clone(optionsCreation), - optionsCreation2 = _.clone(optionsCreation), - optionsCreation3 = _.clone(optionsCreation); - + describe('When a device group listing request arrives', function () { + beforeEach(function (done) { + const optionsCreation1 = _.clone(optionsCreation); + const optionsCreation2 = _.clone(optionsCreation); + const optionsCreation3 = _.clone(optionsCreation); optionsCreation2.json = { services: [] }; optionsCreation3.json = { services: [] }; @@ -843,22 +872,25 @@ describe('Device Group Configuration API', function() { optionsCreation2.json.services[0].apikey = 'qwertyuiop'; optionsCreation3.json.services[0].apikey = 'lkjhgfds'; - async.series([ - async.apply(request, optionsCreation1), - async.apply(request, optionsCreation2), - async.apply(request, optionsCreation3) - ], done); + async.series( + [ + async.apply(request, optionsCreation1), + async.apply(request, optionsCreation2), + async.apply(request, optionsCreation3) + ], + done + ); }); - it('should return a 200 OK', function(done) { - request(optionsList, function(error, response, body) { + it('should return a 200 OK', function (done) { + request(optionsList, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(200); done(); }); }); - it('should return all the configured device groups from the database', function(done) { - request(optionsList, function(error, response, body) { + it('should return all the configured device groups from the database', function (done) { + request(optionsList, function (error, response, body) { should.exist(body.count); should.exist(body.services); body.count.should.equal(3); @@ -868,89 +900,91 @@ describe('Device Group Configuration API', function() { }); }); - describe('When a device info request arrives', function() { - beforeEach(function(done) { - async.series([ - async.apply(request, optionsCreation) - ], done); + describe('When a device info request arrives', function () { + beforeEach(function (done) { + async.series([async.apply(request, optionsCreation)], done); }); - it('should return a 200 OK', function(done) { - request(optionsGet, function(error, response, body) { + it('should return a 200 OK', function (done) { + request(optionsGet, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(200); done(); }); }); - it('should return all the configured device groups from the database', function(done) { - request(optionsGet, function(error, response, body) { + it('should return all the configured device groups from the database', function (done) { + request(optionsGet, function (error, response, body) { body.services[0].service.should.equal('TestService'); done(); }); }); }); - describe('When a new device from a created group arrives to the IoT Agent and sends a measure', function() { - var contextBrokerMock, - values = [ - { - name: 'status', - type: 'String', - value: 'STARTING' - } - ]; + describe('When a new device from a created group arrives to the IoT Agent and sends a measure', function () { + let contextBrokerMock; + const values = [ + { + name: 'status', + type: 'String', + value: 'STARTING' + } + ]; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://unexistentHost:1026') .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/updateContext3WithStatic.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateContext3WithStatic.json') + ) + .reply(200, utils.readExampleFile('./test/unit/examples/contextResponses/updateContext1Success.json')); - async.series([ - async.apply(request, optionsCreation) - ], done); + async.series([async.apply(request, optionsCreation)], done); }); - afterEach(function(done) { + afterEach(function (done) { nock.cleanAll(); done(); }); - it('should use the configured data', function(done) { - iotAgentLib.update('machine1', 'SensorMachine', '801230BJKL23Y9090DSFL123HJK09H324HV8732', values, - function(error) { + it('should use the configured data', function (done) { + iotAgentLib.update( + 'machine1', + 'SensorMachine', + '801230BJKL23Y9090DSFL123HJK09H324HV8732', + values, + function (error) { should.not.exist(error); contextBrokerMock.done(); done(); - }); + } + ); }); }); - describe('When a group listing request arrives with offset and limit parameters', function() { - var optConstrainedList = { - url: 'http://localhost:4041/iot/services', - method: 'GET', - qs: { - limit: 3, - offset: 2 - }, - json: {}, - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/*' - } - }; + describe('When a group listing request arrives with offset and limit parameters', function () { + const optConstrainedList = { + url: 'http://localhost:4041/iot/services', + method: 'GET', + qs: { + limit: 3, + offset: 2 + }, + json: {}, + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/*' + } + }; - beforeEach(function(done) { - var optionsCreationList = [], - creationFns = []; + beforeEach(function (done) { + const optionsCreationList = []; + const creationFns = []; - for (var i = 0; i < 10; i++) { + for (let i = 0; i < 10; i++) { optionsCreationList[i] = _.clone(optionsCreation); optionsCreationList[i].json = { services: [] }; optionsCreationList[i].json.services[0] = _.clone(optionsCreation.json.services[0]); @@ -961,23 +995,23 @@ describe('Device Group Configuration API', function() { async.series(creationFns, done); }); - it('should return a 200 OK', function(done) { - request(optConstrainedList, function(error, response, body) { + it('should return a 200 OK', function (done) { + request(optConstrainedList, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(200); done(); }); }); - it('should use the limit parameter to constrain the number of entries', function(done) { - request(optConstrainedList, function(error, response, body) { + it('should use the limit parameter to constrain the number of entries', function (done) { + request(optConstrainedList, function (error, response, body) { should.exist(body.count); should.exist(body.services); body.services.length.should.equal(3); done(); }); }); - it('should use return the total number of entities', function(done) { - request(optConstrainedList, function(error, response, body) { + it('should use return the total number of entities', function (done) { + request(optConstrainedList, function (error, response, body) { should.exist(body.count); should.exist(body.services); body.count.should.equal(10); diff --git a/test/unit/provisioning/device-group-utils_test.js b/test/unit/provisioning/device-group-utils_test.js index fa2f5a2b9..606c72af6 100644 --- a/test/unit/provisioning/device-group-utils_test.js +++ b/test/unit/provisioning/device-group-utils_test.js @@ -20,148 +20,149 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; -/* jshint camelcase: false */ +/* eslint-disable no-unused-vars */ -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - async = require('async'), - groupRegistryMemory = require('../../../lib/services/groups/groupRegistryMemory'), - request = require('request'), - groupCreation = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionFullGroup.json'), - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - } +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const async = require('async'); +const groupRegistryMemory = require('../../../lib/services/groups/groupRegistryMemory'); +const request = require('request'); +const groupCreation = { + url: 'http://localhost:4041/iot/services', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionFullGroup.json'), + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } +}; +const alternateGroupCreation = { + url: 'http://localhost:4041/iot/services', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionFullGroupAlternate.json'), + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } +}; +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041, + baseRoot: '/' }, - alternateGroupCreation = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionFullGroupAlternate.json'), - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' + types: { + Termometer: { + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [], + apikey: '1234567890asdfghjkl', + service: 'TestService', + subservice: '/testingPath' } }, - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041, - baseRoot: '/' - }, - types: { - 'Termometer': { - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ], - apikey: '1234567890asdfghjkl', - service: 'TestService', - subservice: '/testingPath' - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M', - defaultKey: 'default1234' - }; + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M', + defaultKey: 'default1234' +}; -describe('Device Group utils', function() { - afterEach(function(done) { - iotAgentLib.deactivate(function() { +describe('Device Group utils', function () { + afterEach(function (done) { + iotAgentLib.deactivate(function () { groupRegistryMemory.clear(done); }); }); - describe('When an API Key is requested for a device in a group without the SingleConfiguration mode', function() { - beforeEach(function(done) { - async.series([ - async.apply(iotAgentLib.activate, iotAgentConfig), - async.apply(request, alternateGroupCreation), - async.apply(request, groupCreation) - ], done); + describe('When an API Key is requested for a device in a group without the SingleConfiguration mode', function () { + beforeEach(function (done) { + async.series( + [ + async.apply(iotAgentLib.activate, iotAgentConfig), + async.apply(request, alternateGroupCreation), + async.apply(request, groupCreation) + ], + done + ); }); - it('should return the API Key of the group', function(done) { - iotAgentLib.getEffectiveApiKey('TestService', '/testingPath', 'AnotherMachine', function(error, apiKey) { + it('should return the API Key of the group', function (done) { + iotAgentLib.getEffectiveApiKey('TestService', '/testingPath', 'AnotherMachine', function (error, apiKey) { should.not.exist(error); apiKey.should.equal('754KL23Y9090DSFL123HSFL12380KL23Y2'); done(); }); }); }); - describe('When an API Key is requested for a device in a subservice with the SingleConfiguration mode', function() { - beforeEach(function(done) { + describe('When an API Key is requested for a device in a subservice with the SingleConfiguration mode', function () { + beforeEach(function (done) { iotAgentConfig.singleConfigurationMode = true; - iotAgentLib.activate(iotAgentConfig, function() { - request(groupCreation, function(error, response, body) { + iotAgentLib.activate(iotAgentConfig, function () { + request(groupCreation, function (error, response, body) { done(); }); }); }); - afterEach(function() { + afterEach(function () { iotAgentConfig.singleConfigurationMode = false; }); - it('should return the API Key of the related subservice', function(done) { - iotAgentLib.getEffectiveApiKey('TestService', '/testingPath', null, function(error, apiKey) { + it('should return the API Key of the related subservice', function (done) { + iotAgentLib.getEffectiveApiKey('TestService', '/testingPath', null, function (error, apiKey) { should.not.exist(error); apiKey.should.equal('801230BJKL23Y9090DSFL123HJK09H324HV8732'); done(); }); }); }); - describe('When an API Key is requested without a provisioned group but with a configured type', function() { - beforeEach(function(done) { + describe('When an API Key is requested without a provisioned group but with a configured type', function () { + beforeEach(function (done) { iotAgentLib.activate(iotAgentConfig, done); }); - it('should return the API Key of the related type', function(done) { - iotAgentLib.getEffectiveApiKey('TestService', '/testingPath', 'Termometer', function(error, apiKey) { + it('should return the API Key of the related type', function (done) { + iotAgentLib.getEffectiveApiKey('TestService', '/testingPath', 'Termometer', function (error, apiKey) { should.not.exist(error); apiKey.should.equal('1234567890asdfghjkl'); done(); }); }); }); - describe('When an API Key is requested and there is no group or type configured', function() { - beforeEach(function(done) { + describe('When an API Key is requested and there is no group or type configured', function () { + beforeEach(function (done) { iotAgentLib.activate(iotAgentConfig, done); }); - it('should return the default API Key', function(done) { - iotAgentLib.getEffectiveApiKey('TestService', '/testingPath', 'WeatherMachine', function(error, apiKey) { + it('should return the default API Key', function (done) { + iotAgentLib.getEffectiveApiKey('TestService', '/testingPath', 'WeatherMachine', function (error, apiKey) { should.not.exist(error); apiKey.should.equal('default1234'); done(); }); }); }); - describe('When an API Key is requested and there is no group, type or default value', function() { - beforeEach(function(done) { + describe('When an API Key is requested and there is no group, type or default value', function () { + beforeEach(function (done) { delete iotAgentConfig.defaultKey; iotAgentLib.activate(iotAgentConfig, done); }); - afterEach(function() { + afterEach(function () { iotAgentConfig.defaultKey = 'default1234'; }); - it('should raise an error', function(done) { - iotAgentLib.getEffectiveApiKey('TestService', '/testingPath', 'WeatherMachine', function(error, apiKey) { + it('should raise an error', function (done) { + iotAgentLib.getEffectiveApiKey('TestService', '/testingPath', 'WeatherMachine', function (error, apiKey) { should.exist(error); error.name.should.equal('GROUP_NOT_FOUND'); done(); diff --git a/test/unit/provisioning/device-provisioning-api_test.js b/test/unit/provisioning/device-provisioning-api_test.js index 964ff03ee..39b219aa7 100644 --- a/test/unit/provisioning/device-provisioning-api_test.js +++ b/test/unit/provisioning/device-provisioning-api_test.js @@ -20,84 +20,106 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - - should = require('should'), - nock = require('nock'), - request = require('request'), - contextBrokerMock, - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041, - baseRoot: '/' - }, - types: {}, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }; - -describe('NGSI-v1 - Device provisioning API: Provision devices', function() { - beforeEach(function(done) { + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const nock = require('nock'); +const request = require('request'); +let contextBrokerMock; +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041, + baseRoot: '/' + }, + types: {}, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; + +describe('NGSI-v1 - Device provisioning API: Provision devices', function () { + beforeEach(function (done) { nock.cleanAll(); - iotAgentLib.activate(iotAgentConfig, function() { + iotAgentLib.activate(iotAgentConfig, function () { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerProvisionedDevice.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile( + './test/unit/examples/contextAvailabilityRequests/registerProvisionedDevice.json' + ) + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); iotAgentLib.clearAll(done); }); }); - afterEach(function(done) { + afterEach(function (done) { nock.cleanAll(); iotAgentLib.setProvisioningHandler(); iotAgentLib.deactivate(done); }); - describe('When a device provisioning request with all the required data arrives to the IoT Agent', function() { - beforeEach(function() { + describe('When a device provisioning request with all the required data arrives to the IoT Agent', function () { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerProvisionedDevice.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile( + './test/unit/examples/contextAvailabilityRequests/registerProvisionedDevice.json' + ) + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/createProvisionedDevice.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/createProvisionedDevice.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); }); - var options = { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json'), @@ -107,36 +129,36 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { } }; - it('should add the device to the devices list', function(done) { - request(options, function(error, response, body) { + it('should add the device to the devices list', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(201); - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { results.devices.length.should.equal(1); done(); }); }); }); - it('should call the device provisioning handler if present', function(done) { - var handlerCalled = false; + it('should call the device provisioning handler if present', function (done) { + let handlerCalled = false; - iotAgentLib.setProvisioningHandler(function(device, callback) { + iotAgentLib.setProvisioningHandler(function (device, callback) { handlerCalled = true; callback(null, device); }); - request(options, function(error, response, body) { + request(options, function (error, response, body) { handlerCalled.should.equal(true); done(); }); }); - it('should store the device with the provided entity id, name and type', function(done) { - request(options, function(error, response, body) { + it('should store the device with the provided entity id, name and type', function (done) { + request(options, function (error, response, body) { response.statusCode.should.equal(201); - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { results.devices[0].id.should.equal('Light1'); results.devices[0].name.should.equal('TheFirstLight'); results.devices[0].type.should.equal('TheLightType'); @@ -144,10 +166,10 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { }); }); }); - it('should store the device with the per device information', function(done) { - request(options, function(error, response, body) { + it('should store the device with the per device information', function (done) { + request(options, function (error, response, body) { response.statusCode.should.equal(201); - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { should.exist(results.devices[0].timezone); results.devices[0].timezone.should.equal('America/Santiago'); should.exist(results.devices[0].endpoint); @@ -174,11 +196,10 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { }); }); - it('should store fill the device ID in case only the name is provided', function(done) { - /* jshint camelcase:false */ - request(options, function(error, response, body) { + it('should store fill the device ID in case only the name is provided', function (done) { + request(options, function (error, response, body) { response.statusCode.should.equal(201); - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { results.devices[0].lazy[0].object_id.should.equal('luminance'); results.devices[0].commands[0].object_id.should.equal('commandAttr'); results.devices[0].active[0].object_id.should.equal('attr_name'); @@ -187,10 +208,10 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { }); }); - it('should store service and subservice info from the headers along with the device data', function(done) { - request(options, function(error, response, body) { + it('should store service and subservice info from the headers along with the device data', function (done) { + request(options, function (error, response, body) { response.statusCode.should.equal(201); - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { should.exist(results.devices[0].service); results.devices[0].service.should.equal('smartGondor'); should.exist(results.devices[0].subservice); @@ -200,18 +221,18 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { }); }); - it('should create the initial entity in the Context Broker', function(done) { - request(options, function(error, response, body) { + it('should create the initial entity in the Context Broker', function (done) { + request(options, function (error, response, body) { response.statusCode.should.equal(201); - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { contextBrokerMock.done(); done(); }); }); }); }); - describe('When a device provisioning request with a TimeInstant attribute arrives to the IoTA', function() { - var options = { + describe('When a device provisioning request with a TimeInstant attribute arrives to the IoTA', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionTimeInstant.json'), @@ -221,40 +242,44 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { } }; - beforeEach(function(done) { - iotAgentLib.deactivate(function() { + beforeEach(function (done) { + iotAgentLib.deactivate(function () { iotAgentConfig.timestamp = true; iotAgentLib.activate(iotAgentConfig, done); }); }); - afterEach(function() { + afterEach(function () { iotAgentConfig.timestamp = false; }); - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/createTimeinstantDevice.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/createTimeinstantSuccess.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/createTimeinstantDevice.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createTimeinstantSuccess.json') + ); done(); }); - it('should send the appropriate requests to the Context Broker', function(done) { - request(options, function(error, response, body) { + it('should send the appropriate requests to the Context Broker', function (done) { + request(options, function (error, response, body) { contextBrokerMock.done(); done(); }); }); }); - describe('When a device provisioning request with the minimum required data arrives to the IoT Agent', function() { - var options = { + describe('When a device provisioning request with the minimum required data arrives to the IoT Agent', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), @@ -264,42 +289,46 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/createMinimumProvisionedDevice.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/createMinimumProvisionedDevice.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); done(); }); - it('should send the appropriate requests to the Context Broker', function(done) { - request(options, function(error, response, body) { + it('should send the appropriate requests to the Context Broker', function (done) { + request(options, function (error, response, body) { contextBrokerMock.done(); done(); }); }); - it('should add the device to the devices list', function(done) { - request(options, function(error, response, body) { + it('should add the device to the devices list', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(201); - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { results.devices.length.should.equal(1); done(); }); }); }); - it('should store the device with the provided entity id, name and type', function(done) { - request(options, function(error, response, body) { + it('should store the device with the provided entity id, name and type', function (done) { + request(options, function (error, response, body) { response.statusCode.should.equal(201); - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { results.devices[0].id.should.equal('MicroLight1'); results.devices[0].name.should.equal('FirstMicroLight'); results.devices[0].type.should.equal('MicroLights'); @@ -309,8 +338,8 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { }); }); - describe('When a device provisioning request with geo:point attributes arrives', function() { - var options = { + describe('When a device provisioning request with geo:point attributes arrives', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionGeopointDevice.json'), @@ -320,31 +349,35 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/updateContext', + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/createGeopointProvisionedDevice.json') + ) + .reply( + 200, utils.readExampleFile( - './test/unit/examples/contextRequests/createGeopointProvisionedDevice.json')) - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createGeopointProvisionedDeviceSuccess.json')); + './test/unit/examples/contextResponses/createGeopointProvisionedDeviceSuccess.json' + ) + ); done(); }); - it('should send the appropriate initial values to the Context Broker', function(done) { - request(options, function(error, response, body) { + it('should send the appropriate initial values to the Context Broker', function (done) { + request(options, function (error, response, body) { contextBrokerMock.done(); done(); }); }); }); - describe('When a device provisioning request with DateTime attributes arrives', function() { - var options = { + describe('When a device provisioning request with DateTime attributes arrives', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionDatetimeDevice.json'), @@ -354,89 +387,97 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/updateContext', - utils.readExampleFile( - './test/unit/examples/contextRequests/createDatetimeProvisionedDevice.json')) - .reply(200, + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/createDatetimeProvisionedDevice.json') + ) + .reply( + 200, utils.readExampleFile( - './test/unit/examples/contextResponses/createDatetimeProvisionedDeviceSuccess.json')); + './test/unit/examples/contextResponses/createDatetimeProvisionedDeviceSuccess.json' + ) + ); done(); }); - it('should send the appropriate initial values to the Context Broker', function(done) { - request(options, function(error, response, body) { + it('should send the appropriate initial values to the Context Broker', function (done) { + request(options, function (error, response, body) { contextBrokerMock.done(); done(); }); }); }); + describe('When two devices with the same ID but different services arrive to the agent', function () { + const options1 = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + const options2 = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), + headers: { + 'fiware-service': 'smartMordor', + 'fiware-servicepath': '/electricity' + } + }; - describe('When two devices with the same ID but different services arrive to the agent', function() { - var options1 = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }, - options2 = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), - headers: { - 'fiware-service': 'smartMordor', - 'fiware-servicepath': '/electricity' - } - }; - - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/createMinimumProvisionedDevice.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); - + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/createMinimumProvisionedDevice.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); contextBrokerMock - .post('/v1/updateContext', - utils.readExampleFile('./test/unit/examples/contextRequests/createMinimumProvisionedDevice.json')) - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/createMinimumProvisionedDevice.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); done(); }); - it('should accept both creations', function(done) { - request(options1, function(error, response, body) { + it('should accept both creations', function (done) { + request(options1, function (error, response, body) { response.statusCode.should.equal(201); - request(options2, function(error, response, body) { + request(options2, function (error, response, body) { response.statusCode.should.equal(201); done(); }); }); }); - it('should show the new device in each list', function(done) { - request(options1, function(error, response, body) { - request(options2, function(error, response, body) { - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + it('should show the new device in each list', function (done) { + request(options1, function (error, response, body) { + request(options2, function (error, response, body) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { results.devices.length.should.equal(1); results.devices[0].id.should.equal('MicroLight1'); - iotAgentLib.listDevices('smartMordor', '/electricity', function(error, results) { + iotAgentLib.listDevices('smartMordor', '/electricity', function (error, results) { results.devices.length.should.equal(1); results.devices[0].id.should.equal('MicroLight1'); done(); @@ -447,8 +488,8 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { }); }); - describe('When there is a connection error with a String code connecting the CB', function() { - var options = { + describe('When there is a connection error with a String code connecting the CB', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), @@ -458,28 +499,31 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/NGSI9/registerContext') - .reply(200, + .reply( + 200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v1/updateContext') - .replyWithError({'message': 'Description of the error', 'code': 'STRING_CODE'}); + .replyWithError({ message: 'Description of the error', code: 'STRING_CODE' }); done(); }); - it('should return a valid return code', function(done) { - request(options, function(error, response, body) { + it('should return a valid return code', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(500); @@ -488,8 +532,8 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { }); }); - describe('When there is a connection error with a Number code connecting the CB', function() { - var options = { + describe('When there is a connection error with a Number code connecting the CB', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice.json'), @@ -499,28 +543,31 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/NGSI9/registerContext') - .reply(200, + .reply( + 200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v1/updateContext') - .replyWithError({'message': 'Description of the error', 'code': 123456789}); + .replyWithError({ message: 'Description of the error', code: 123456789 }); done(); }); - it('should return a valid return code (three character number)', function(done) { - request(options, function(error, response, body) { + it('should return a valid return code (three character number)', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(500); @@ -529,8 +576,8 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { }); }); - describe('When a device provisioning request with missing data arrives to the IoT Agent', function() { - var options = { + describe('When a device provisioning request with missing data arrives to the IoT Agent', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', headers: { @@ -538,11 +585,12 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { 'fiware-servicepath': '/gardens' }, json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionDeviceMissingParameters.json') + './test/unit/examples/deviceProvisioningRequests/provisionDeviceMissingParameters.json' + ) }; - it('should raise a MISSING_ATTRIBUTES error, indicating the missing attributes', function(done) { - request(options, function(error, response, body) { + it('should raise a MISSING_ATTRIBUTES error, indicating the missing attributes', function (done) { + request(options, function (error, response, body) { should.exist(body); response.statusCode.should.equal(400); body.name.should.equal('MISSING_ATTRIBUTES'); @@ -551,8 +599,8 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { }); }); }); - describe('When two device provisioning requests with the same service and Device ID arrive', function() { - var options = { + describe('When two device provisioning requests with the same service and Device ID arrive', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json'), @@ -562,29 +610,38 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerProvisionedDevice.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile( + './test/unit/examples/contextAvailabilityRequests/registerProvisionedDevice.json' + ) + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); done(); }); - it('should raise a DUPLICATE_ID error, indicating the ID was already in use', function(done) { - request(options, function(error, response, body) { - request(options, function(error, response, body) { + it('should raise a DUPLICATE_ID error, indicating the ID was already in use', function (done) { + request(options, function (error, response, body) { + request(options, function (error, response, body) { should.exist(body); response.statusCode.should.equal(409); body.name.should.equal('DUPLICATE_DEVICE_ID'); @@ -593,21 +650,22 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { }); }); }); - describe('When a device provisioning request is malformed', function() { - var options = { + describe('When a device provisioning request is malformed', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionNewDeviceMalformed1.json'), + './test/unit/examples/deviceProvisioningRequests/provisionNewDeviceMalformed1.json' + ), headers: { 'fiware-service': 'smartGondor', 'fiware-servicepath': '/gardens' } }; - it('should raise a WRONG_SYNTAX exception', function(done) { - request(options, function(error, response, body) { - request(options, function(error, response, body) { + it('should raise a WRONG_SYNTAX exception', function (done) { + request(options, function (error, response, body) { + request(options, function (error, response, body) { should.exist(body); response.statusCode.should.equal(400); body.name.should.equal('WRONG_SYNTAX'); @@ -616,8 +674,8 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { }); }); }); - describe('When an agent is activated with a different base root', function() { - var options = { + describe('When an agent is activated with a different base root', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/newBaseRoot/iot/devices', method: 'POST', headers: { @@ -627,40 +685,41 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json') }; - beforeEach(function(done) { - iotAgentLib.deactivate(function() { + beforeEach(function (done) { + iotAgentLib.deactivate(function () { iotAgentConfig.server.baseRoot = '/newBaseRoot'; iotAgentLib.activate(iotAgentConfig, done); }); }); - afterEach(function() { + afterEach(function () { iotAgentConfig.server.baseRoot = '/'; }); - it('should listen to requests in the new root', function(done) { - request(options, function(error, response, body) { + it('should listen to requests in the new root', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(201); - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { results.devices.length.should.equal(1); done(); }); }); }); }); - describe('When a device provisioning request without the mandatory headers arrives to the Agent', function() { - var options = { + describe('When a device provisioning request without the mandatory headers arrives to the Agent', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', headers: {}, json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionDeviceMissingParameters.json') + './test/unit/examples/deviceProvisioningRequests/provisionDeviceMissingParameters.json' + ) }; - it('should raise a MISSING_HEADERS error, indicating the missing attributes', function(done) { - request(options, function(error, response, body) { + it('should raise a MISSING_HEADERS error, indicating the missing attributes', function (done) { + request(options, function (error, response, body) { should.exist(body); response.statusCode.should.equal(400); body.name.should.equal('MISSING_HEADERS'); @@ -668,22 +727,22 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { }); }); }); - describe('When a device delete request arrives to the Agent for a not existing device', function() { - var options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light84', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - }, - method: 'DELETE' - }; - - it('should return a 404 error', function(done) { - request(options, function(error, response, body) { - should.not.exist(error); - response.statusCode.should.equal(404); - done(); - }); - }); + describe('When a device delete request arrives to the Agent for a not existing device', function () { + const options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light84', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + }, + method: 'DELETE' + }; + + it('should return a 404 error', function (done) { + request(options, function (error, response, body) { + should.not.exist(error); + response.statusCode.should.equal(404); + done(); + }); + }); }); }); diff --git a/test/unit/provisioning/device-registration_test.js b/test/unit/provisioning/device-registration_test.js index f4afdfd16..6616b5ddd 100644 --- a/test/unit/provisioning/device-registration_test.js +++ b/test/unit/provisioning/device-registration_test.js @@ -20,137 +20,151 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - async = require('async'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ], - service: 'smartGondor', - subservice: 'gardens' - }, - 'Termometer': { - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ], - service: 'smartGondor', - subservice: 'gardens' - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +const async = require('async'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' }, - device1 = { - id: 'light1', - type: 'Light', - service: 'smartGondor', - subservice: 'gardens' + server: { + port: 4041 }, - device2 = { - id: 'term2', - type: 'Termometer', - service: 'smartGondor', - subservice: 'gardens' - }; - -describe('NGSI-v1 - IoT Agent Device Registration', function() { - beforeEach(function() { + types: { + Light: { + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ], + service: 'smartGondor', + subservice: 'gardens' + }, + Termometer: { + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [], + service: 'smartGondor', + subservice: 'gardens' + } + }, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; +const device1 = { + id: 'light1', + type: 'Light', + service: 'smartGondor', + subservice: 'gardens' +}; +const device2 = { + id: 'term2', + type: 'Termometer', + service: 'smartGondor', + subservice: 'gardens' +}; + +describe('NGSI-v1 - IoT Agent Device Registration', function () { + beforeEach(function () { logger.setLevel('FATAL'); }); - afterEach(function(done) { - delete(device1.registrationId); - iotAgentLib.clearAll(function() { + afterEach(function (done) { + delete device1.registrationId; + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When a new device is connected to the IoT Agent', function() { - beforeEach(function(done) { + describe('When a new device is connected to the IoT Agent', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); - iotAgentLib.activate(iotAgentConfig, function(error) { + iotAgentLib.activate(iotAgentConfig, function (error) { iotAgentLib.clearAll(done); }); }); - it('should register as ContextProvider of its lazy attributes', function(done) { - iotAgentLib.register(device1, function(error) { - should.not.exist(error); - contextBrokerMock.done(); - done(); + it('should register as ContextProvider of its lazy attributes', function (done) { + iotAgentLib.register(device1, function (error) { + should.not.exist(error); + contextBrokerMock.done(); + done(); }); }); }); - describe('When the Context Broker returns a NGSI error while registering a device', function() { - beforeEach(function(done) { + describe('When the Context Broker returns a NGSI error while registering a device', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Failed.json')); - - iotAgentLib.activate(iotAgentConfig, function(error) { + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Failed.json' + ) + ); + + iotAgentLib.activate(iotAgentConfig, function (error) { iotAgentLib.clearAll(done); }); }); - it('should register as ContextProvider of its lazy attributes', function(done) { - iotAgentLib.register(device1, function(error) { + it('should register as ContextProvider of its lazy attributes', function (done) { + iotAgentLib.register(device1, function (error) { should.exist(error); error.name.should.equal('BAD_REQUEST'); contextBrokerMock.done(); @@ -159,26 +173,32 @@ describe('NGSI-v1 - IoT Agent Device Registration', function() { }); }); - describe('When the Context Broker returns an HTTP transport error while registering a device', function() { - beforeEach(function(done) { + describe('When the Context Broker returns an HTTP transport error while registering a device', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json')) - .reply(500, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Failed.json')); - - iotAgentLib.activate(iotAgentConfig, function(error) { + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json') + ) + .reply( + 500, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Failed.json' + ) + ); + + iotAgentLib.activate(iotAgentConfig, function (error) { iotAgentLib.clearAll(done); }); }); it('should not register the device in the internal registry'); - it('should return a REGISTRATION_ERROR error to the caller', function(done) { - iotAgentLib.register(device1, function(error) { + it('should return a REGISTRATION_ERROR error to the caller', function (done) { + iotAgentLib.register(device1, function (error) { should.exist(error); should.exist(error.name); error.name.should.equal('REGISTRATION_ERROR'); @@ -188,33 +208,41 @@ describe('NGSI-v1 - IoT Agent Device Registration', function() { }); }); - describe('When a device is requested to the library using its ID', function() { - beforeEach(function(done) { + describe('When a device is requested to the library using its ID', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); - iotAgentLib.activate(iotAgentConfig, function(error) { + iotAgentLib.activate(iotAgentConfig, function (error) { iotAgentLib.clearAll(done); }); }); - it('should return all the device\'s information', function(done) { - iotAgentLib.register(device1, function(error) { - iotAgentLib.getDevice('light1', 'smartGondor', 'gardens', function(error, data) { + it("should return all the device's information", function (done) { + iotAgentLib.register(device1, function (error) { + iotAgentLib.getDevice('light1', 'smartGondor', 'gardens', function (error, data) { should.not.exist(error); should.exist(data); data.type.should.equal('Light'); @@ -225,26 +253,32 @@ describe('NGSI-v1 - IoT Agent Device Registration', function() { }); }); - describe('When an unexistent device is requested to the library using its ID', function() { - beforeEach(function(done) { + describe('When an unexistent device is requested to the library using its ID', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); - - iotAgentLib.activate(iotAgentConfig, function(error) { + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/registerIoTAgent1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json' + ) + ); + + iotAgentLib.activate(iotAgentConfig, function (error) { iotAgentLib.clearAll(done); }); }); - it('should return a ENTITY_NOT_FOUND error', function(done) { - iotAgentLib.register(device1, function(error) { - iotAgentLib.getDevice('lightUnexistent', 'smartGondor', 'gardens', function(error, data) { + it('should return a ENTITY_NOT_FOUND error', function (done) { + iotAgentLib.register(device1, function (error) { + iotAgentLib.getDevice('lightUnexistent', 'smartGondor', 'gardens', function (error, data) { should.exist(error); should.not.exist(data); error.code.should.equal(404); @@ -255,51 +289,68 @@ describe('NGSI-v1 - IoT Agent Device Registration', function() { }); }); - describe('When a device is removed from the IoT Agent', function() { - beforeEach(function(done) { - var expectedPayload3 = utils - .readExampleFile('./test/unit/examples/contextAvailabilityRequests/unregisterDevice1.json'); + describe('When a device is removed from the IoT Agent', function () { + beforeEach(function (done) { + const expectedPayload3 = utils.readExampleFile( + './test/unit/examples/contextAvailabilityRequests/unregisterDevice1.json' + ); nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .post('/NGSI9/registerContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerNewDevice1Success.json')); + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerNewDevice1Success.json' + ) + ); contextBrokerMock .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); contextBrokerMock .post('/NGSI9/registerContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerNewDevice2Success.json')); + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerNewDevice2Success.json' + ) + ); contextBrokerMock .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); contextBrokerMock .post('/NGSI9/registerContext', expectedPayload3) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/unregisterDevice1Success.json')); - - - iotAgentLib.activate(iotAgentConfig, function(error) { - async.series([ - async.apply(iotAgentLib.clearAll), - async.apply(iotAgentLib.register, device1), - async.apply(iotAgentLib.register, device2) - ], done); + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/unregisterDevice1Success.json' + ) + ); + + iotAgentLib.activate(iotAgentConfig, function (error) { + async.series( + [ + async.apply(iotAgentLib.clearAll), + async.apply(iotAgentLib.register, device1), + async.apply(iotAgentLib.register, device2) + ], + done + ); }); }); - it('should update the devices information in Context Broker', function(done) { - iotAgentLib.unregister(device1.id, 'smartGondor', 'gardens', function(error) { + it('should update the devices information in Context Broker', function (done) { + iotAgentLib.unregister(device1.id, 'smartGondor', 'gardens', function (error) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -307,51 +358,69 @@ describe('NGSI-v1 - IoT Agent Device Registration', function() { }); }); - describe('When the Context Broker returns an error while unregistering a device', function() { - beforeEach(function(done) { - var expectedPayload3 = utils - .readExampleFile('./test/unit/examples/contextAvailabilityRequests/unregisterDevice1.json'); + describe('When the Context Broker returns an error while unregistering a device', function () { + beforeEach(function (done) { + const expectedPayload3 = utils.readExampleFile( + './test/unit/examples/contextAvailabilityRequests/unregisterDevice1.json' + ); nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .post('/NGSI9/registerContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerNewDevice1Success.json')); + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerNewDevice1Success.json' + ) + ); contextBrokerMock .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); contextBrokerMock .post('/NGSI9/registerContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerNewDevice2Success.json')); + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerNewDevice2Success.json' + ) + ); contextBrokerMock .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); contextBrokerMock .post('/NGSI9/registerContext', expectedPayload3) - .reply(500, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/unregisterDevice1Failed.json')); - - iotAgentLib.activate(iotAgentConfig, function(error) { - async.series([ - async.apply(iotAgentLib.clearAll), - async.apply(iotAgentLib.register, device1), - async.apply(iotAgentLib.register, device2) - ], done); + .reply( + 500, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/unregisterDevice1Failed.json' + ) + ); + + iotAgentLib.activate(iotAgentConfig, function (error) { + async.series( + [ + async.apply(iotAgentLib.clearAll), + async.apply(iotAgentLib.register, device1), + async.apply(iotAgentLib.register, device2) + ], + done + ); }); }); it('should not remove the device from the internal registry'); - it('should return a UNREGISTRATION_ERROR error to the caller', function(done) { - iotAgentLib.unregister(device1.id, 'smartGondor', 'gardens', function(error) { + it('should return a UNREGISTRATION_ERROR error to the caller', function (done) { + iotAgentLib.unregister(device1.id, 'smartGondor', 'gardens', function (error) { should.exist(error); should.exist(error.name); error.name.should.equal('UNREGISTRATION_ERROR'); diff --git a/test/unit/provisioning/device-update-registration_test.js b/test/unit/provisioning/device-update-registration_test.js index fac26d653..3d719455f 100644 --- a/test/unit/provisioning/device-update-registration_test.js +++ b/test/unit/provisioning/device-update-registration_test.js @@ -20,119 +20,119 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - logger = require('logops'), - nock = require('nock'), - contextBrokerMock, - iotAgentConfig = { - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041 - }, - types: { - 'Light': { - commands: [], - lazy: [ - { - name: 'temperature', - type: 'centigrades' - } - ], - active: [ - { - name: 'pressure', - type: 'Hgmm' - } - ], - service: 'smartGondor', - subservice: 'gardens' - }, - 'Termometer': { - commands: [], - lazy: [ - { - name: 'temp', - type: 'kelvin' - } - ], - active: [ - ], - service: 'smartGondor', - subservice: 'gardens' - } - }, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }, - device1 = { - id: 'light1', - type: 'Light', - service: 'smartGondor', - subservice: 'gardens', +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const logger = require('logops'); +const nock = require('nock'); +let contextBrokerMock; +const iotAgentConfig = { + contextBroker: { + host: '192.168.1.1', + port: '1026' }, - deviceUpdated = { - id: 'light1', - type: 'Light', - name: 'light1', - service: 'smartGondor', - subservice: 'gardens', - internalId: 'newInternalId', - lazy: [ - { - name: 'pressure', - type: 'Hgmm' - } - ], - active: [ - { - name: 'temperature', - type: 'centigrades' - } - ] + server: { + port: 4041 }, - deviceCommandUpdated = { - id: 'light1', - type: 'Light', - name: 'light1', - service: 'smartGondor', - subservice: 'gardens', - internalId: 'newInternalId', - commands: [ - { - name: 'move', - type: 'command' - } - ], - active: [ - { - name: 'temperature', - type: 'centigrades' - } - ] + types: { + Light: { + commands: [], + lazy: [ + { + name: 'temperature', + type: 'centigrades' + } + ], + active: [ + { + name: 'pressure', + type: 'Hgmm' + } + ], + service: 'smartGondor', + subservice: 'gardens' + }, + Termometer: { + commands: [], + lazy: [ + { + name: 'temp', + type: 'kelvin' + } + ], + active: [], + service: 'smartGondor', + subservice: 'gardens' + } }, - unknownDevice = { - id: 'rotationSensor4', - type: 'Rotation', - name: 'Rotation4', - service: 'dumbMordor', - subservice: 'gardens', - internalId: 'unknownInternalId', + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; +const device1 = { + id: 'light1', + type: 'Light', + service: 'smartGondor', + subservice: 'gardens' +}; +const deviceUpdated = { + id: 'light1', + type: 'Light', + name: 'light1', + service: 'smartGondor', + subservice: 'gardens', + internalId: 'newInternalId', + lazy: [ + { + name: 'pressure', + type: 'Hgmm' + } + ], + active: [ + { + name: 'temperature', + type: 'centigrades' + } + ] +}; +const deviceCommandUpdated = { + id: 'light1', + type: 'Light', + name: 'light1', + service: 'smartGondor', + subservice: 'gardens', + internalId: 'newInternalId', + commands: [ + { + name: 'move', + type: 'command' + } + ], + active: [ + { + name: 'temperature', + type: 'centigrades' + } + ] +}; +const unknownDevice = { + id: 'rotationSensor4', + type: 'Rotation', + name: 'Rotation4', + service: 'dumbMordor', + subservice: 'gardens', + internalId: 'unknownInternalId', - lazy: [], - active: [] - }; + lazy: [], + active: [] +}; -describe('NGSI-v1 - IoT Agent Device Update Registration', function() { - beforeEach(function(done) { +describe('NGSI-v1 - IoT Agent Device Update Registration', function () { + beforeEach(function (done) { logger.setLevel('FATAL'); nock.cleanAll(); @@ -141,58 +141,73 @@ describe('NGSI-v1 - IoT Agent Device Update Registration', function() { .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/NGSI9/registerContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextAvailabilityResponses/registerIoTAgent1Success.json') + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); - iotAgentLib.activate(iotAgentConfig, function(error) { - iotAgentLib.register(device1, function(error) { + iotAgentLib.activate(iotAgentConfig, function (error) { + iotAgentLib.register(device1, function (error) { done(); }); }); }); - afterEach(function(done) { + afterEach(function (done) { nock.cleanAll(); - iotAgentLib.clearAll(function() { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When a device is preregistered and its registration information updated', function() { - beforeEach(function() { + describe('When a device is preregistered and its registration information updated', function () { + beforeEach(function () { contextBrokerMock - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/updateIoTAgent1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/updateIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/updateIoTAgent1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/updateIoTAgent1Success.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateProvisionActiveAttributes1.json')) - .reply(200, + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateProvisionActiveAttributes1.json') + ) + .reply( + 200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateProvisionActiveAttributes1Success.json')); + './test/unit/examples/contextResponses/updateProvisionActiveAttributes1Success.json' + ) + ); }); - it('should register as ContextProvider of its lazy attributes', function(done) { - iotAgentLib.updateRegister(deviceUpdated, function(error) { + it('should register as ContextProvider of its lazy attributes', function (done) { + iotAgentLib.updateRegister(deviceUpdated, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); - it('should store the new values in the registry', function(done) { - iotAgentLib.updateRegister(deviceUpdated, function(error, data) { - iotAgentLib.getDevice(deviceUpdated.id, 'smartGondor', 'gardens', function(error, deviceResult) { + it('should store the new values in the registry', function (done) { + iotAgentLib.updateRegister(deviceUpdated, function (error, data) { + iotAgentLib.getDevice(deviceUpdated.id, 'smartGondor', 'gardens', function (error, deviceResult) { should.not.exist(error); should.exist(deviceResult); deviceResult.internalId.should.equal(deviceUpdated.internalId); @@ -204,34 +219,46 @@ describe('NGSI-v1 - IoT Agent Device Update Registration', function() { }); }); - describe('When a device is preregistered and it is updated with new commands', function() { - beforeEach(function() { + describe('When a device is preregistered and it is updated with new commands', function () { + beforeEach(function () { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateProvisionCommands1.json')) - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/updateProvisionCommands1Success.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateProvisionCommands1.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/updateProvisionCommands1Success.json') + ); contextBrokerMock - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/updateCommands1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/updateCommands1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/updateCommands1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/updateCommands1Success.json' + ) + ); }); - it('should register as ContextProvider of its commands and create the additional attributes', function(done) { - iotAgentLib.updateRegister(deviceCommandUpdated, function(error) { + it('should register as ContextProvider of its commands and create the additional attributes', function (done) { + iotAgentLib.updateRegister(deviceCommandUpdated, function (error) { should.not.exist(error); contextBrokerMock.done(); done(); }); }); - it('should store the new values in the registry', function(done) { - iotAgentLib.updateRegister(deviceCommandUpdated, function(error, data) { - iotAgentLib.getDevice(deviceCommandUpdated.id, 'smartGondor', 'gardens', function(error, deviceResult) { + it('should store the new values in the registry', function (done) { + iotAgentLib.updateRegister(deviceCommandUpdated, function (error, data) { + iotAgentLib.getDevice(deviceCommandUpdated.id, 'smartGondor', 'gardens', function ( + error, + deviceResult + ) { should.not.exist(error); should.exist(deviceResult); deviceResult.internalId.should.equal(deviceUpdated.internalId); @@ -243,47 +270,57 @@ describe('NGSI-v1 - IoT Agent Device Update Registration', function() { }); }); - describe('When a update action is executed in a non registered device', function() { - beforeEach(function() { + describe('When a update action is executed in a non registered device', function () { + beforeEach(function () { contextBrokerMock - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/updateIoTAgent1.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/updateIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/updateIoTAgent1.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/updateIoTAgent1Success.json' + ) + ); }); - it('should return a DEVICE_NOT_FOUND error', function(done) { - iotAgentLib.updateRegister(unknownDevice, function(error) { + it('should return a DEVICE_NOT_FOUND error', function (done) { + iotAgentLib.updateRegister(unknownDevice, function (error) { should.exist(error); error.name.should.equal('DEVICE_NOT_FOUND'); done(); }); }); }); - describe('When a device register is updated in the Context Broker and the request fail to connect', function() { - beforeEach(function() { + describe('When a device register is updated in the Context Broker and the request fail to connect', function () { + beforeEach(function () { contextBrokerMock - .post('/NGSI9/registerContext', - utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/updateIoTAgent1.json')) + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/updateIoTAgent1.json') + ) .reply(500, {}); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', 'gardens') .post('/v1/updateContext') - .reply(200, - utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); }); - it('should return a REGISTRATION_ERROR error in the update action', function(done) { - iotAgentLib.updateRegister(deviceUpdated, function(error) { + it('should return a REGISTRATION_ERROR error in the update action', function (done) { + iotAgentLib.updateRegister(deviceUpdated, function (error) { should.exist(error); error.name.should.equal('REGISTRATION_ERROR'); done(); }); }); }); - describe('When a device register is updated in the Context Broker and the registration is not found', function() { + describe('When a device register is updated in the Context Broker and the registration is not found', function () { it('should create the registration anew'); }); }); diff --git a/test/unit/provisioning/listProvisionedDevices-test.js b/test/unit/provisioning/listProvisionedDevices-test.js index d8ce019d0..d57c4ba8c 100644 --- a/test/unit/provisioning/listProvisionedDevices-test.js +++ b/test/unit/provisioning/listProvisionedDevices-test.js @@ -20,41 +20,40 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; - -/* jshint camelcase: false */ - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - nock = require('nock'), - async = require('async'), - request = require('request'), - contextBrokerMock, - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041, - baseRoot: '/' - }, - types: {}, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }; - -describe('NGSI-v1 - Device provisioning API: List provisioned devices', function() { - var provisioning1Options, - provisioning2Options, - provisioning3Options, - provisioning4Options; - - beforeEach(function(done) { + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const nock = require('nock'); +const async = require('async'); +const request = require('request'); +let contextBrokerMock; +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041, + baseRoot: '/' + }, + types: {}, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; + +describe('NGSI-v1 - Device provisioning API: List provisioned devices', function () { + let provisioning1Options; + let provisioning2Options; + let provisioning3Options; + let provisioning4Options; + + beforeEach(function (done) { provisioning1Options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', @@ -85,60 +84,75 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionFullDevice.json') }; - iotAgentLib.activate(iotAgentConfig, function() { + iotAgentLib.activate(iotAgentConfig, function () { contextBrokerMock = nock('http://192.168.1.1:1026') .post('/NGSI9/registerContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); contextBrokerMock .post('/NGSI9/registerContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); contextBrokerMock .post('/NGSI9/registerContext') - .reply(200, + .reply( + 200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); - - async.series([ - iotAgentLib.clearAll, - async.apply(request, provisioning1Options), - async.apply(request, provisioning2Options), - async.apply(request, provisioning4Options) - ], function(error, results) { - done(); - }); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); + + async.series( + [ + iotAgentLib.clearAll, + async.apply(request, provisioning1Options), + async.apply(request, provisioning2Options), + async.apply(request, provisioning4Options) + ], + function (error, results) { + done(); + } + ); }); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); }); - describe('When a request for the list of provisioned devices arrive', function() { - var options = { + describe('When a request for the list of provisioned devices arrive', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', headers: { 'fiware-service': 'smartGondor', @@ -147,9 +161,9 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function method: 'GET' }; - it('should return all the provisioned devices', function(done) { - request(options, function(error, response, body) { - var parsedBody = JSON.parse(body); + it('should return all the provisioned devices', function (done) { + request(options, function (error, response, body) { + const parsedBody = JSON.parse(body); should.not.exist(error); should.exist(parsedBody.devices); response.statusCode.should.equal(200); @@ -159,11 +173,11 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function }); }); - it('should return all the appropriate field names', function(done) { + it('should return all the appropriate field names', function (done) { /* jshint camelcase:false */ - request(options, function(error, response, body) { - var parsedBody = JSON.parse(body); + request(options, function (error, response, body) { + const parsedBody = JSON.parse(body); should.exist(parsedBody.devices[0].attributes); parsedBody.devices[0].attributes.length.should.equal(1); @@ -184,10 +198,9 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function }); }); - it('should return all the plugin attributes', function(done) { - request(options, function(error, response, body) { - var parsedBody = JSON.parse(body); - + it('should return all the plugin attributes', function (done) { + request(options, function (error, response, body) { + const parsedBody = JSON.parse(body); should.exist(parsedBody.devices[2].attributes[0].entity_name); should.exist(parsedBody.devices[2].attributes[0].entity_type); @@ -201,8 +214,8 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function }); }); }); - describe('When a request for the information about a specific device arrives', function() { - var options = { + describe('When a request for the information about a specific device arrives', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', headers: { 'fiware-service': 'smartGondor', @@ -211,31 +224,23 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function method: 'GET' }; - it('should return all the information on that particular device', function(done) { - request(options, function(error, response, body) { - /* jshint camelcase:false */ - - var parsedBody; - + it('should return all the information on that particular device', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(200); - parsedBody = JSON.parse(body); + const parsedBody = JSON.parse(body); parsedBody.entity_name.should.equal('TheFirstLight'); parsedBody.device_id.should.equal('Light1'); done(); }); }); - it('should return the appropriate attribute fields', function(done) { - request(options, function(error, response, body) { - /* jshint camelcase:false */ - - var parsedBody; - + it('should return the appropriate attribute fields', function (done) { + request(options, function (error, response, body) { should.not.exist(error); - parsedBody = JSON.parse(body); + const parsedBody = JSON.parse(body); should.exist(parsedBody.attributes[0].object_id); parsedBody.attributes[0].object_id.should.equal('attr_name'); parsedBody.attributes[0].name.should.equal('attr_name'); @@ -244,8 +249,8 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function }); }); }); - describe('When a request for a device with plugin attributes arrives', function() { - var options = { + describe('When a request for a device with plugin attributes arrives', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/LightFull', headers: { 'fiware-service': 'smartGondor', @@ -254,15 +259,11 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function method: 'GET' }; - it('should return the appropriate attribute fields', function(done) { - request(options, function(error, response, body) { - /* jshint camelcase:false */ - - var parsedBody; - + it('should return the appropriate attribute fields', function (done) { + request(options, function (error, response, body) { should.not.exist(error); - parsedBody = JSON.parse(body); + const parsedBody = JSON.parse(body); should.exist(parsedBody.attributes[0].entity_name); should.exist(parsedBody.attributes[0].entity_type); should.exist(parsedBody.attributes[1].expression); @@ -275,8 +276,8 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function }); }); }); - describe('When a request for an unexistent device arrives', function() { - var options = { + describe('When a request for an unexistent device arrives', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light84', headers: { 'fiware-service': 'smartGondor', @@ -285,8 +286,8 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function method: 'GET' }; - it('should return a 404 error', function(done) { - request(options, function(error, response, body) { + it('should return a 404 error', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(404); done(); @@ -294,8 +295,8 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function }); }); - describe('When a request for listing all the devices with a limit of 3 arrives', function() { - var options = { + describe('When a request for listing all the devices with a limit of 3 arrives', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices?limit=3', headers: { 'fiware-service': 'smartGondor', @@ -307,7 +308,7 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function function createDeviceRequest(i, callback) { /* jshint camelcase: false */ - var provisioningDeviceOptions = { + const provisioningDeviceOptions = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', headers: { @@ -323,7 +324,7 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function request(provisioningDeviceOptions, callback); } - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') @@ -331,36 +332,40 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function .matchHeader('fiware-servicepath', '/gardens') .post('/NGSI9/registerContext') .times(10) - .reply(200, + .reply( + 200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .post('/v1/updateContext') .times(10) - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); - iotAgentLib.clearAll(function() { - async.times(10, createDeviceRequest, function(error, results) { + iotAgentLib.clearAll(function () { + async.times(10, createDeviceRequest, function (error, results) { done(); }); }); }); - it('should return just 3 devices', function(done) { - request(options, function(error, response, body) { - var parsedBody = JSON.parse(body); + it('should return just 3 devices', function (done) { + request(options, function (error, response, body) { + const parsedBody = JSON.parse(body); should.not.exist(error); parsedBody.devices.length.should.equal(3); done(); }); }); - it('should return a count with the complete number of devices', function(done) { - request(options, function(error, response, body) { - var parsedBody = JSON.parse(body); + it('should return a count with the complete number of devices', function (done) { + request(options, function (error, response, body) { + const parsedBody = JSON.parse(body); should.not.exist(error); parsedBody.count.should.equal(10); done(); @@ -368,8 +373,8 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function }); }); - describe('When a request for listing all the devices with a offset of 3 arrives', function() { - var options = { + describe('When a request for listing all the devices with a offset of 3 arrives', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices?offset=3', headers: { 'fiware-service': 'smartGondor', @@ -379,7 +384,7 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function }; function createDeviceRequest(i, callback) { - var provisioningDeviceOptions = { + const provisioningDeviceOptions = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', headers: { @@ -392,12 +397,12 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function provisioningDeviceOptions.json.devices[0].device_id = provisioningDeviceOptions.json.devices[0].device_id + '_' + i; - request(provisioningDeviceOptions, function(error, response, body) { + request(provisioningDeviceOptions, function (error, response, body) { callback(); }); } - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') @@ -405,23 +410,26 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function .matchHeader('fiware-servicepath', '/gardens') .post('/NGSI9/registerContext') .times(10) - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); - iotAgentLib.clearAll(function() { - async.timesSeries(10, createDeviceRequest, function(error, results) { + iotAgentLib.clearAll(function () { + async.timesSeries(10, createDeviceRequest, function (error, results) { done(); }); }); }); - it('should skip the first 3 devices', function(done) { - request(options, function(error, response, body) { - var parsedBody = JSON.parse(body); + it('should skip the first 3 devices', function (done) { + request(options, function (error, response, body) { + const parsedBody = JSON.parse(body); should.not.exist(error); - for (var i = 0; i < parsedBody.devices.length; i++) { + for (let i = 0; i < parsedBody.devices.length; i++) { ['Light1_0', 'Light1_1', 'Light1_2'].indexOf(parsedBody.devices[i].id).should.equal(-1); } @@ -430,8 +438,8 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function }); }); - describe('When a listing request arrives and there are devices in other service and servicepath', function() { - var options = { + describe('When a listing request arrives and there are devices in other service and servicepath', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', headers: { 'fiware-service': 'smartGondor', @@ -440,7 +448,7 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function method: 'GET' }; - beforeEach(function(done) { + beforeEach(function (done) { provisioning3Options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', @@ -449,23 +457,27 @@ describe('NGSI-v1 - Device provisioning API: List provisioned devices', function 'fiware-servicepath': '/gardens' }, json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/provisionYetAnotherDevice.json') + './test/unit/examples/deviceProvisioningRequests/provisionYetAnotherDevice.json' + ) }; contextBrokerMock .post('/NGSI9/registerContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); - request(provisioning3Options, function(error) { + request(provisioning3Options, function (error) { done(); }); }); - it('should return just the ones in the selected service', function(done) { - request(options, function(error, response, body) { - var parsedBody = JSON.parse(body); + it('should return just the ones in the selected service', function (done) { + request(options, function (error, response, body) { + const parsedBody = JSON.parse(body); should.not.exist(error); response.statusCode.should.equal(200); parsedBody.devices.length.should.equal(3); diff --git a/test/unit/provisioning/provisionDeviceMultientity-test.js b/test/unit/provisioning/provisionDeviceMultientity-test.js index 0bf4992eb..ece9269a1 100644 --- a/test/unit/provisioning/provisionDeviceMultientity-test.js +++ b/test/unit/provisioning/provisionDeviceMultientity-test.js @@ -20,85 +20,100 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), +/* eslint-disable no-unused-vars */ - should = require('should'), - nock = require('nock'), - request = require('request'), - contextBrokerMock, - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041, - baseRoot: '/' - }, - types: {}, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' - }; +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const nock = require('nock'); +const request = require('request'); +let contextBrokerMock; +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041, + baseRoot: '/' + }, + types: {}, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; -describe('NGSI-v1 - Device provisioning API: Provision devices', function() { - beforeEach(function(done) { +describe('NGSI-v1 - Device provisioning API: Provision devices', function () { + beforeEach(function (done) { nock.cleanAll(); - iotAgentLib.activate(iotAgentConfig, function() { + iotAgentLib.activate(iotAgentConfig, function () { iotAgentLib.clearAll(done); }); }); - afterEach(function(done) { + afterEach(function (done) { nock.cleanAll(); iotAgentLib.setProvisioningHandler(); iotAgentLib.deactivate(done); }); - describe('When a device provisioning request with all the required data arrives to the IoT Agent', function() { - beforeEach(function() { + describe('When a device provisioning request with all the required data arrives to the IoT Agent', function () { + beforeEach(function () { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerProvisionedDevice.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile( + './test/unit/examples/contextAvailabilityRequests/registerProvisionedDevice.json' + ) + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/createProvisionedDeviceMultientity.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .post( + '/v1/updateContext', + utils.readExampleFile( + './test/unit/examples/contextRequests/createProvisionedDeviceMultientity.json' + ) + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); }); - var options = { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/' + - 'provisionNewDeviceMultientity.json'), + json: utils.readExampleFile( + './test/unit/examples/deviceProvisioningRequests/provisionNewDeviceMultientity.json' + ), headers: { 'fiware-service': 'smartGondor', 'fiware-servicepath': '/gardens' } }; - it('should add the device to the devices list', function(done) { - request(options, function(error, response, body) { + it('should add the device to the devices list', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(201); - iotAgentLib.listDevices('smartGondor', '/gardens', function(error, results) { + iotAgentLib.listDevices('smartGondor', '/gardens', function (error, results) { results.devices.length.should.equal(1); done(); }); @@ -106,6 +121,3 @@ describe('NGSI-v1 - Device provisioning API: Provision devices', function() { }); }); }); - - - diff --git a/test/unit/provisioning/removeProvisionedDevice-test.js b/test/unit/provisioning/removeProvisionedDevice-test.js index 8b0cb32a7..e2d27533d 100644 --- a/test/unit/provisioning/removeProvisionedDevice-test.js +++ b/test/unit/provisioning/removeProvisionedDevice-test.js @@ -20,133 +20,154 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - nock = require('nock'), - async = require('async'), - request = require('request'), - contextBrokerMock, - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041, - baseRoot: '/' + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const nock = require('nock'); +const async = require('async'); +const request = require('request'); +let contextBrokerMock; +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041, + baseRoot: '/' + }, + types: {}, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; + +describe('NGSI-v1 - Device provisioning API: Remove provisioned devices', function () { + const provisioning1Options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' }, - types: {}, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json') }; - -describe('NGSI-v1 - Device provisioning API: Remove provisioned devices', function() { - var provisioning1Options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - }, - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json') + const provisioning2Options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' }, - provisioning2Options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - }, - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionAnotherDevice.json') + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionAnotherDevice.json') + }; + const provisioning3Options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' }, - provisioning3Options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - }, - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/' + - 'provisionDeviceActiveAtts.json') - }; + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionDeviceActiveAtts.json') + }; - beforeEach(function(done) { - iotAgentLib.activate(iotAgentConfig, function() { + beforeEach(function (done) { + iotAgentLib.activate(iotAgentConfig, function () { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/NGSI9/registerContext', - utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerProvisionedDevice.json')) - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile( + './test/unit/examples/contextAvailabilityRequests/registerProvisionedDevice.json' + ) + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/NGSI9/registerContext', - utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerProvisionedDevice2.json')) - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile( + './test/unit/examples/contextAvailabilityRequests/registerProvisionedDevice2.json' + ) + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/NGSI9/registerContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/unregisterDevice1Success.json')); + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/unregisterDevice1Success.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); - - async.series([ - iotAgentLib.clearAll, - async.apply(request, provisioning1Options), - async.apply(request, provisioning2Options), - async.apply(request, provisioning3Options) - ], function(error, results) { - done(); - }); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); + + async.series( + [ + iotAgentLib.clearAll, + async.apply(request, provisioning1Options), + async.apply(request, provisioning2Options), + async.apply(request, provisioning3Options) + ], + function (error, results) { + done(); + } + ); }); }); - afterEach(function(done) { + afterEach(function (done) { iotAgentLib.deactivate(done); }); - describe('When a request to remove a provision device arrives', function() { - var options = { + describe('When a request to remove a provision device arrives', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', headers: { 'fiware-service': 'smartGondor', @@ -155,17 +176,17 @@ describe('NGSI-v1 - Device provisioning API: Remove provisioned devices', functi method: 'DELETE' }; - it('should return a 200 OK and no errors', function(done) { - request(options, function(error, response, body) { + it('should return a 200 OK and no errors', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(204); done(); }); }); - it('should remove the device from the provisioned devices list', function(done) { - request(options, function(error, response, body) { - var options = { + it('should remove the device from the provisioned devices list', function (done) { + request(options, function (error, response, body) { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', headers: { 'fiware-service': 'smartGondor', @@ -174,17 +195,17 @@ describe('NGSI-v1 - Device provisioning API: Remove provisioned devices', functi method: 'GET' }; - request(options, function(error, response, body) { - var parsedBody = JSON.parse(body); + request(options, function (error, response, body) { + const parsedBody = JSON.parse(body); parsedBody.devices.length.should.equal(2); done(); }); }); }); - it('should return a 404 error when asking for the particular device', function(done) { - request(options, function(error, response, body) { - var options = { + it('should return a 404 error when asking for the particular device', function (done) { + request(options, function (error, response, body) { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', headers: { 'fiware-service': 'smartGondor', @@ -193,7 +214,7 @@ describe('NGSI-v1 - Device provisioning API: Remove provisioned devices', functi method: 'GET' }; - request(options, function(error, response, body) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(404); done(); @@ -202,8 +223,8 @@ describe('NGSI-v1 - Device provisioning API: Remove provisioned devices', functi }); }); - describe('When a request to remove a provision device arrives. Device without lazy atts or commands', function() { - var options = { + describe('When a request to remove a provision device arrives. Device without lazy atts or commands', function () { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light3', headers: { 'fiware-service': 'smartGondor', @@ -212,8 +233,8 @@ describe('NGSI-v1 - Device provisioning API: Remove provisioned devices', functi method: 'DELETE' }; - it('should return a 200 OK and no errors', function(done) { - request(options, function(error, response, body) { + it('should return a 200 OK and no errors', function (done) { + request(options, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(204); done(); diff --git a/test/unit/provisioning/singleConfigurationMode-test.js b/test/unit/provisioning/singleConfigurationMode-test.js index 11d44df2f..42bd712b9 100644 --- a/test/unit/provisioning/singleConfigurationMode-test.js +++ b/test/unit/provisioning/singleConfigurationMode-test.js @@ -20,70 +20,68 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; - -/* jshint camelcase: false */ - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - - should = require('should'), - nock = require('nock'), - contextBrokerMock, - request = require('request'), - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041, - baseRoot: '/' - }, - types: {}, - service: 'smartGondor', - singleConfigurationMode: true, - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const nock = require('nock'); +let contextBrokerMock; +const request = require('request'); +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026' }, - groupCreation = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionFullGroup.json'), - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - } + server: { + port: 4041, + baseRoot: '/' }, - deviceCreation = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json'), - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - } - }; - -describe('NGSI-v1 - Provisioning API: Single service mode', function() { - beforeEach(function(done) { + types: {}, + service: 'smartGondor', + singleConfigurationMode: true, + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; +const groupCreation = { + url: 'http://localhost:4041/iot/services', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionFullGroup.json'), + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } +}; +const deviceCreation = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json'), + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } +}; + +describe('NGSI-v1 - Provisioning API: Single service mode', function () { + beforeEach(function (done) { nock.cleanAll(); - iotAgentLib.activate(iotAgentConfig, function() { + iotAgentLib.activate(iotAgentConfig, function () { iotAgentLib.clearAll(done); }); }); - afterEach(function(done) { + afterEach(function (done) { nock.cleanAll(); iotAgentLib.setProvisioningHandler(); iotAgentLib.deactivate(done); }); - describe('When a new configuration arrives to an already configured subservice', function() { - var groupCreationDuplicated = { + describe('When a new configuration arrives to an already configured subservice', function () { + const groupCreationDuplicated = { url: 'http://localhost:4041/iot/services', method: 'POST', json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionDuplicateGroup.json'), @@ -93,12 +91,12 @@ describe('NGSI-v1 - Provisioning API: Single service mode', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { request(groupCreation, done); }); - it('should raise a DUPLICATE_GROUP error', function(done) { - request(groupCreationDuplicated, function(error, response, body) { + it('should raise a DUPLICATE_GROUP error', function (done) { + request(groupCreationDuplicated, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(409); should.exist(body.name); @@ -107,8 +105,8 @@ describe('NGSI-v1 - Provisioning API: Single service mode', function() { }); }); }); - describe('When a device is provisioned with an ID that already exists in the configuration', function() { - var deviceCreationDuplicated = { + describe('When a device is provisioned with an ID that already exists in the configuration', function () { + const deviceCreationDuplicated = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionDuplicatedDev.json'), @@ -118,32 +116,38 @@ describe('NGSI-v1 - Provisioning API: Single service mode', function() { } }; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://unexistentHost:1026') .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') .post('/NGSI9/registerContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); - request(groupCreation, function(error) { - request(deviceCreation, function(error, response, body) { + request(groupCreation, function (error) { + request(deviceCreation, function (error, response, body) { done(); }); }); }); - it('should raise a DUPLICATE_DEVICE_ID error', function(done) { - request(deviceCreationDuplicated, function(error, response, body) { + it('should raise a DUPLICATE_DEVICE_ID error', function (done) { + request(deviceCreationDuplicated, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(409); should.exist(body.name); @@ -152,117 +156,133 @@ describe('NGSI-v1 - Provisioning API: Single service mode', function() { }); }); }); - describe('When a device is provisioned with an ID that exists globally but not in the configuration', function() { - var alternativeDeviceCreation = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json'), - headers: { - 'fiware-service': 'AlternateService', - 'fiware-servicepath': '/testingPath' - } - }, - alternativeGroupCreation = { - url: 'http://localhost:4041/iot/services', - method: 'POST', - json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionFullGroup.json'), - headers: { - 'fiware-service': 'AlternateService', - 'fiware-servicepath': '/testingPath' - } - }; - - beforeEach(function(done) { + describe('When a device is provisioned with an ID that exists globally but not in the configuration', function () { + const alternativeDeviceCreation = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json'), + headers: { + 'fiware-service': 'AlternateService', + 'fiware-servicepath': '/testingPath' + } + }; + const alternativeGroupCreation = { + url: 'http://localhost:4041/iot/services', + method: 'POST', + json: utils.readExampleFile('./test/unit/examples/groupProvisioningRequests/provisionFullGroup.json'), + headers: { + 'fiware-service': 'AlternateService', + 'fiware-servicepath': '/testingPath' + } + }; + + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') .post('/NGSI9/registerContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'AlternateService') .matchHeader('fiware-servicepath', '/testingPath') .post('/NGSI9/registerContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'AlternateService') .matchHeader('fiware-servicepath', '/testingPath') .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); - - request(groupCreation, function(error) { - request(deviceCreation, function(error, response, body) { - request(alternativeGroupCreation, function(error, response, body) { + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); + + request(groupCreation, function (error) { + request(deviceCreation, function (error, response, body) { + request(alternativeGroupCreation, function (error, response, body) { done(); }); }); }); }); - it('should return a 201 OK', function(done) { - request(alternativeDeviceCreation, function(error, response, body) { + it('should return a 201 OK', function (done) { + request(alternativeDeviceCreation, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(201); done(); }); }); }); - describe('When a device is provisioned without a type and with a default configuration type', function() { - var getDevice = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', - method: 'GET', - headers: { - 'fiware-service': 'TestService', - 'fiware-servicepath': '/testingPath' - } - }, - oldType; - - beforeEach(function(done) { + describe('When a device is provisioned without a type and with a default configuration type', function () { + const getDevice = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', + method: 'GET', + headers: { + 'fiware-service': 'TestService', + 'fiware-servicepath': '/testingPath' + } + }; + let oldType; + + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://unexistentHost:1026') .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') .post('/NGSI9/registerContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') .post('/v1/updateContext') - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); oldType = deviceCreation.json.devices[0].entity_type; delete deviceCreation.json.devices[0].entity_type; request(groupCreation, done); }); - afterEach(function() { + afterEach(function () { deviceCreation.json.devices[0].entity_type = oldType; }); - it('should be provisioned with the default type', function(done) { - request(deviceCreation, function(error, response, body) { - request(getDevice, function(error, response, body) { - var parsedBody; - - parsedBody = JSON.parse(body); + it('should be provisioned with the default type', function (done) { + request(deviceCreation, function (error, response, body) { + request(getDevice, function (error, response, body) { + const parsedBody = JSON.parse(body); parsedBody.entity_type.should.equal('SensorMachine'); @@ -271,43 +291,56 @@ describe('NGSI-v1 - Provisioning API: Single service mode', function() { }); }); }); - describe('When a device is provisioned for a configuration', function() { - beforeEach(function(done) { + describe('When a device is provisioned for a configuration', function () { + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://unexistentHost:1026') .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerProvisionedDeviceWithGroup.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile( + './test/unit/examples/contextAvailabilityRequests/registerProvisionedDeviceWithGroup.json' + ) + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/createProvisionedDeviceWithGroupAndStatic.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .post( + '/v1/updateContext', + utils.readExampleFile( + './test/unit/examples/contextRequests/createProvisionedDeviceWithGroupAndStatic.json' + ) + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); request(groupCreation, done); }); - it('should not raise any error', function(done) { - request(deviceCreation, function(error, response, body) { + it('should not raise any error', function (done) { + request(deviceCreation, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(201); done(); }); }); - it('should send the mixed data to the Context Broker', function(done) { - request(deviceCreation, function(error, response, body) { + it('should send the mixed data to the Context Broker', function (done) { + request(deviceCreation, function (error, response, body) { contextBrokerMock.done(); done(); }); }); - }); }); diff --git a/test/unit/provisioning/updateProvisionedDevices-test.js b/test/unit/provisioning/updateProvisionedDevices-test.js index 3f19e44ef..17486ad80 100644 --- a/test/unit/provisioning/updateProvisionedDevices-test.js +++ b/test/unit/provisioning/updateProvisionedDevices-test.js @@ -20,126 +20,148 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; - -var iotAgentLib = require('../../../lib/fiware-iotagent-lib'), - utils = require('../../tools/utils'), - should = require('should'), - nock = require('nock'), - async = require('async'), - request = require('request'), - contextBrokerMock, - iotAgentConfig = { - logLevel: 'FATAL', - contextBroker: { - host: '192.168.1.1', - port: '1026' - }, - server: { - port: 4041, - baseRoot: '/' + +/* eslint-disable no-unused-vars */ + +const iotAgentLib = require('../../../lib/fiware-iotagent-lib'); +const utils = require('../../tools/utils'); +const should = require('should'); +const nock = require('nock'); +const async = require('async'); +const request = require('request'); +let contextBrokerMock; +const iotAgentConfig = { + logLevel: 'FATAL', + contextBroker: { + host: '192.168.1.1', + port: '1026' + }, + server: { + port: 4041, + baseRoot: '/' + }, + types: {}, + service: 'smartGondor', + subservice: 'gardens', + providerUrl: 'http://smartGondor.com', + deviceRegistrationDuration: 'P1M' +}; + +describe('NGSI-v1 - Device provisioning API: Update provisioned devices', function () { + const provisioning1Options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' }, - types: {}, - service: 'smartGondor', - subservice: 'gardens', - providerUrl: 'http://smartGondor.com', - deviceRegistrationDuration: 'P1M' + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json') }; - -describe('NGSI-v1 - Device provisioning API: Update provisioned devices', function() { - var provisioning1Options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - }, - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionNewDevice.json') + const provisioning2Options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' }, - provisioning2Options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - }, - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionAnotherDevice.json') + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionAnotherDevice.json') + }; + const provisioning3Options = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', + method: 'POST', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' }, - provisioning3Options = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices', - method: 'POST', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - }, - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice2.json') - }; + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/provisionMinimumDevice2.json') + }; - beforeEach(function(done) { + beforeEach(function (done) { nock.cleanAll(); - iotAgentLib.activate(iotAgentConfig, function() { + iotAgentLib.activate(iotAgentConfig, function () { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/NGSI9/registerContext', - utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerProvisionedDevice.json')) - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile( + './test/unit/examples/contextAvailabilityRequests/registerProvisionedDevice.json' + ) + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/NGSI9/registerContext', - utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/registerProvisionedDevice2.json')) - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile( + './test/unit/examples/contextAvailabilityRequests/registerProvisionedDevice2.json' + ) + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/registerProvisionedDeviceSuccess.json' + ) + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/NGSI9/registerContext', - utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/updateIoTAgent2.json')) - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/updateIoTAgent1Success.json')); - - async.series([ - iotAgentLib.clearAll, - async.apply(request, provisioning1Options), - async.apply(request, provisioning2Options) - ], done); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/updateIoTAgent2.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/updateIoTAgent1Success.json' + ) + ); + + async.series( + [ + iotAgentLib.clearAll, + async.apply(request, provisioning1Options), + async.apply(request, provisioning2Options) + ], + done + ); }); }); - afterEach(function(done) { - iotAgentLib.clearAll(function() { + afterEach(function (done) { + iotAgentLib.clearAll(function () { iotAgentLib.deactivate(done); }); }); - describe('When a request to update a provision device arrives', function() { - var optionsUpdate = { + describe('When a request to update a provision device arrives', function () { + const optionsUpdate = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', method: 'PUT', headers: { @@ -149,34 +171,43 @@ describe('NGSI-v1 - Device provisioning API: Update provisioned devices', functi json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/updateProvisionDevice.json') }; - beforeEach(function() { + beforeEach(function () { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateActiveAttributes.json')) - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/updateActiveAttributesSuccess.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateActiveAttributes.json') + ) + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/updateActiveAttributesSuccess.json') + ); contextBrokerMock - .post('/NGSI9/registerContext', utils.readExampleFile( - './test/unit/examples/contextAvailabilityRequests/updateIoTAgent3.json')) - .reply(200, utils.readExampleFile( - './test/unit/examples/contextAvailabilityResponses/updateIoTAgent1Success.json')); + .post( + '/NGSI9/registerContext', + utils.readExampleFile('./test/unit/examples/contextAvailabilityRequests/updateIoTAgent3.json') + ) + .reply( + 200, + utils.readExampleFile( + './test/unit/examples/contextAvailabilityResponses/updateIoTAgent1Success.json' + ) + ); }); - it('should return a 200 OK and no errors', function(done) { - request(optionsUpdate, function(error, response, body) { + it('should return a 200 OK and no errors', function (done) { + request(optionsUpdate, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(204); done(); }); }); - it('should have updated the data when asking for the particular device', function(done) { - request(optionsUpdate, function(error, response, body) { - var options = { + it('should have updated the data when asking for the particular device', function (done) { + request(optionsUpdate, function (error, response, body) { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', headers: { 'fiware-service': 'smartGondor', @@ -185,10 +216,10 @@ describe('NGSI-v1 - Device provisioning API: Update provisioned devices', functi method: 'GET' }; - request(options, function(error, response, body) { + request(options, function (error, response, body) { /* jshint camelcase:false */ - var parsedBody = JSON.parse(body); + const parsedBody = JSON.parse(body); parsedBody.entity_name.should.equal('ANewLightName'); parsedBody.timezone.should.equal('Europe/Madrid'); done(); @@ -196,9 +227,9 @@ describe('NGSI-v1 - Device provisioning API: Update provisioned devices', functi }); }); - it('should not modify the attributes not present in the update request', function(done) { - request(optionsUpdate, function(error, response, body) { - var options = { + it('should not modify the attributes not present in the update request', function (done) { + request(optionsUpdate, function (error, response, body) { + const options = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', headers: { 'fiware-service': 'smartGondor', @@ -207,10 +238,10 @@ describe('NGSI-v1 - Device provisioning API: Update provisioned devices', functi method: 'GET' }; - request(options, function(error, response, body) { + request(options, function (error, response, body) { /* jshint camelcase:false */ - var parsedBody = JSON.parse(body); + const parsedBody = JSON.parse(body); parsedBody.entity_type.should.equal('TheLightType'); parsedBody.service.should.equal('smartGondor'); done(); @@ -218,8 +249,8 @@ describe('NGSI-v1 - Device provisioning API: Update provisioned devices', functi }); }); }); - describe('When an update request arrives with a new Device ID', function() { - var optionsUpdate = { + describe('When an update request arrives with a new Device ID', function () { + const optionsUpdate = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', method: 'PUT', headers: { @@ -227,19 +258,20 @@ describe('NGSI-v1 - Device provisioning API: Update provisioned devices', functi 'fiware-servicepath': '/gardens' }, json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/updateProvisionDeviceWithId.json') + './test/unit/examples/deviceProvisioningRequests/updateProvisionDeviceWithId.json' + ) }; - it('should raise a 400 error', function(done) { - request(optionsUpdate, function(error, response, body) { + it('should raise a 400 error', function (done) { + request(optionsUpdate, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(400); done(); }); }); }); - describe('When a wrong update request payload arrives', function() { - var optionsUpdate = { + describe('When a wrong update request payload arrives', function () { + const optionsUpdate = { url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/Light1', method: 'PUT', headers: { @@ -247,11 +279,12 @@ describe('NGSI-v1 - Device provisioning API: Update provisioned devices', functi 'fiware-servicepath': '/gardens' }, json: utils.readExampleFile( - './test/unit/examples/deviceProvisioningRequests/updateProvisionDeviceWrong.json') + './test/unit/examples/deviceProvisioningRequests/updateProvisionDeviceWrong.json' + ) }; - it('should raise a 400 error', function(done) { - request(optionsUpdate, function(error, response, body) { + it('should raise a 400 error', function (done) { + request(optionsUpdate, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(400); done(); @@ -259,65 +292,67 @@ describe('NGSI-v1 - Device provisioning API: Update provisioned devices', functi }); }); - describe('When a device is provisioned without attributes and new ones are added through an update', function() { - var optionsUpdate = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/MicroLight2', - method: 'PUT', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - }, - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/updateMinimumDevice.json') + describe('When a device is provisioned without attributes and new ones are added through an update', function () { + const optionsUpdate = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/MicroLight2', + method: 'PUT', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' }, - optionsGetDevice = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/MicroLight2', - method: 'GET', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }; - - beforeEach(function(done) { + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/updateMinimumDevice.json') + }; + const optionsGetDevice = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/MicroLight2', + method: 'GET', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateProvisionMinimumDevice.json')) - .reply(200, + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateProvisionMinimumDevice.json') + ) + .reply( + 200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateProvisionMinimumDeviceSuccess.json')); + './test/unit/examples/contextResponses/updateProvisionMinimumDeviceSuccess.json' + ) + ); - async.series([ - iotAgentLib.clearAll, - async.apply(request, provisioning3Options) - ], done); + async.series([iotAgentLib.clearAll, async.apply(request, provisioning3Options)], done); }); - it('should not raise any error', function(done) { - request(optionsUpdate, function(error, response, body) { + it('should not raise any error', function (done) { + request(optionsUpdate, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(204); done(); }); }); - it('should provision the attributes appropriately', function(done) { - request(optionsUpdate, function(error, response, body) { - request(optionsGetDevice, function(error, response, body) { - var parsedBody; + it('should provision the attributes appropriately', function (done) { + request(optionsUpdate, function (error, response, body) { + request(optionsGetDevice, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(200); - parsedBody = JSON.parse(body); + const parsedBody = JSON.parse(body); parsedBody.attributes.length.should.equal(1); parsedBody.attributes[0].name.should.equal('newAttribute'); @@ -325,8 +360,8 @@ describe('NGSI-v1 - Device provisioning API: Update provisioned devices', functi }); }); }); - it('should create the initial values for the attributes in the Context Broker', function(done) { - request(optionsUpdate, function(error, response, body) { + it('should create the initial values for the attributes in the Context Broker', function (done) { + request(optionsUpdate, function (error, response, body) { should.not.exist(error); contextBrokerMock.done(); done(); @@ -334,60 +369,62 @@ describe('NGSI-v1 - Device provisioning API: Update provisioned devices', functi }); }); - describe('When a device is updated to add static attributes', function() { + describe('When a device is updated to add static attributes', function () { /* jshint camelcase: false */ - var optionsUpdate = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/MicroLight2', - method: 'PUT', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - }, - json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/updateDeviceStatic.json') + const optionsUpdate = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/MicroLight2', + method: 'PUT', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' }, - optionsGetDevice = { - url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/MicroLight2', - method: 'GET', - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }; - - beforeEach(function(done) { + json: utils.readExampleFile('./test/unit/examples/deviceProvisioningRequests/updateDeviceStatic.json') + }; + const optionsGetDevice = { + url: 'http://localhost:' + iotAgentConfig.server.port + '/iot/devices/MicroLight2', + method: 'GET', + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + + beforeEach(function (done) { nock.cleanAll(); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v1/updateContext') - .reply(200, - utils.readExampleFile( - './test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json')); + .reply( + 200, + utils.readExampleFile('./test/unit/examples/contextResponses/createProvisionedDeviceSuccess.json') + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/unit/examples/contextRequests/updateProvisionDeviceStatic.json')) - .reply(200, + .post( + '/v1/updateContext', + utils.readExampleFile('./test/unit/examples/contextRequests/updateProvisionDeviceStatic.json') + ) + .reply( + 200, utils.readExampleFile( - './test/unit/examples/contextResponses/updateProvisionMinimumDeviceSuccess.json')); + './test/unit/examples/contextResponses/updateProvisionMinimumDeviceSuccess.json' + ) + ); - async.series([ - iotAgentLib.clearAll, - async.apply(request, provisioning3Options) - ], done); + async.series([iotAgentLib.clearAll, async.apply(request, provisioning3Options)], done); }); - it('should provision the attributes appropriately', function(done) { - request(optionsUpdate, function(error, response, body) { - request(optionsGetDevice, function(error, response, body) { - var parsedBody; + it('should provision the attributes appropriately', function (done) { + request(optionsUpdate, function (error, response, body) { + request(optionsGetDevice, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(200); - parsedBody = JSON.parse(body); + const parsedBody = JSON.parse(body); parsedBody.static_attributes.length.should.equal(3); parsedBody.static_attributes[0].name.should.equal('cellID');