diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 00000000..8238852e --- /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/bin/iotaJsonTester.js b/bin/iotaJsonTester.js index 3607bf01..c8ecedc2 100755 --- a/bin/iotaJsonTester.js +++ b/bin/iotaJsonTester.js @@ -86,7 +86,7 @@ function checkConnection(fn) { } else { console.log('Please, check your configuration and connect before using MQTT commands.'); } - } + }; } function singleMeasure(commands) { @@ -96,9 +96,7 @@ function singleMeasure(commands) { } function parseMultipleAttributes(attributeString) { - var result, - attributes, - attribute; + var result, attributes, attribute; if (!attributeString) { result = null; @@ -125,7 +123,10 @@ function multipleMeasure(commands) { function connect(commands) { console.log('\nConnecting to MQTT Broker...'); - mqttClient = mqtt.connect('mqtt://' + config.host, defaultConfig.mqtt.options); + mqttClient = mqtt.connect( + 'mqtt://' + config.host, + defaultConfig.mqtt.options + ); clUtils.prompt(); } @@ -135,33 +136,34 @@ function exitClient() { } var commands = { - 'config': { + config: { parameters: ['host', 'port', 'apiKey', 'deviceId'], description: '\tConfigure the client to emulate the selected device, connecting to the given host.', handler: setConfig }, - 'showConfig': { + showConfig: { parameters: [], description: '\tConfigure the client to emulate the selected device, connecting to the given host.', handler: getConfig }, - 'connect': { + connect: { parameters: [], description: '\tConnect to the MQTT broker.', handler: connect }, - 'singleMeasure': { + singleMeasure: { parameters: ['attribute', 'value'], description: '\tSend the given value for the selected attribute to the MQTT broker.', handler: checkConnection(singleMeasure) }, - 'multipleMeasure': { + multipleMeasure: { parameters: ['attributes'], - description: '\tSend a collection of attributes to the MQTT broker, using JSON format. The "attributes"\n' + + description: + '\tSend a collection of attributes to the MQTT broker, using JSON format. The "attributes"\n' + '\tstring should have the following syntax: name=value[;name=value]*', handler: checkConnection(multipleMeasure) }, - 'exit': { + exit: { parameters: [], description: '\tExit the client', handler: exitClient diff --git a/client-config.js b/client-config.js index 4e2713fb..0b074f11 100644 --- a/client-config.js +++ b/client-config.js @@ -34,6 +34,6 @@ config.mqtt = { config.device = { id: 'myDeviceId', apikey: '1234' -} +}; module.exports = config; diff --git a/config.js b/config.js index 1f949fbd..9cbe0c68 100644 --- a/config.js +++ b/config.js @@ -37,8 +37,8 @@ config.mqtt = { /** * Activating thinkingThingsPlugin flag. When it is set to true the constraint devices sends an HTTP POST request * to the server with a Content-Type, containing a field name and a payload. The payload can be divided in modules, - * each one of them responsible for a single measure. Modules are separated by the '#' character, and all of them - * consists of a series of parameters separated by commas. + * each one of them responsible for a single measure. Modules are separated by the '#' character, and all of them + * consists of a series of parameters separated by commas. */ thinkingThingsPlugin: true, /** @@ -46,7 +46,7 @@ config.mqtt = { */ qos: 0, /** - * Retain flag. (default is true.) Normally if a publisher publishes a message to a topic, and no one is + * Retain flag. (default is true.) Normally if a publisher publishes a message to a topic, and no one is * subscribed to that topic (i.e retain flag is set to false) the message is simply discarded by the broker. * The publisher can tell the broker to keep the last message on that topic by setting the retained message flag to true . */ @@ -84,7 +84,7 @@ config.amqp = { /** * durable queue flag (default is false). */ - options: {durable: true} + options: { durable: true } }; /** @@ -94,7 +94,7 @@ config.http = { /** * South Port where the Ultralight transport binding for HTTP will be listening for device requests. */ - port: 7896, + port: 7896 /** * HTTP Timeout for the http command endpoint (in miliseconds). */ @@ -116,22 +116,22 @@ config.iota = { * the IoT Agent will send the device data. */ contextBroker: { - /** - * Host where the Context Broker is located. - */ + /** + * Host where the Context Broker is located. + */ host: 'localhost', - /** - * Port where the Context Broker is listening. - */ + /** + * Port where the Context Broker is listening. + */ port: '1026' }, /** * Configuration of the North Port of the IoT Agent. */ server: { - /** - * Port where the IoT Agent will be listening for NGSI and Provisioning requests. - */ + /** + * Port where the IoT Agent will be listening for NGSI and Provisioning requests. + */ port: 4041 }, /** @@ -152,10 +152,10 @@ config.iota = { * 'mongodb'. */ mongodb: { - /** - * Host where MongoDB is located. If the MongoDB used is a replicaSet, this property will contain a - * comma-separated list of the instance names or IPs. - */ + /** + * Host where MongoDB is located. If the MongoDB used is a replicaSet, this property will contain a + * comma-separated list of the instance names or IPs. + */ host: 'localhost', /** * Port where MongoDB is listening. In the case of a replicaSet, all the instances are supposed to be listening diff --git a/docs/usermanual.md b/docs/usermanual.md index 1e945c28..a8fcc27b 100644 --- a/docs/usermanual.md +++ b/docs/usermanual.md @@ -441,6 +441,16 @@ Removes `node_modules` and `coverage` folders, and `package-lock.json` file so 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 +``` + ## New transport development ### Overview diff --git a/ghpages/javascripts/scale.fix.js b/ghpages/javascripts/scale.fix.js index 87a40ca7..39cdc766 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) { iotAgentLib.update(device.name, device.type, '', values, device, updateCommandHandler); @@ -225,9 +236,10 @@ function handleIncomingMeasure(req, res, next) { } function isCommand(req, res, next) { - if (req.path === - (config.getConfig().iota.defaultResource || constants.HTTP_MEASURE_PATH) + constants.HTTP_COMMANDS_PATH) { - + if ( + req.path === + (config.getConfig().iota.defaultResource || constants.HTTP_MEASURE_PATH) + constants.HTTP_COMMANDS_PATH + ) { req.isCommand = true; } @@ -235,7 +247,6 @@ function isCommand(req, res, next) { } function sendConfigurationToDevice(apiKey, deviceId, results, callback) { - function handleDeviceResponse(innerCallback) { return function(error, response, body) { if (error) { @@ -281,12 +292,18 @@ function handleConfigurationRequest(req, res, next) { } } iotaUtils.retrieveDevice(req.deviceId, req.apiKey, transport, function(error, device) { - if (error) { - next(error); - } else { - iotaUtils.manageConfiguration( - req.apiKey, req.deviceId, device, req.jsonPayload, sendConfigurationToDevice, replyToDevice); - } + if (error) { + next(error); + } else { + iotaUtils.manageConfiguration( + req.apiKey, + req.deviceId, + device, + req.jsonPayload, + sendConfigurationToDevice, + replyToDevice + ); + } }); } @@ -331,13 +348,12 @@ function deviceProvisioningHandler(device, callback) { * add the command information to the return payload. Otherwise it returns an empty payload. */ function returnCommands(req, res, next) { - function updateCommandStatus(device, commandList) { - var updates, - cleanCommands; + var updates, cleanCommands; function createCommandUpdate(command) { - return apply(iotAgentLib.setCommandResult, + return apply( + iotAgentLib.setCommandResult, device.name, device.resource, req.query.k, @@ -349,11 +365,7 @@ function returnCommands(req, res, next) { } function cleanCommand(command) { - return apply(iotAgentLib.removeCommand, - device.service, - device.subservice, - device.id, - command.name); + return apply(iotAgentLib.removeCommand, device.service, device.subservice, device.id, command.name); } updates = commandList.map(createCommandUpdate); @@ -361,13 +373,21 @@ function returnCommands(req, res, next) { if (updates) { async.parallel(updates.concat(cleanCommands), function(error, results) { if (error) { - config.getLogger().error(context, - 'Error updating command status after delivering commands for device [%s]', - device.id); + config + .getLogger() + .error( + context, + 'Error updating command status after delivering commands for device [%s]', + device.id + ); } else { - config.getLogger().debug(context, - 'Command status updated successfully after delivering command list to device [%s]', - device.id); + config + .getLogger() + .debug( + context, + 'Command status updated successfully after delivering command list to device [%s]', + device.id + ); } }); } @@ -392,21 +412,15 @@ function returnCommands(req, res, next) { } } if (req.query && req.query.getCmd === '1') { - iotAgentLib.commandQueue( - req.device.service, - req.device.subservice, - req.deviceId, - function(error, list) { - if (error || !list || list.count === 0) { - res.status(200).send(''); - } else { - res.status(200).send( - JSON.stringify(list.commands.map(parseCommand).reduce(concatCommand, {})) - ); + iotAgentLib.commandQueue(req.device.service, req.device.subservice, req.deviceId, function(error, list) { + if (error || !list || list.count === 0) { + res.status(200).send(''); + } else { + res.status(200).send(JSON.stringify(list.commands.map(parseCommand).reduce(concatCommand, {}))); - process.nextTick(updateCommandStatus.bind(null, req.device, list.commands)); - } - }); + process.nextTick(updateCommandStatus.bind(null, req.device, list.commands)); + } + }); } else { res.status(200).send(''); } @@ -422,8 +436,9 @@ function start(callback) { }; if (!config.getConfig().http) { - config.getLogger().fatal(context, - 'GLOBAL-002: Configuration error. Configuration object [config.http] is missing'); + config + .getLogger() + .fatal(context, 'GLOBAL-002: Configuration error. Configuration object [config.http] is missing'); callback(new errors.ConfigurationError('config.http')); return; } @@ -439,7 +454,8 @@ function start(callback) { parseData, addTimestamp, handleIncomingMeasure, - returnCommands); + returnCommands + ); httpBindingServer.router.post( config.getConfig().iota.defaultResource || constants.HTTP_MEASURE_PATH, @@ -448,7 +464,8 @@ function start(callback) { parseData, addTimestamp, handleIncomingMeasure, - returnCommands); + returnCommands + ); httpBindingServer.router.post( (config.getConfig().iota.defaultResource || constants.HTTP_MEASURE_PATH) + constants.HTTP_COMMANDS_PATH, @@ -458,7 +475,8 @@ function start(callback) { addTimestamp, isCommand, handleIncomingMeasure, - returnCommands); + returnCommands + ); httpBindingServer.router.post( (config.getConfig().iota.defaultResource || constants.HTTP_MEASURE_PATH) + constants.HTTP_CONFIGURATION_PATH, @@ -489,7 +507,6 @@ function stop(callback) { } } - function sendPushNotifications(device, values, callback) { var executions = _.flatten(values.map(commandHandler.generateCommandExecution.bind(null, null, device))); @@ -499,7 +516,6 @@ function sendPushNotifications(device, values, callback) { } function storePollNotifications(device, values, callback) { - function addPollNotification(item, innerCallback) { iotAgentLib.addCommand(device.service, device.subservice, device.id, item, innerCallback); } diff --git a/lib/bindings/MQTTBinding.js b/lib/bindings/MQTTBinding.js index 0e290b76..98ab5905 100644 --- a/lib/bindings/MQTTBinding.js +++ b/lib/bindings/MQTTBinding.js @@ -72,10 +72,7 @@ function recreateSubscriptions(callback) { }); } - async.waterfall([ - generateTopics, - subscribeToTopics - ], callback); + async.waterfall([generateTopics, subscribeToTopics], callback); } /** @@ -97,10 +94,14 @@ function sendConfigurationToDevice(apiKey, deviceId, results, callback) { } config.getLogger().debug(context, 'Sending requested configuration to the device:\n %j', configurations); + //prettier-ignore mqttClient.publish( - '/' + apiKey + '/' + deviceId + '/' + constants.CONFIGURATION_SUFIX + '/' + + '/' + apiKey + '/' + deviceId + '/' + constants.CONFIGURATION_SUFIX + '/' + constants.CONFIGURATION_VALUES_SUFIX, - JSON.stringify(configurations), options, callback); + JSON.stringify(configurations), + options, + callback + ); } /** @@ -113,10 +114,7 @@ function unsubscribeAll(callback) { callback(); } - async.waterfall([ - generateTopics, - unsubscribeFromTopics - ], callback); + async.waterfall([generateTopics, unsubscribeFromTopics], callback); } /** @@ -160,10 +158,7 @@ function deviceProvisioningHandler(device, callback) { * Stop the binding, releasing its resources. */ function stop(callback) { - async.series([ - unsubscribeAll, - mqttClient.end.bind(mqttClient, true) - ], callback); + async.series([unsubscribeAll, mqttClient.end.bind(mqttClient, true)], callback); } /** diff --git a/lib/commandHandler.js b/lib/commandHandler.js index b4564f8f..2f966a0f 100644 --- a/lib/commandHandler.js +++ b/lib/commandHandler.js @@ -49,11 +49,21 @@ function generateCommandExecution(apiKey, device, attribute) { payload[attribute.name] = attribute.value; serialized = JSON.stringify(payload); - config.getLogger().debug(context, 'Sending command execution to device [%s] with apikey [%s] and payload [%j] ', - apiKey, device.id, attribute); + config + .getLogger() + .debug( + context, + 'Sending command execution to device [%s] with apikey [%s] and payload [%j] ', + apiKey, + device.id, + attribute + ); executions = transportSelector.createExecutionsForBinding( - [apiKey, device, serialized], 'executeCommand', device.transport); + [apiKey, device, serialized], + 'executeCommand', + device.transport + ); return executions; } @@ -71,8 +81,9 @@ function generateCommandExecution(apiKey, device, attribute) { * @param {Array} attributes List of NGSI attributes of type command to execute. */ function commandHandler(id, type, service, subservice, attributes, callback) { - config.getLogger().debug(context, - 'Handling MQTT command for device [%s] in service [%s - %s]', id, service, subservice); + config + .getLogger() + .debug(context, 'Handling MQTT command for device [%s] in service [%s - %s]', id, service, subservice); function concat(previous, current) { previous = previous.concat(current); @@ -81,19 +92,24 @@ function commandHandler(id, type, service, subservice, attributes, callback) { iotAgentLib.getDeviceByName(id, service, subservice, function(error, device) { if (error) { - config.getLogger().error(context, - 'COMMAND-001: Command execution could not be handled, as device for entity [%s] [%s] wasn\'t found', - id, type); + config.getLogger().error( + context, + /*jshint quotmark: double */ + "COMMAND-001: Command execution could not be handled, as device for entity [%s] [%s] wasn't found", + /*jshint quotmark: single */ + id, + type + ); callback(error); } else { iotaUtils.getEffectiveApiKey(device.service, device.subservice, function(error, apiKey) { if (error) { callback(error); } else { - async.series(attributes - .map(generateCommandExecution.bind(null, apiKey, device)) - .reduce(concat, []), - callback); + async.series( + attributes.map(generateCommandExecution.bind(null, apiKey, device)).reduce(concat, []), + callback + ); } }); } @@ -114,26 +130,40 @@ function updateCommand(apiKey, deviceId, device, messageObj) { for (var i = 0; i < commandList.length; i++) { commandUpdates.push( - async.apply(iotAgentLib.setCommandResult, + async.apply( + iotAgentLib.setCommandResult, device.name, config.getConfig().iota.defaultResource, apiKey, commandList[i], messageObj[commandList[i]], constants.COMMAND_STATUS_COMPLETED, - device) + device + ) ); } async.series(commandUpdates, function(error) { if (error) { - config.getLogger().error(context, - 'COMMANDS-002: Couldn\'t update command status in the Context broker ' + - 'for device [%s] with apiKey [%s]: %s', - device.id, apiKey, error); + config.getLogger().error( + context, + /*jshint quotmark: double */ + "COMMANDS-002: Couldn't update command status in the Context broker " + + /*jshint quotmark: single */ + 'for device [%s] with apiKey [%s]: %s', + device.id, + apiKey, + error + ); } else { - config.getLogger().debug(context, 'Single measure for device [%s] with apiKey [%s] successfully updated', - device.id, apiKey); + config + .getLogger() + .debug( + context, + 'Single measure for device [%s] with apiKey [%s] successfully updated', + device.id, + apiKey + ); } }); } diff --git a/lib/commonBindings.js b/lib/commonBindings.js index f59c8621..1dfaf798 100644 --- a/lib/commonBindings.js +++ b/lib/commonBindings.js @@ -36,7 +36,6 @@ var iotAgentLib = require('iotagent-node-lib'), }, config = require('./configService'); - /** * Parse a message received from a Topic. * @@ -44,8 +43,7 @@ var iotAgentLib = require('iotagent-node-lib'), * @return {Object} Parsed message or null if an error has occurred. */ function parseMessage(message) { - var parsedMessage, - stringMessage; + var parsedMessage, stringMessage; try { stringMessage = message.toString(); @@ -82,8 +80,7 @@ function guessType(attribute, device) { if (attribute === constants.TIMESTAMP_ATTRIBUTE) { if (iotAgentLib.configModule.checkNgsi2()) { return constants.TIMESTAMP_TYPE_NGSI2; - } - else { + } else { return constants.TIMESTAMP_TYPE; } } else { @@ -112,7 +109,8 @@ function sendConfigurationToDevice(device, apiKey, deviceId, results, callback) [apiKey, deviceId, results], 'sendConfigurationToDevice', device.transport, - callback); + callback + ); } /** @@ -127,17 +125,22 @@ function sendConfigurationToDevice(device, apiKey, deviceId, results, callback) */ function manageConfigurationRequest(apiKey, deviceId, device, objMessage) { iotaUtils.manageConfiguration( - apiKey, deviceId, device, objMessage, + apiKey, + deviceId, + device, + objMessage, async.apply(sendConfigurationToDevice, device), function(error) { if (error) { iotAgentLib.alarms.raise(constants.MQTTB_ALARM, error); } else { iotAgentLib.alarms.release(constants.MQTTB_ALARM); - config.getLogger().debug( - context, 'Configuration request finished for APIKey [%s] and Device [%s]', apiKey, deviceId); + config + .getLogger() + .debug(context, 'Configuration request finished for APIKey [%s] and Device [%s]', apiKey, deviceId); } - }); + } + ); } /** @@ -165,11 +168,22 @@ function singleMeasure(apiKey, deviceId, attribute, device, message) { iotAgentLib.update(device.name, device.type, '', values, device, function(error) { if (error) { - config.getLogger().error(context, - 'MEASURES-002: Couldn\'t send the updated values to the Context Broker due to an error: %s', error); + config.getLogger().error( + context, + /*jshint quotmark: double */ + "MEASURES-002: Couldn't send the updated values to the Context Broker due to an error: %s", + /*jshint quotmark: single */ + error + ); } else { - config.getLogger().debug(context, 'Single measure for device [%s] with apiKey [%s] successfully updated', - deviceId, apiKey); + config + .getLogger() + .debug( + context, + 'Single measure for device [%s] with apiKey [%s] successfully updated', + deviceId, + apiKey + ); } }); } @@ -186,8 +200,9 @@ function singleMeasure(apiKey, deviceId, attribute, device, message) { function multipleMeasures(apiKey, deviceId, device, messageObj) { var values = []; - config.getLogger().debug(context, - 'Processing multiple measures for device [%s] with apiKey [%s]', deviceId, apiKey); + config + .getLogger() + .debug(context, 'Processing multiple measures for device [%s] with apiKey [%s]', deviceId, apiKey); for (var i in messageObj) { if (messageObj.hasOwnProperty(i)) { @@ -201,11 +216,22 @@ function multipleMeasures(apiKey, deviceId, device, messageObj) { iotAgentLib.update(device.name, device.type, '', values, device, function(error) { if (error) { - config.getLogger().error(context, - 'MEASURES-002: Couldn\'t send the updated values to the Context Broker due to an error: %s', error); + config.getLogger().error( + context, + /*jshint quotmark: double */ + "MEASURES-002: Couldn't send the updated values to the Context Broker due to an error: %s", + /*jshint quotmark: single */ + error + ); } else { - config.getLogger().debug(context, 'Multiple measures for device [%s] with apiKey [%s] successfully updated', - deviceId, apiKey); + config + .getLogger() + .debug( + context, + 'Multiple measures for device [%s] with apiKey [%s] successfully updated', + deviceId, + apiKey + ); } }); } @@ -236,7 +262,13 @@ function messageHandler(topic, message, protocol) { } else if (parsedMessage && typeof parsedMessage === 'object') { multipleMeasures(apiKey, deviceId, device, parsedMessage); } else { - config.getLogger().error(context, 'Couldn\'t process message [%s] due to format issues.', message); + config.getLogger().error( + context, + /*jshint quotmark: double */ + "Couldn't process message [%s] due to format issues.", + /*jshint quotmark: single */ + message + ); } } } diff --git a/lib/configService.js b/lib/configService.js index 909b87e3..c4c9064d 100644 --- a/lib/configService.js +++ b/lib/configService.js @@ -85,18 +85,17 @@ function processEnvironmentVariables() { 'IOTA_AMQP_QUEUE', 'IOTA_AMQP_DURABLE', 'IOTA_AMQP_RETRIES', - 'IOTA_AMQP_RETRY_TIME', + 'IOTA_AMQP_RETRY_TIME' ], - httpVariables = [ - 'IOTA_HTTP_HOST', - 'IOTA_HTTP_PORT', - 'IOTA_HTTP_TIMEOUT' - ]; + httpVariables = ['IOTA_HTTP_HOST', 'IOTA_HTTP_PORT', 'IOTA_HTTP_TIMEOUT']; for (var i = 0; i < environmentVariables.length; i++) { if (process.env[environmentVariables[i]]) { - logger.info('Setting %s to environment value: %s', - environmentVariables[i], process.env[environmentVariables[i]]); + logger.info( + 'Setting %s to environment value: %s', + environmentVariables[i], + process.env[environmentVariables[i]] + ); } } @@ -200,7 +199,7 @@ function processEnvironmentVariables() { if (process.env.IOTA_HTTP_PORT) { config.http.port = process.env.IOTA_HTTP_PORT; } - + if (process.env.IOTA_HTTP_TIMEOUT) { config.http.timeout = process.env.IOTA_HTTP_TIMEOUT; } diff --git a/lib/constants.js b/lib/constants.js index 03448aad..9c584840 100644 --- a/lib/constants.js +++ b/lib/constants.js @@ -32,7 +32,9 @@ module.exports = { CONFIGURATION_COMMAND_UPDATE: 'cmdexe', CONFIGURATION_VALUES_SUFIX: 'values', - DATE_FORMAT: 'yyyymmdd\'T\'HHMMss\'Z\'', + /*jshint quotmark: double */ + DATE_FORMAT: "yyyymmdd'T'HHMMss'Z'", + /*jshint quotmark: single */ HTTP_MEASURE_PATH: '/iot/d', HTTP_CONFIGURATION_PATH: '/configuration', diff --git a/lib/errors.js b/lib/errors.js index f933ed41..69be8f5b 100644 --- a/lib/errors.js +++ b/lib/errors.js @@ -40,12 +40,21 @@ module.exports = { }, MandatoryParamsNotFound: function(paramList) { this.name = 'MANDATORY_PARAMS_NOT_FOUND'; - this.message = 'Some of the mandatory params weren\'t found in the request: ' + JSON.stringify(paramList); + this.message = + /*jshint quotmark: double */ + "Some of the mandatory params weren't found in the request: " + + /*jshint quotmark: single */ + JSON.stringify(paramList); this.code = 400; }, UnsupportedType: function(expectedType) { this.name = 'UNSUPPORTED_TYPE'; - this.message = 'The request content didn\'t have the expected type [' + expectedType + ' ]'; + this.message = + //prettier-ignore + /*jshint quotmark: double */ + "The request content didn't have the expected type [" + expectedType + " ]"; + /*jshint quotmark: single */ + this.code = 400; }, DeviceNotFound: function(deviceId) { diff --git a/lib/iotaUtils.js b/lib/iotaUtils.js index 347e8ece..cab28fc8 100644 --- a/lib/iotaUtils.js +++ b/lib/iotaUtils.js @@ -58,41 +58,65 @@ function getEffectiveApiKey(service, subservice, callback) { function manageConfiguration(apiKey, deviceId, device, objMessage, sendFunction, callback) { function handleSendConfigurationError(error, results) { if (error) { - config.getLogger().error(context, - 'CONFIG-001: Couldn\'t get the requested values from the Context Broker: %s', error); + config.getLogger().error( + context, + /*jshint quotmark: double */ + "CONFIG-001: Couldn't get the requested values from the Context Broker: %s", + /*jshint quotmark: single */ + error + ); } else { - config.getLogger().debug(context, 'Configuration attributes sent to the device successfully.', - deviceId, apiKey); + config + .getLogger() + .debug(context, 'Configuration attributes sent to the device successfully.', deviceId, apiKey); } callback(error); } function extractAttributes(results, callback) { - if (results.contextResponses && results.contextResponses[0] && - results.contextResponses[0].contextElement.attributes) { + if ( + results.contextResponses && + results.contextResponses[0] && + results.contextResponses[0].contextElement.attributes + ) { callback(null, results.contextResponses[0].contextElement.attributes); } else { - callback('Couldn\'t find any information in Context Broker response'); + /*jshint quotmark: double */ + callback("Couldn't find any information in Context Broker response"); + /*jshint quotmark: single */ } } if (objMessage.type === 'configuration') { - async.waterfall([ - apply(iotAgentLib.query, device.name, device.type, '', objMessage.fields, device), - extractAttributes, - apply(sendFunction, apiKey, deviceId) - ], handleSendConfigurationError); + async.waterfall( + [ + apply(iotAgentLib.query, device.name, device.type, '', objMessage.fields, device), + extractAttributes, + apply(sendFunction, apiKey, deviceId) + ], + handleSendConfigurationError + ); } else if (objMessage.type === 'subscription') { iotAgentLib.subscribe(device, objMessage.fields, objMessage.fields, function(error) { if (error) { - config.getLogger().error( - context, - 'CONFIG-002: There was an error subscribing device [%s] to attributes [%j]', - device.name, objMessage.fields); + config + .getLogger() + .error( + context, + 'CONFIG-002: There was an error subscribing device [%s] to attributes [%j]', + device.name, + objMessage.fields + ); } else { - config.getLogger().debug(context, 'Successfully subscribed device [%s] to attributes[%j]', - device.name, objMessage.fields); + config + .getLogger() + .debug( + context, + 'Successfully subscribed device [%s] to attributes[%j]', + device.name, + objMessage.fields + ); } callback(error); @@ -108,8 +132,7 @@ function createConfigurationNotification(results) { now = new Date(); for (var i = 0; i < results.length; i++) { - configurations[results[i].name] = - results[i].value; + configurations[results[i].name] = results[i].value; } configurations.dt = dateFormat(now, constants.DATE_FORMAT); @@ -127,8 +150,11 @@ function findOrCreate(deviceId, transport, group, callback) { subservice: group.subservice, type: group.type }; - if (config.getConfig().iota && config.getConfig().iota.iotManager && - config.getConfig().iota.iotManager.protocol) { + if ( + config.getConfig().iota && + config.getConfig().iota.iotManager && + config.getConfig().iota.iotManager.protocol + ) { newDevice.protocol = config.getConfig().iota.iotManager.protocol; } // Fix transport depending on binding @@ -147,8 +173,6 @@ function findOrCreate(deviceId, transport, group, callback) { }); } - - /** * Retrieve a device from the device repository based on the given APIKey and DeviceID, creating one if none is * found for the given data. @@ -164,28 +188,31 @@ function retrieveDevice(deviceId, apiKey, transport, callback) { } else if (devices && devices.length === 1) { callback(null, devices[0]); } else { - config.getLogger().error(context, - 'MEASURES-001: Couldn\'t find device data for APIKey [%s] and DeviceId[%s]', - apiKey, deviceId); + config.getLogger().error( + context, + /*jshint quotmark: double */ + "MEASURES-001: Couldn't find device data for APIKey [%s] and DeviceId[%s]", + /*jshint quotmark: single */ + apiKey, + deviceId + ); callback(new errors.DeviceNotFound(deviceId)); } }); } else { - async.waterfall([ - apply(iotAgentLib.getConfiguration, config.getConfig().iota.defaultResource || '', apiKey), - apply(findOrCreate, deviceId, transport), - apply(iotAgentLib.mergeDeviceWithConfiguration, - [ - 'lazy', - 'active', - 'staticAttributes', - 'commands', - 'subscriptions' - ], - [null, null, [], [], [], [], []] - ) - ], callback); + async.waterfall( + [ + apply(iotAgentLib.getConfiguration, config.getConfig().iota.defaultResource || '', apiKey), + apply(findOrCreate, deviceId, transport), + apply( + iotAgentLib.mergeDeviceWithConfiguration, + ['lazy', 'active', 'staticAttributes', 'commands', 'subscriptions'], + [null, null, [], [], [], [], []] + ) + ], + callback + ); } } diff --git a/lib/iotagent-json.js b/lib/iotagent-json.js index add376eb..13998938 100644 --- a/lib/iotagent-json.js +++ b/lib/iotagent-json.js @@ -49,23 +49,28 @@ function configurationNotificationHandler(device, updates, callback) { [apiKey, device.id, updates], 'sendConfigurationToDevice', device.transport || config.getConfig().defaultTransport, - callback); + callback + ); } - async.waterfall([ - apply(iotaUtils.getEffectiveApiKey, device.service, device.subservice), - invokeConfiguration - ], callback); - + async.waterfall( + [apply(iotaUtils.getEffectiveApiKey, device.service, device.subservice), invokeConfiguration], + callback + ); } function configurationHandler(configuration, callback) { - if (configuration.resource && config.getConfig().iota.iotManager && config.getConfig().iota.defaultResource && - configuration.resource !== config.getConfig().iota.defaultResource) { + if ( + configuration.resource && + config.getConfig().iota.iotManager && + config.getConfig().iota.defaultResource && + configuration.resource !== config.getConfig().iota.defaultResource + ) { callback(new errors.InvalidResource()); } else { callback(); - }} + } +} /** * Handles incoming updateContext requests related with lazy attributes. This handler is still just registered, @@ -80,8 +85,12 @@ function updateHandler(id, type, attributes, service, subservice, callback) { } function bidirectionalityNotificationHandler(device, updates, callback) { - transportSelector.applyFunctionFromBinding([device, updates], 'notificationHandler', - device.transport || config.getConfig().defaultTransport, callback); + transportSelector.applyFunctionFromBinding( + [device, updates], + 'notificationHandler', + device.transport || config.getConfig().defaultTransport, + callback + ); } /** @@ -146,7 +155,6 @@ function start(newConfig, callback) { iotAgentLib.setNotificationHandler(bidirectionalityNotificationHandler); } - transportSelector.startTransportBindings(newConfig, callback); } }); @@ -158,11 +166,10 @@ function start(newConfig, callback) { */ function stop(callback) { config.getLogger().info(context, 'Stopping IoT Agent'); - async.series([ - transportSelector.stopTransportBindings, - iotAgentLib.resetMiddlewares, - iotAgentLib.deactivate - ], callback); + async.series( + [transportSelector.stopTransportBindings, iotAgentLib.resetMiddlewares, iotAgentLib.deactivate], + callback + ); } exports.start = start; diff --git a/lib/thinkingThingPlugin.js b/lib/thinkingThingPlugin.js index 1e6f1f47..a4bc9c6e 100644 --- a/lib/thinkingThingPlugin.js +++ b/lib/thinkingThingPlugin.js @@ -247,13 +247,12 @@ function updatePluginNgsi2(entity, entityType, callback) { if (entity) { Object.keys(entity).map(function(key, index) { entity[key] = modifyAttributesNgsi2(key, entity[key]); - }); + }); callback(null, entity, entityType); } else { callback(new errors.BadPayload(entity)); } - } /** @@ -272,7 +271,6 @@ function updatePluginNgsi1(entity, entityType, callback) { } else { callback(new errors.BadPayload(entity)); } - } /** @@ -283,8 +281,7 @@ function updatePluginNgsi1(entity, entityType, callback) { function updatePlugin(entity, entityType, callback) { if (iotAgentLib.configModule.checkNgsi2()) { updatePluginNgsi2(entity, entityType, callback); - } - else { + } else { updatePluginNgsi1(entity, entityType, callback); } } diff --git a/lib/timestampProcessPlugin.js b/lib/timestampProcessPlugin.js index addafa6b..3d93a3f1 100644 --- a/lib/timestampProcessPlugin.js +++ b/lib/timestampProcessPlugin.js @@ -40,11 +40,13 @@ function updatePlugin(entity, entityType, callback) { 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; diff --git a/package.json b/package.json index 5f17c3fa..c585bb48 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,6 @@ { "name": "iotagent-json", + "license": "AGPL-3.0-only", "description": "IoT Agent for the JSON protocol", "version": "1.9.0-next", "homepage": "https://github.com/telefonicaid/iotagent-json", @@ -23,17 +24,21 @@ "test": "mocha --recursive 'test/**/*.js' --reporter spec --timeout 3000 --ui bdd --exit", "test:watch": "npm run test -- -w ./lib", "lint": "jshint lib/ --config .jshintrc && jshint test/ --config test/.jshintrc", + "prettier": "prettier --config .prettierrc.json --write '**/**/**/*.js' '**/**/*.js' '**/*.js' '*.js'", "test:coverage": "istanbul cover _mocha -- --recursive 'test/**/*.js' --reporter spec --exit", "test:coveralls": "npm run test:coverage && cat ./coverage/lcov.info | coveralls && rm -rf ./coverage", "watch": "watch 'npm test && npm run lint' ./lib ./test" }, "devDependencies": { "coveralls": "~3.0.2", + "husky": "~1.1.0", + "lint-staged": "~7.3.0", "nock": "10.0.1", "mocha": "5.2.0", "should": "13.2.3", "sinon": "~6.1.0", "istanbul": "~0.4.5", + "prettier": "~1.14.2", "proxyquire": "2.1.0", "moment": "~2.22.2", "watch": "~1.0.2", @@ -51,5 +56,16 @@ "mqtt": "2.18.8", "request": "2.88.0", "underscore": "1.9.1" + }, + "husky": { + "hooks": { + "pre-commit": "lint-staged" + } + }, + "lint-staged": { + "*.js": [ + "prettier --config .prettierrc.json --write", + "git add" + ] } } diff --git a/test/.jshintrc b/test/.jshintrc index d4425445..e0b7d710 100644 --- a/test/.jshintrc +++ b/test/.jshintrc @@ -13,7 +13,7 @@ "maxparams": 6, "maxdepth": 4, "camelcase": true, - "maxlen": 120, + "maxlen": 180, "node": true, "expr": true, "unused": "vars", diff --git a/test/config-startup.js b/test/config-startup.js index ab1b5773..a5fb7bcb 100644 --- a/test/config-startup.js +++ b/test/config-startup.js @@ -39,7 +39,7 @@ config.amqp = { port: 5672, exchange: 'amq.topic', queue: 'iota_queue', - options: {durable: true} + options: { durable: true } }; config.iota = { diff --git a/test/config-test.js b/test/config-test.js index 9a9b1f6d..0aa06723 100644 --- a/test/config-test.js +++ b/test/config-test.js @@ -39,7 +39,7 @@ config.amqp = { port: 5672, exchange: 'amq.topic', queue: 'iota_queue', - options: {durable: true} + options: { durable: true } }; config.iota = { diff --git a/test/unit/HTTP_commands_test.js b/test/unit/HTTP_commands_test.js index 17fa1c9d..3307237f 100644 --- a/test/unit/HTTP_commands_test.js +++ b/test/unit/HTTP_commands_test.js @@ -53,8 +53,7 @@ describe('HTTP: Commands', function() { .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/NGSI9/registerContext') - .reply(200, - utils.readExampleFile('./test/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .reply(200, utils.readExampleFile('./test/contextAvailabilityResponses/registerIoTAgent1Success.json')); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') @@ -71,10 +70,7 @@ describe('HTTP: Commands', function() { afterEach(function(done) { nock.cleanAll(); - async.series([ - iotAgentLib.clearAll, - iotagentMqtt.stop - ], done); + async.series([iotAgentLib.clearAll, iotagentMqtt.stop], done); }); describe('When a command arrive to the Agent for a device with the HTTP protocol', function() { @@ -138,4 +134,3 @@ describe('HTTP: Commands', function() { }); }); }); - diff --git a/test/unit/HTTP_get-configuration_test.js b/test/unit/HTTP_get-configuration_test.js index a49ca2e6..15895589 100644 --- a/test/unit/HTTP_get-configuration_test.js +++ b/test/unit/HTTP_get-configuration_test.js @@ -55,8 +55,7 @@ describe('HTTP: Get configuration from the devices', function() { .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/NGSI9/registerContext') - .reply(200, - utils.readExampleFile('./test/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .reply(200, utils.readExampleFile('./test/contextAvailabilityResponses/registerIoTAgent1Success.json')); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') @@ -78,10 +77,7 @@ describe('HTTP: Get configuration from the devices', function() { nock.cleanAll(); config.configRetrieval = oldConfigurationFlag; - async.series([ - iotAgentLib.clearAll, - iotagentMqtt.stop - ], done); + async.series([iotAgentLib.clearAll, iotagentMqtt.stop], done); }); describe('When a configuration request is received in the path /configuration/commands', function() { @@ -90,10 +86,7 @@ describe('HTTP: Get configuration from the devices', function() { method: 'POST', json: { type: 'configuration', - fields: [ - 'sleepTime', - 'warningLevel' - ] + fields: ['sleepTime', 'warningLevel'] }, headers: { 'fiware-service': 'smartGondor', @@ -110,14 +103,17 @@ describe('HTTP: Get configuration from the devices', function() { .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v1/queryContext', utils.readExampleFile('./test/contextRequests/getConfiguration.json')) - .reply(200, - utils.readExampleFile('./test/contextResponses/getConfigurationSuccess.json')); + .reply(200, utils.readExampleFile('./test/contextResponses/getConfigurationSuccess.json')); mockedClientServer = nock('http://localhost:9876') .post('/command/configuration', function(result) { - return result.sleepTime && result.sleepTime === '200' && - result.warningLevel && result.warningLevel === '80' && - result.dt; + return ( + result.sleepTime && + result.sleepTime === '200' && + result.warningLevel && + result.warningLevel === '80' && + result.dt + ); }) .reply(200, ''); }); @@ -149,10 +145,7 @@ describe('HTTP: Get configuration from the devices', function() { method: 'POST', json: { type: 'subscription', - fields: [ - 'sleepTime', - 'warningLevel' - ] + fields: ['sleepTime', 'warningLevel'] }, headers: { 'fiware-service': 'smartGondor', @@ -169,14 +162,17 @@ describe('HTTP: Get configuration from the devices', function() { .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v1/subscribeContext', utils.readExampleFile('./test/subscriptions/subscriptionRequest.json')) - .reply(200, - utils.readExampleFile('./test/subscriptions/subscriptionResponse.json')); + .reply(200, utils.readExampleFile('./test/subscriptions/subscriptionResponse.json')); mockedClientServer = nock('http://localhost:9876') .post('/command/configuration', function(result) { - return result.sleepTime && result.sleepTime === '200' && - result.warningLevel && result.warningLevel === 'ERROR' && - result.dt; + return ( + result.sleepTime && + result.sleepTime === '200' && + result.warningLevel && + result.warningLevel === 'ERROR' && + result.dt + ); }) .reply(200, ''); }); diff --git a/test/unit/HTTP_reveice_measures-test.js b/test/unit/HTTP_reveice_measures-test.js index 2e293d60..429a6820 100644 --- a/test/unit/HTTP_reveice_measures-test.js +++ b/test/unit/HTTP_reveice_measures-test.js @@ -94,10 +94,7 @@ describe('HTTP: Measure reception ', function() { afterEach(function(done) { nock.cleanAll(); - async.series([ - iotAgentLib.clearAll, - iotagentMqtt.stop - ], done); + async.series([iotAgentLib.clearAll, iotagentMqtt.stop], done); }); describe('When a POST measure arrives for the HTTP binding', function() { @@ -165,7 +162,7 @@ describe('HTTP: Measure reception ', function() { 'fiware-service': 'smartGondor', 'fiware-servicepath': '/gardens' } - }; + }; beforeEach(function(done) { nock.cleanAll(); @@ -344,5 +341,3 @@ describe('HTTP: Measure reception ', function() { }); }); }); - - diff --git a/test/unit/MQTT_commands_test.js b/test/unit/MQTT_commands_test.js index afec802d..a2f95949 100644 --- a/test/unit/MQTT_commands_test.js +++ b/test/unit/MQTT_commands_test.js @@ -34,7 +34,6 @@ var iotagentMqtt = require('../../'), contextBrokerMock, mqttClient; - describe('MQTT: Commands', function() { beforeEach(function(done) { var provisionOptions = { @@ -51,10 +50,13 @@ describe('MQTT: Commands', function() { nock.cleanAll(); - mqttClient = mqtt.connect('mqtt://' + config.mqtt.host, { - keepalive: 0, - connectTimeout: 60 * 60 * 1000 - }); + mqttClient = mqtt.connect( + 'mqtt://' + config.mqtt.host, + { + keepalive: 0, + connectTimeout: 60 * 60 * 1000 + } + ); mqttClient.subscribe('/1234/MQTT_2/cmd', null); @@ -62,8 +64,7 @@ describe('MQTT: Commands', function() { .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/NGSI9/registerContext') - .reply(200, - utils.readExampleFile('./test/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .reply(200, utils.readExampleFile('./test/contextAvailabilityResponses/registerIoTAgent1Success.json')); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') @@ -83,10 +84,7 @@ describe('MQTT: Commands', function() { mqttClient.unsubscribe('/1234/MQTT_2/cmd', null); mqttClient.end(); - async.series([ - iotAgentLib.clearAll, - iotagentMqtt.stop - ], done); + async.series([iotAgentLib.clearAll, iotagentMqtt.stop], done); }); describe('When a command arrive to the Agent for a device with the MQTT_UL protocol', function() { diff --git a/test/unit/MQTT_get-configuration_test.js b/test/unit/MQTT_get-configuration_test.js index 3f693950..82805343 100644 --- a/test/unit/MQTT_get-configuration_test.js +++ b/test/unit/MQTT_get-configuration_test.js @@ -49,10 +49,13 @@ describe('MQTT: Get configuration from the devices', function() { nock.cleanAll(); - mqttClient = mqtt.connect('mqtt://' + config.mqtt.host, { - keepalive: 0, - connectTimeout: 60 * 60 * 1000 - }); + mqttClient = mqtt.connect( + 'mqtt://' + config.mqtt.host, + { + keepalive: 0, + connectTimeout: 60 * 60 * 1000 + } + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') @@ -76,94 +79,90 @@ describe('MQTT: Get configuration from the devices', function() { nock.cleanAll(); mqttClient.end(); - async.series([ - iotAgentLib.clearAll, - iotagentMqtt.stop - ], done); + async.series([iotAgentLib.clearAll, iotagentMqtt.stop], done); }); - describe('When a configuration request is received in the topic ' + - '"/{{apikey}}/{{deviceid}}/configuration/commands"', function() { - var values = { - type: 'configuration', - fields: [ - 'sleepTime', - 'warningLevel' - ] - }, - configurationReceived; - - beforeEach(function() { - contextBrokerMock - .matchHeader('fiware-service', 'smartGondor') - .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/queryContext', utils.readExampleFile('./test/contextRequests/getConfiguration.json')) - .reply(200, - utils.readExampleFile('./test/contextResponses/getConfigurationSuccess.json')); - - mqttClient.subscribe('/1234/MQTT_2/configuration/values', null); - - configurationReceived = false; - }); + describe( + 'When a configuration request is received in the topic ' + '"/{{apikey}}/{{deviceid}}/configuration/commands"', + function() { + var values = { + type: 'configuration', + fields: ['sleepTime', 'warningLevel'] + }, + configurationReceived; + + beforeEach(function() { + contextBrokerMock + .matchHeader('fiware-service', 'smartGondor') + .matchHeader('fiware-servicepath', '/gardens') + .post('/v1/queryContext', utils.readExampleFile('./test/contextRequests/getConfiguration.json')) + .reply(200, utils.readExampleFile('./test/contextResponses/getConfigurationSuccess.json')); + + mqttClient.subscribe('/1234/MQTT_2/configuration/values', null); + + configurationReceived = false; + }); - afterEach(function(done) { - mqttClient.unsubscribe('/1234/MQTT_2/configuration/values', null); + afterEach(function(done) { + mqttClient.unsubscribe('/1234/MQTT_2/configuration/values', null); - done(); - }); + done(); + }); - it('should ask the Context Broker for the request attributes', function(done) { - mqttClient.publish('/1234/MQTT_2/configuration/commands', JSON.stringify(values), null, function(error) { - setTimeout(function() { - contextBrokerMock.done(); - done(); - }, 100); + it('should ask the Context Broker for the request attributes', function(done) { + mqttClient.publish('/1234/MQTT_2/configuration/commands', JSON.stringify(values), null, function( + error + ) { + setTimeout(function() { + contextBrokerMock.done(); + done(); + }, 100); + }); }); - }); - it('should return the requested attributes to the client in /1234/MQTT_2/configuration/values', - function(done) { + it('should return the requested attributes to the client in /1234/MQTT_2/configuration/values', function(done) { mqttClient.on('message', function(topic, data) { var result = JSON.parse(data); configurationReceived = - result.sleepTime && result.sleepTime === '200' && - result.warningLevel && result.warningLevel === '80'; + result.sleepTime && + result.sleepTime === '200' && + result.warningLevel && + result.warningLevel === '80'; }); - mqttClient.publish('/1234/MQTT_2/configuration/commands', JSON.stringify(values), null, - function(error) { - setTimeout(function() { - configurationReceived.should.equal(true); - done(); - }, 100); + mqttClient.publish('/1234/MQTT_2/configuration/commands', JSON.stringify(values), null, function( + error + ) { + setTimeout(function() { + configurationReceived.should.equal(true); + done(); + }, 100); }); - }); + }); - it('should add the system timestamp in compressed format to the request', - function(done) { + it('should add the system timestamp in compressed format to the request', function(done) { mqttClient.on('message', function(topic, data) { var result = JSON.parse(data); configurationReceived = result.dt && result.dt.should.match(/^\d{8}T\d{6}Z$/); }); - mqttClient.publish('/1234/MQTT_2/configuration/commands', JSON.stringify(values), null, - function(error) { - setTimeout(function() { - should.exist(configurationReceived); - done(); - }, 100); - }); + mqttClient.publish('/1234/MQTT_2/configuration/commands', JSON.stringify(values), null, function( + error + ) { + setTimeout(function() { + should.exist(configurationReceived); + done(); + }, 100); + }); }); - }); + } + ); describe('When a subscription request is received in the IoT Agent', function() { var values = { type: 'subscription', - fields: [ - 'sleepTime', - 'warningLevel' - ] + fields: ['sleepTime', 'warningLevel'] }, configurationReceived; @@ -172,8 +171,7 @@ describe('MQTT: Get configuration from the devices', function() { .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v1/subscribeContext', utils.readExampleFile('./test/subscriptions/subscriptionRequest.json')) - .reply(200, - utils.readExampleFile('./test/subscriptions/subscriptionResponse.json')); + .reply(200, utils.readExampleFile('./test/subscriptions/subscriptionResponse.json')); mqttClient.subscribe('/1234/MQTT_2/configuration/values', null); @@ -186,45 +184,41 @@ describe('MQTT: Get configuration from the devices', function() { done(); }); - it('should create a subscription in the ContextBroker', - function(done) { - mqttClient.publish('/1234/MQTT_2/configuration/commands', JSON.stringify(values), null, - function(error) { - setTimeout(function() { - contextBrokerMock.done(); - done(); - }, 100); - }); + it('should create a subscription in the ContextBroker', function(done) { + mqttClient.publish('/1234/MQTT_2/configuration/commands', JSON.stringify(values), null, function(error) { + setTimeout(function() { + contextBrokerMock.done(); + done(); + }, 100); + }); + }); + it('should update the values in the MQTT topic when a notification is received', function(done) { + var optionsNotify = { + url: 'http://localhost:' + config.iota.server.port + '/notify', + method: 'POST', + json: utils.readExampleFile('./test/subscriptions/notification.json'), + headers: { + 'fiware-service': 'smartGondor', + 'fiware-servicepath': '/gardens' + } + }; + + mqttClient.on('message', function(topic, data) { + var result = JSON.parse(data); + + configurationReceived = result.sleepTime === '200' && result.warningLevel === 'ERROR'; }); - it('should update the values in the MQTT topic when a notification is received', - function(done) { - var optionsNotify = { - url: 'http://localhost:' + config.iota.server.port + '/notify', - method: 'POST', - json: utils.readExampleFile('./test/subscriptions/notification.json'), - headers: { - 'fiware-service': 'smartGondor', - 'fiware-servicepath': '/gardens' - } - }; - - mqttClient.on('message', function(topic, data) { - var result = JSON.parse(data); - - configurationReceived = result.sleepTime === '200' && result.warningLevel === 'ERROR'; - }); - mqttClient.publish('/1234/MQTT_2/configuration/commands', JSON.stringify(values), null, - function(error) { + mqttClient.publish('/1234/MQTT_2/configuration/commands', JSON.stringify(values), null, function(error) { + setTimeout(function() { + request(optionsNotify, function(error, response, body) { setTimeout(function() { - request(optionsNotify, function(error, response, body) { - setTimeout(function() { - configurationReceived.should.equal(true); - done(); - }, 100); - }); + configurationReceived.should.equal(true); + done(); }, 100); }); + }, 100); }); + }); }); }); diff --git a/test/unit/MQTT_receive_measures-test.js b/test/unit/MQTT_receive_measures-test.js index 7486c8fc..e92b6ee3 100644 --- a/test/unit/MQTT_receive_measures-test.js +++ b/test/unit/MQTT_receive_measures-test.js @@ -79,10 +79,13 @@ describe('MQTT: Measure reception ', function() { nock.cleanAll(); - mqttClient = mqtt.connect('mqtt://' + config.mqtt.host, { - keepalive: 0, - connectTimeout: 60 * 60 * 1000 - }); + mqttClient = mqtt.connect( + 'mqtt://' + config.mqtt.host, + { + keepalive: 0, + connectTimeout: 60 * 60 * 1000 + } + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') @@ -101,10 +104,7 @@ describe('MQTT: Measure reception ', function() { nock.cleanAll(); mqttClient.end(); - async.series([ - iotAgentLib.clearAll, - iotagentMqtt.stop - ], done); + async.series([iotAgentLib.clearAll, iotagentMqtt.stop], done); }); describe('When a new multiple measure arrives to the MQTT Topic', function() { @@ -154,13 +154,14 @@ describe('MQTT: Measure reception ', function() { temperature: '87' }; - mqttClient.publish('/KL223HHV8732SFL1/MQTT_UNPROVISIONED/attrs', JSON.stringify(values), null, - function(error) { - setTimeout(function() { - contextBrokerUnprovMock.done(); - done(); - }, 100); - }); + mqttClient.publish('/KL223HHV8732SFL1/MQTT_UNPROVISIONED/attrs', JSON.stringify(values), null, function( + error + ) { + setTimeout(function() { + contextBrokerUnprovMock.done(); + done(); + }, 100); + }); }); }); @@ -217,8 +218,7 @@ describe('MQTT: Measure reception ', function() { .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v1/updateContext', utils.readExampleFile('./test/contextRequests/singleMeasure.json')) - .reply(200, - utils.readExampleFile('./test/contextResponses/singleMeasureSuccess.json')); + .reply(200, utils.readExampleFile('./test/contextResponses/singleMeasureSuccess.json')); }); it('should send its values to the Context Broker', function(done) { mqttClient.publish('/1234/MQTT_2/attrs/temperature', '87', null, function(error) { diff --git a/test/unit/amqpBinding-test.js b/test/unit/amqpBinding-test.js index 4cee5a36..b0ecd050 100644 --- a/test/unit/amqpBinding-test.js +++ b/test/unit/amqpBinding-test.js @@ -39,16 +39,19 @@ var iotagentMqtt = require('../../'), channel; function startConnection(exchange, callback) { - amqp.connect('amqp://localhost', function(err, conn) { - amqpConn = conn; + amqp.connect( + 'amqp://localhost', + function(err, conn) { + amqpConn = conn; - conn.createChannel(function(err, ch) { - ch.assertExchange(exchange, 'topic', {}); + conn.createChannel(function(err, ch) { + ch.assertExchange(exchange, 'topic', {}); - channel = ch; - callback(err); - }); - }); + channel = ch; + callback(err); + }); + } + ); } describe('AMQP Transport binding: measures', function() { @@ -74,11 +77,14 @@ describe('AMQP Transport binding: measures', function() { .post('/v1/updateContext') .reply(200, utils.readExampleFile('./test/contextResponses/multipleMeasuresSuccess.json')); - async.series([ - apply(iotagentMqtt.start, config), - apply(request, provisionOptions), - apply(startConnection, config.amqp.exchange) - ], done); + async.series( + [ + apply(iotagentMqtt.start, config), + apply(request, provisionOptions), + apply(startConnection, config.amqp.exchange) + ], + done + ); }); afterEach(function(done) { @@ -87,10 +93,7 @@ describe('AMQP Transport binding: measures', function() { amqpConn.close(); config.iota.defaultResource = oldResource; - async.series([ - iotAgentLib.clearAll, - iotagentMqtt.stop - ], done); + async.series([iotAgentLib.clearAll, iotagentMqtt.stop], done); }); describe('When a new single measure arrives to a Device routing key', function() { @@ -130,7 +133,6 @@ describe('AMQP Transport binding: measures', function() { .post('/v1/updateContext') .reply(200, utils.readExampleFile('./test/contextResponses/multipleMeasuresSuccess.json')); - contextBrokerUnprovMock .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') @@ -162,9 +164,7 @@ describe('AMQP Transport binding: measures', function() { }); it('should send a single update context request with all the attributes', function(done) { - channel.publish(config.amqp.exchange, '.1234.MQTT_2.attrs', new Buffer( - JSON.stringify({a: '23'}) - )); + channel.publish(config.amqp.exchange, '.1234.MQTT_2.attrs', new Buffer(JSON.stringify({ a: '23' }))); setTimeout(function() { contextBrokerMock.done(); @@ -201,12 +201,16 @@ describe('AMQP Transport binding: measures', function() { }); it('should send one update context per measure group to the Contet Broker', function(done) { - channel.publish(config.amqp.exchange, '.1234.MQTT_2.attrs', new Buffer( - JSON.stringify({ - a: '23', - b: '98' - }) - )); + channel.publish( + config.amqp.exchange, + '.1234.MQTT_2.attrs', + new Buffer( + JSON.stringify({ + a: '23', + b: '98' + }) + ) + ); setTimeout(function() { contextBrokerMock.done(); diff --git a/test/unit/attribute-alias_test.js b/test/unit/attribute-alias_test.js index 76498890..c01a7df9 100644 --- a/test/unit/attribute-alias_test.js +++ b/test/unit/attribute-alias_test.js @@ -47,10 +47,13 @@ describe('Attribute alias', function() { nock.cleanAll(); - mqttClient = mqtt.connect('mqtt://' + config.mqtt.host, { - keepalive: 0, - connectTimeout: 60 * 60 * 1000 - }); + mqttClient = mqtt.connect( + 'mqtt://' + config.mqtt.host, + { + keepalive: 0, + connectTimeout: 60 * 60 * 1000 + } + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') @@ -69,10 +72,7 @@ describe('Attribute alias', function() { nock.cleanAll(); mqttClient.end(); - async.series([ - iotAgentLib.clearAll, - iotagentMqtt.stop - ], done); + async.series([iotAgentLib.clearAll, iotagentMqtt.stop], done); }); describe('When a new multiple measure arrives with a timestamp in an attribute alias', function() { diff --git a/test/unit/bidirectionalityHttp-test.js b/test/unit/bidirectionalityHttp-test.js index 1e82d4e0..7d08a266 100644 --- a/test/unit/bidirectionalityHttp-test.js +++ b/test/unit/bidirectionalityHttp-test.js @@ -69,26 +69,35 @@ describe('Data Bidirectionality: HTTP', function() { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/subscribeContext', utils.readExampleFile( - './test//subscriptions/bidirectionalSubscriptionRequest.json')) - .reply(200, utils.readExampleFile( - './test/subscriptionResponses/bidirectionalSubscriptionSuccess.json')); + .post( + '/v1/subscribeContext', + utils.readExampleFile('./test//subscriptions/bidirectionalSubscriptionRequest.json') + ) + .reply( + 200, + utils.readExampleFile('./test/subscriptionResponses/bidirectionalSubscriptionSuccess.json') + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/contextRequests/createBidirectionalDevice.json')) - .reply(200, utils.readExampleFile( - './test/contextResponses/createBidirectionalDeviceSuccess.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/contextRequests/createBidirectionalDevice.json') + ) + .reply(200, utils.readExampleFile('./test/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/subscriptions/simpleSubscriptionRemove.json')) - .reply(200, utils.readExampleFile( - './test/subscriptionResponses/bidirectionalSubscriptionSuccess.json')); + .post( + '/v1/unsubscribeContext', + utils.readExampleFile('./test/subscriptions/simpleSubscriptionRemove.json') + ) + .reply( + 200, + utils.readExampleFile('./test/subscriptionResponses/bidirectionalSubscriptionSuccess.json') + ); iotagentJson.start(config, function(error) { request(provisionOptions, function(error, response, body) { @@ -123,15 +132,19 @@ describe('Data Bidirectionality: HTTP', function() { longitudeFound = false; for (var i = 0; i < list.commands.length; i++) { - if (list.commands[i].name === 'latitude' && + if ( + list.commands[i].name === 'latitude' && list.commands[i].type === 'string' && - list.commands[i].value === '-9.6') { + list.commands[i].value === '-9.6' + ) { latitudeFound = true; } - if (list.commands[i].name === 'longitude' && + if ( + list.commands[i].name === 'longitude' && list.commands[i].type === 'string' && - list.commands[i].value === '12.4') { + list.commands[i].value === '12.4' + ) { longitudeFound = true; } } @@ -162,26 +175,35 @@ describe('Data Bidirectionality: HTTP', function() { contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/subscribeContext', utils.readExampleFile( - './test//subscriptions/bidirectionalSubscriptionRequest.json')) - .reply(200, utils.readExampleFile( - './test/subscriptionResponses/bidirectionalSubscriptionSuccess.json')); + .post( + '/v1/subscribeContext', + utils.readExampleFile('./test//subscriptions/bidirectionalSubscriptionRequest.json') + ) + .reply( + 200, + utils.readExampleFile('./test/subscriptionResponses/bidirectionalSubscriptionSuccess.json') + ); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v1/updateContext', utils.readExampleFile( - './test/contextRequests/createBidirectionalDevice.json')) - .reply(200, utils.readExampleFile( - './test/contextResponses/createBidirectionalDeviceSuccess.json')); + .post( + '/v1/updateContext', + utils.readExampleFile('./test/contextRequests/createBidirectionalDevice.json') + ) + .reply(200, utils.readExampleFile('./test/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/subscriptions/simpleSubscriptionRemove.json')) - .reply(200, utils.readExampleFile( - './test/subscriptionResponses/bidirectionalSubscriptionSuccess.json')); + .post( + '/v1/unsubscribeContext', + utils.readExampleFile('./test/subscriptions/simpleSubscriptionRemove.json') + ) + .reply( + 200, + utils.readExampleFile('./test/subscriptionResponses/bidirectionalSubscriptionSuccess.json') + ); mockedClientServer = nock('http://localhost:9876') .post('/command', '{"location":"12.4, -9.6"}') diff --git a/test/unit/commandsAmqp-test.js b/test/unit/commandsAmqp-test.js index 95499f3f..cec22700 100644 --- a/test/unit/commandsAmqp-test.js +++ b/test/unit/commandsAmqp-test.js @@ -39,16 +39,19 @@ var iotagentMqtt = require('../../'), channel; function startConnection(exchange, callback) { - amqp.connect('amqp://localhost', function(err, conn) { - amqpConn = conn; + amqp.connect( + 'amqp://localhost', + function(err, conn) { + amqpConn = conn; - conn.createChannel(function(err, ch) { - ch.assertExchange(exchange, 'topic', {}); + conn.createChannel(function(err, ch) { + ch.assertExchange(exchange, 'topic', {}); - channel = ch; - callback(err); - }); - }); + channel = ch; + callback(err); + }); + } + ); } describe('AMQP Transport binding: commands', function() { @@ -71,8 +74,7 @@ describe('AMQP Transport binding: commands', function() { .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/NGSI9/registerContext') - .reply(200, - utils.readExampleFile('./test/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .reply(200, utils.readExampleFile('./test/contextAvailabilityResponses/registerIoTAgent1Success.json')); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') @@ -83,11 +85,14 @@ describe('AMQP Transport binding: commands', function() { oldTransport = config.defaultTransport; config.defaultTransport = 'AMQP'; - async.series([ - apply(iotagentMqtt.start, config), - apply(request, provisionOptions), - apply(startConnection, config.amqp.exchange) - ], done); + async.series( + [ + apply(iotagentMqtt.start, config), + apply(request, provisionOptions), + apply(startConnection, config.amqp.exchange) + ], + done + ); }); afterEach(function(done) { @@ -97,10 +102,7 @@ describe('AMQP Transport binding: commands', function() { config.defaultTransport = oldTransport; - async.series([ - iotAgentLib.clearAll, - iotagentMqtt.stop - ], done); + async.series([iotAgentLib.clearAll, iotagentMqtt.stop], done); }); describe('When a command arrive to the Agent for a device with the AMQP protocol', function() { @@ -147,12 +149,16 @@ describe('AMQP Transport binding: commands', function() { channel.assertExchange(config.amqp.exchange, 'topic', config.amqp.options); - channel.assertQueue('client-queue', {exclusive: false}, function(err, q) { + channel.assertQueue('client-queue', { exclusive: false }, function(err, q) { channel.bindQueue(q.queue, config.amqp.exchange, '.' + config.defaultKey + '.MQTT_2.cmd'); - channel.consume(q.queue, function(msg) { - payload = msg.content.toString(); - }, {noAck: true}); + channel.consume( + q.queue, + function(msg) { + payload = msg.content.toString(); + }, + { noAck: true } + ); request(commandOptions, function(error, response, body) { setTimeout(function() { @@ -176,8 +182,7 @@ describe('AMQP Transport binding: commands', function() { it('should send an update request to the Context Broker', function(done) { channel.assertExchange(config.amqp.exchange, 'topic', config.amqp.options); - channel.publish( - config.amqp.exchange, '.1234.MQTT_2.cmdexe', new Buffer('{"PING":"1234567890"}')); + channel.publish(config.amqp.exchange, '.1234.MQTT_2.cmdexe', new Buffer('{"PING":"1234567890"}')); setTimeout(function() { contextBrokerMock.done(); @@ -222,8 +227,7 @@ describe('AMQP Transport binding: commands', function() { .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/NGSI9/registerContext') - .reply(200, - utils.readExampleFile('./test/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .reply(200, utils.readExampleFile('./test/contextAvailabilityResponses/registerIoTAgent1Success.json')); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') @@ -250,12 +254,16 @@ describe('AMQP Transport binding: commands', function() { channel.assertExchange(config.amqp.exchange, 'topic', config.amqp.options); - channel.assertQueue('client-queue', {exclusive: false}, function(err, q) { + channel.assertQueue('client-queue', { exclusive: false }, function(err, q) { channel.bindQueue(q.queue, config.amqp.exchange, '.ALTERNATIVE.MQTT_4.cmd'); - channel.consume(q.queue, function(msg) { - payload = msg.content.toString(); - }, {noAck: true}); + channel.consume( + q.queue, + function(msg) { + payload = msg.content.toString(); + }, + { noAck: true } + ); request(commandOptions, function(error, response, body) { setTimeout(function() { diff --git a/test/unit/commandsPolling-test.js b/test/unit/commandsPolling-test.js index f7521225..03b7fa9d 100644 --- a/test/unit/commandsPolling-test.js +++ b/test/unit/commandsPolling-test.js @@ -61,8 +61,7 @@ describe('HTTP Transport binding: polling commands', function() { .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/NGSI9/registerContext') - .reply(200, - utils.readExampleFile('./test/contextAvailabilityResponses/registerIoTAgent1Success.json')); + .reply(200, utils.readExampleFile('./test/contextAvailabilityResponses/registerIoTAgent1Success.json')); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') @@ -177,7 +176,6 @@ describe('HTTP Transport binding: polling commands', function() { }); }); - describe('When a device asks for the pending commands without body', function() { var deviceRequest = { url: 'http://localhost:' + config.http.port + '/iot/json', diff --git a/test/unit/configuration-api_test.js b/test/unit/configuration-api_test.js index 55fdc1ff..288e407f 100644 --- a/test/unit/configuration-api_test.js +++ b/test/unit/configuration-api_test.js @@ -67,14 +67,16 @@ describe('Configuration API support', function() { } }; - beforeEach(function(done) { nock.cleanAll(); originalResource = config.iota.defaultResource; - mqttClient = mqtt.connect('mqtt://' + config.mqtt.host, { - keepalive: 0, - connectTimeout: 60 * 60 * 1000 - }); + mqttClient = mqtt.connect( + 'mqtt://' + config.mqtt.host, + { + keepalive: 0, + connectTimeout: 60 * 60 * 1000 + } + ); config.iota.iotManager = { host: '127.0.0.1', @@ -88,12 +90,12 @@ describe('Configuration API support', function() { iotamMock = nock('http://127.0.0.1:8081') .post('/iot/protocols', { - protocol: 'TT_MQTT-JSON', - description: 'MQTT-JSON protocol for TT', - iotagent: 'http://localhost:4041', - resource: '/iotamqtt', - services: [] - }) + protocol: 'TT_MQTT-JSON', + description: 'MQTT-JSON protocol for TT', + iotagent: 'http://localhost:4041', + resource: '/iotamqtt', + services: [] + }) .reply(200, {}); contextBrokerMock = nock('http://192.168.1.1:1026') @@ -117,7 +119,8 @@ describe('Configuration API support', function() { describe('When a configuration is provisioned for a service', function() { beforeEach(function() { - iotamMock.post('/iot/protocols', { + iotamMock + .post('/iot/protocols', { protocol: 'TT_MQTT-JSON', description: 'MQTT-JSON protocol for TT', iotagent: 'http://localhost:4041', @@ -140,8 +143,7 @@ describe('Configuration API support', function() { .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v1/updateContext', utils.readExampleFile('./test/contextRequests/singleMeasure.json')) - .reply(200, - utils.readExampleFile('./test/contextResponses/singleMeasureSuccess.json')); + .reply(200, utils.readExampleFile('./test/contextResponses/singleMeasureSuccess.json')); }); it('should use the API Key of that configuration in device topics', function(done) { @@ -180,10 +182,7 @@ describe('Configuration API support', function() { ] }; - iotamMock - .post('/iot/protocols', configurationProvision) - .reply(200, {}); - + iotamMock.post('/iot/protocols', configurationProvision).reply(200, {}); }); it('should reject the configuration provisioning with a BAD FORMAT error', function(done) { diff --git a/test/unit/ngsiv2/HTTP_reveice_measures-test.js b/test/unit/ngsiv2/HTTP_reveice_measures-test.js index 7e9f2b10..74e90e4f 100644 --- a/test/unit/ngsiv2/HTTP_reveice_measures-test.js +++ b/test/unit/ngsiv2/HTTP_reveice_measures-test.js @@ -99,10 +99,7 @@ describe('HTTP: Measure reception ', function() { afterEach(function(done) { nock.cleanAll(); - async.series([ - iotAgentLib.clearAll, - iotaJson.stop - ], done); + async.series([iotAgentLib.clearAll, iotaJson.stop], done); }); describe('When a POST measure arrives for the HTTP binding', function() { @@ -114,7 +111,9 @@ describe('HTTP: Measure reception ', function() { temperature: '87', luminosity: 10, pollution: 43.4, - configuration: {firmware: {version: '1.1.0', hash: 'cf23df2207d99a74fbe169e3eba035e633b65d94'}}, + configuration: { + firmware: { version: '1.1.0', hash: 'cf23df2207d99a74fbe169e3eba035e633b65d94' } + }, tags: ['iot', 'device'], enabled: true, alive: null @@ -133,9 +132,11 @@ describe('HTTP: Measure reception ', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/multipleMeasuresJsonTypes.json')) - .query({type: 'AnMQTTDevice'}) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/multipleMeasuresJsonTypes.json') + ) + .query({ type: 'AnMQTTDevice' }) .reply(204); }); it('should return a 200 OK with no error', function(done) { @@ -152,7 +153,6 @@ describe('HTTP: Measure reception ', function() { done(); }); }); - }); describe('When a POST measure arrives with a TimeInstant attribute in the body', function() { @@ -180,7 +180,7 @@ describe('HTTP: Measure reception ', function() { 'fiware-service': 'smartGondor', 'fiware-servicepath': '/gardens' } - }; + }; beforeEach(function(done) { nock.cleanAll(); @@ -196,9 +196,11 @@ describe('HTTP: Measure reception ', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/e0130101/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/timeInstantMeasures.json')) - .query({type: 'sensor'}) + .post( + '/v2/entities/e0130101/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/timeInstantMeasures.json') + ) + .query({ type: 'sensor' }) .reply(204); iotaJson.stop(function() { @@ -266,9 +268,11 @@ describe('HTTP: Measure reception ', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/e0130101/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/timeInstantMeasures.json')) - .query({type: 'sensor'}) + .post( + '/v2/entities/e0130101/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/timeInstantMeasures.json') + ) + .query({ type: 'sensor' }) .reply(204); iotaJson.stop(function() { @@ -325,9 +329,11 @@ describe('HTTP: Measure reception ', function() { contextBrokerUnprovMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/TheLightType:JSON_UNPROVISIONED/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/unprovisionedDevice.json')) - .query({type: 'TheLightType'}) + .post( + '/v2/entities/TheLightType:JSON_UNPROVISIONED/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/unprovisionedDevice.json') + ) + .query({ type: 'TheLightType' }) .reply(204); request(groupCreation, function(error, response, body) { @@ -342,8 +348,4 @@ describe('HTTP: Measure reception ', function() { }); }); }); - - }); - - diff --git a/test/unit/ngsiv2/MQTT_receive_measures-test.js b/test/unit/ngsiv2/MQTT_receive_measures-test.js index fd2f009b..f525351a 100644 --- a/test/unit/ngsiv2/MQTT_receive_measures-test.js +++ b/test/unit/ngsiv2/MQTT_receive_measures-test.js @@ -81,10 +81,13 @@ describe('MQTT: Measure reception ', function() { nock.cleanAll(); - mqttClient = mqtt.connect('mqtt://' + config.mqtt.host, { - keepalive: 0, - connectTimeout: 60 * 60 * 1000 - }); + mqttClient = mqtt.connect( + 'mqtt://' + config.mqtt.host, + { + keepalive: 0, + connectTimeout: 60 * 60 * 1000 + } + ); // 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,10 +109,7 @@ describe('MQTT: Measure reception ', function() { nock.cleanAll(); mqttClient.end(); - async.series([ - iotAgentLib.clearAll, - iotaJson.stop - ], done); + async.series([iotAgentLib.clearAll, iotaJson.stop], done); }); describe('When a new multiple measure arrives to the MQTT Topic', function() { @@ -117,9 +117,11 @@ describe('MQTT: Measure reception ', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/multipleMeasuresJsonTypes.json')) - .query({type: 'AnMQTTDevice'}) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/multipleMeasuresJsonTypes.json') + ) + .query({ type: 'AnMQTTDevice' }) .reply(204); }); it('should send its value to the Context Broker', function(done) { @@ -128,7 +130,9 @@ describe('MQTT: Measure reception ', function() { temperature: '87', luminosity: 10, pollution: 43.4, - configuration: {firmware: {version: '1.1.0', hash: 'cf23df2207d99a74fbe169e3eba035e633b65d94'}}, + configuration: { + firmware: { version: '1.1.0', hash: 'cf23df2207d99a74fbe169e3eba035e633b65d94' } + }, tags: ['iot', 'device'], enabled: true, alive: null @@ -145,7 +149,6 @@ describe('MQTT: Measure reception ', function() { describe('When a new multiple measure arrives for an unprovisioned device', 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 of iotagent-node-lib @@ -158,9 +161,11 @@ describe('MQTT: Measure reception ', function() { contextBrokerUnprovMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/TheLightType:JSON_UNPROVISIONED/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/unprovisionedDevice.json')) - .query({type: 'TheLightType'}) + .post( + '/v2/entities/TheLightType:JSON_UNPROVISIONED/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/unprovisionedDevice.json') + ) + .query({ type: 'TheLightType' }) .reply(204); request(groupCreation, function(error, response, body) { @@ -173,13 +178,14 @@ describe('MQTT: Measure reception ', function() { temperature: '87' }; - mqttClient.publish('/KL223HHV8732SFL1/JSON_UNPROVISIONED/attrs', JSON.stringify(values), null, - function(error) { - setTimeout(function() { - contextBrokerUnprovMock.done(); - done(); - }, 100); - }); + mqttClient.publish('/KL223HHV8732SFL1/JSON_UNPROVISIONED/attrs', JSON.stringify(values), null, function( + error + ) { + setTimeout(function() { + contextBrokerUnprovMock.done(); + done(); + }, 100); + }); }); }); @@ -188,9 +194,11 @@ describe('MQTT: Measure reception ', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/unknownMeasures.json')) - .query({type: 'AnMQTTDevice'}) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/unknownMeasures.json') + ) + .query({ type: 'AnMQTTDevice' }) .reply(204); }); it('should send its value to the Context Broker', function(done) { @@ -213,9 +221,11 @@ describe('MQTT: Measure reception ', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/timestampMeasure.json')) - .query({type: 'AnMQTTDevice'}) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/timestampMeasure.json') + ) + .query({ type: 'AnMQTTDevice' }) .reply(204); }); it('should send its value to the Context Broker', function(done) { @@ -239,9 +249,11 @@ describe('MQTT: Measure reception ', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/singleMeasure.json')) - .query({type: 'AnMQTTDevice'}) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/singleMeasure.json') + ) + .query({ type: 'AnMQTTDevice' }) .reply(204); }); it('should send its values to the Context Broker', function(done) { diff --git a/test/unit/ngsiv2/amqpBinding-test.js b/test/unit/ngsiv2/amqpBinding-test.js index dc42120a..40157966 100644 --- a/test/unit/ngsiv2/amqpBinding-test.js +++ b/test/unit/ngsiv2/amqpBinding-test.js @@ -41,16 +41,19 @@ var iotaJson = require('../../../'), channel; function startConnection(exchange, callback) { - amqp.connect('amqp://localhost', function(err, conn) { - amqpConn = conn; + amqp.connect( + 'amqp://localhost', + function(err, conn) { + amqpConn = conn; - conn.createChannel(function(err, ch) { - ch.assertExchange(exchange, 'topic', {}); + conn.createChannel(function(err, ch) { + ch.assertExchange(exchange, 'topic', {}); - channel = ch; - callback(err); - }); - }); + channel = ch; + callback(err); + }); + } + ); } describe('AMQP Transport binding: measures', function() { @@ -79,11 +82,14 @@ describe('AMQP Transport binding: measures', function() { .post('/v2/entities?options=upsert') .reply(204); - async.series([ - apply(iotaJson.start, config), - apply(request, provisionOptions), - apply(startConnection, config.amqp.exchange) - ], done); + async.series( + [ + apply(iotaJson.start, config), + apply(request, provisionOptions), + apply(startConnection, config.amqp.exchange) + ], + done + ); }); afterEach(function(done) { @@ -92,10 +98,7 @@ describe('AMQP Transport binding: measures', function() { amqpConn.close(); config.iota.defaultResource = oldResource; - async.series([ - iotAgentLib.clearAll, - iotaJson.stop - ], done); + async.series([iotAgentLib.clearAll, iotaJson.stop], done); }); describe('When a new single measure arrives to a Device routing key', function() { @@ -103,9 +106,11 @@ describe('AMQP Transport binding: measures', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/singleMeasureAMQP.json')) - .query({type: 'AnMQTTDevice'}) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/singleMeasureAMQP.json') + ) + .query({ type: 'AnMQTTDevice' }) .reply(204); }); @@ -131,7 +136,6 @@ describe('AMQP Transport binding: measures', 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 of iotagent-node-lib @@ -144,9 +148,11 @@ describe('AMQP Transport binding: measures', function() { contextBrokerUnprovMock .matchHeader('fiware-service', 'TestService') .matchHeader('fiware-servicepath', '/testingPath') - .post('/v2/entities/SensorMachine:JSON_UNPROVISIONED/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/unprovisionedMeasure.json')) - .query({type: 'SensorMachine'}) + .post( + '/v2/entities/SensorMachine:JSON_UNPROVISIONED/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/unprovisionedMeasure.json') + ) + .query({ type: 'SensorMachine' }) .reply(204); request(groupCreation, function(error, response, body) { @@ -169,16 +175,16 @@ describe('AMQP Transport binding: measures', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/singleMeasureAMQP.json')) - .query({type: 'AnMQTTDevice'}) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/singleMeasureAMQP.json') + ) + .query({ type: 'AnMQTTDevice' }) .reply(200, utils.readExampleFile('./test/contextResponses/singleMeasureSuccess.json')); }); it('should send a single update context request with all the attributes', function(done) { - channel.publish(config.amqp.exchange, '.1234.MQTT_2.attrs', new Buffer( - JSON.stringify({a: '23'}) - )); + channel.publish(config.amqp.exchange, '.1234.MQTT_2.attrs', new Buffer(JSON.stringify({ a: '23' }))); setTimeout(function() { contextBrokerMock.done(); @@ -192,8 +198,10 @@ describe('AMQP Transport binding: measures', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/singleMeasureAMQP.json')) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/singleMeasureAMQP.json') + ) .reply(200, utils.readExampleFile('./test/contextResponses/singleMeasureSuccess.json')); }); @@ -211,19 +219,25 @@ describe('AMQP Transport binding: measures', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/multipleMeasure.json')) - .query({type: 'AnMQTTDevice'}) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/multipleMeasure.json') + ) + .query({ type: 'AnMQTTDevice' }) .reply(204); }); it('should send one update context per measure group to the Contet Broker', function(done) { - channel.publish(config.amqp.exchange, '.1234.MQTT_2.attrs', new Buffer( - JSON.stringify({ - a: '23', - b: '98' - }) - )); + channel.publish( + config.amqp.exchange, + '.1234.MQTT_2.attrs', + new Buffer( + JSON.stringify({ + a: '23', + b: '98' + }) + ) + ); setTimeout(function() { contextBrokerMock.done(); diff --git a/test/unit/ngsiv2/attribute-alias_test.js b/test/unit/ngsiv2/attribute-alias_test.js index 9a9e3460..16fbff3e 100644 --- a/test/unit/ngsiv2/attribute-alias_test.js +++ b/test/unit/ngsiv2/attribute-alias_test.js @@ -49,10 +49,13 @@ describe('Attribute alias', function() { nock.cleanAll(); - mqttClient = mqtt.connect('mqtt://' + config.mqtt.host, { - keepalive: 0, - connectTimeout: 60 * 60 * 1000 - }); + mqttClient = mqtt.connect( + 'mqtt://' + config.mqtt.host, + { + keepalive: 0, + connectTimeout: 60 * 60 * 1000 + } + ); // 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,10 +77,7 @@ describe('Attribute alias', function() { nock.cleanAll(); mqttClient.end(); - async.series([ - iotAgentLib.clearAll, - iotaJson.stop - ], done); + async.series([iotAgentLib.clearAll, iotaJson.stop], done); }); describe('When a new multiple measure arrives with a timestamp in an attribute alias', function() { @@ -85,9 +85,11 @@ describe('Attribute alias', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/timestampAliasMeasure.json')) - .query({type: 'AnMQTTDevice'}) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/timestampAliasMeasure.json') + ) + .query({ type: 'AnMQTTDevice' }) .reply(204); }); it('should send its value to the Context Broker', function(done) { diff --git a/test/unit/ngsiv2/bidirectionalityHttp-test.js b/test/unit/ngsiv2/bidirectionalityHttp-test.js index eacf6249..7241b682 100644 --- a/test/unit/ngsiv2/bidirectionalityHttp-test.js +++ b/test/unit/ngsiv2/bidirectionalityHttp-test.js @@ -73,18 +73,15 @@ describe('Data Bidirectionality: HTTP', function() { .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v2/subscriptions', function(body) { - var expectedBody = utils.readExampleFile( - './test/unit/ngsiv2/subscriptions/bidirectionalSubscriptionRequest.json'); + './test/unit/ngsiv2/subscriptions/bidirectionalSubscriptionRequest.json' + ); // Note that expired field is not included in the json used by this mock as it is a dynamic // field. The following code performs such calculation and adds the field to the subscription // payload of the mock. - if (!body.expires) - { + if (!body.expires) { return false; - } - else if (moment(body.expires, 'YYYY-MM-DDTHH:mm:ss.SSSZ').isValid()) - { + } else if (moment(body.expires, 'YYYY-MM-DDTHH:mm:ss.SSSZ').isValid()) { expectedBody.expires = moment().add(config.deviceRegistrationDuration); var expiresDiff = moment(expectedBody.expires).diff(body.expires, 'milliseconds'); if (expiresDiff < 500) { @@ -95,21 +92,21 @@ describe('Data Bidirectionality: HTTP', function() { } return false; - } - else { + } else { return false; } }) - .reply(201, null, {'Location': '/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8'}); + .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/contextRequests/createBidirectionalDevice.json')) + .post( + '/v2/entities?options=upsert', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/createBidirectionalDevice.json') + ) .reply(204); - iotagentJson.start(config, function(error) { request(provisionOptions, function(error, response, body) { done(); @@ -143,15 +140,19 @@ describe('Data Bidirectionality: HTTP', function() { longitudeFound = false; for (var i = 0; i < list.commands.length; i++) { - if (list.commands[i].name === 'latitude' && + if ( + list.commands[i].name === 'latitude' && list.commands[i].type === 'string' && - list.commands[i].value === '-9.6') { + list.commands[i].value === '-9.6' + ) { latitudeFound = true; } - if (list.commands[i].name === 'longitude' && + if ( + list.commands[i].name === 'longitude' && list.commands[i].type === 'string' && - list.commands[i].value === '12.4') { + list.commands[i].value === '12.4' + ) { longitudeFound = true; } } @@ -183,18 +184,15 @@ describe('Data Bidirectionality: HTTP', function() { .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v2/subscriptions', function(body) { - var expectedBody = utils.readExampleFile( - './test/unit/ngsiv2/subscriptions/bidirectionalSubscriptionRequest.json'); + './test/unit/ngsiv2/subscriptions/bidirectionalSubscriptionRequest.json' + ); // Note that expired field is not included in the json used by this mock as it is a dynamic // field. The following code performs such calculation and adds the field to the subscription // payload of the mock. - if (!body.expires) - { + if (!body.expires) { return false; - } - else if (moment(body.expires, 'YYYY-MM-DDTHH:mm:ss.SSSZ').isValid()) - { + } else if (moment(body.expires, 'YYYY-MM-DDTHH:mm:ss.SSSZ').isValid()) { expectedBody.expires = moment().add(config.deviceRegistrationDuration); var expiresDiff = moment(expectedBody.expires).diff(body.expires, 'milliseconds'); if (expiresDiff < 500) { @@ -205,18 +203,19 @@ describe('Data Bidirectionality: HTTP', function() { } return false; - } - else { + } else { return false; } }) - .reply(201, null, {'Location': '/v2/subscriptions/51c0ac9ed714fb3b37d7d5a8'}); + .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/contextRequests/createBidirectionalDevice.json')) + .post( + '/v2/entities?options=upsert', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/createBidirectionalDevice.json') + ) .reply(204); contextBrokerMock diff --git a/test/unit/ngsiv2/config-test.js b/test/unit/ngsiv2/config-test.js index 68e77b97..b61800c1 100644 --- a/test/unit/ngsiv2/config-test.js +++ b/test/unit/ngsiv2/config-test.js @@ -38,7 +38,7 @@ config.amqp = { port: 5672, exchange: 'amq.topic', queue: 'iota_queue', - options: {durable: true} + options: { durable: true } }; config.iota = { diff --git a/test/unit/ngsiv2/configuration-api_test.js b/test/unit/ngsiv2/configuration-api_test.js index 93419655..ffad4bbf 100644 --- a/test/unit/ngsiv2/configuration-api_test.js +++ b/test/unit/ngsiv2/configuration-api_test.js @@ -69,14 +69,16 @@ describe('Configuration API support', function() { } }; - beforeEach(function(done) { nock.cleanAll(); originalResource = config.iota.defaultResource; - mqttClient = mqtt.connect('mqtt://' + config.mqtt.host, { - keepalive: 0, - connectTimeout: 60 * 60 * 1000 - }); + mqttClient = mqtt.connect( + 'mqtt://' + config.mqtt.host, + { + keepalive: 0, + connectTimeout: 60 * 60 * 1000 + } + ); config.iota.iotManager = { host: '127.0.0.1', @@ -90,12 +92,12 @@ describe('Configuration API support', function() { iotamMock = nock('http://127.0.0.1:8081') .post('/iot/protocols', { - protocol: 'TT_MQTT-JSON', - description: 'MQTT-JSON protocol for TT', - iotagent: 'http://localhost:4041', - resource: '/iotamqtt', - services: [] - }) + protocol: 'TT_MQTT-JSON', + description: 'MQTT-JSON protocol for TT', + iotagent: 'http://localhost:4041', + resource: '/iotamqtt', + services: [] + }) .reply(200, {}); // This mock does not check the payload since the aim of the test is not to verify @@ -122,7 +124,8 @@ describe('Configuration API support', function() { describe('When a configuration is provisioned for a service', function() { beforeEach(function() { - iotamMock.post('/iot/protocols', { + iotamMock + .post('/iot/protocols', { protocol: 'TT_MQTT-JSON', description: 'MQTT-JSON protocol for TT', iotagent: 'http://localhost:4041', @@ -143,9 +146,11 @@ describe('Configuration API support', function() { contextBrokerUnprovMock = nock('http://unexistentHost:1026') .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/singleMeasure.json')) - .query({type: 'AnMQTTDevice'}) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/singleMeasure.json') + ) + .query({ type: 'AnMQTTDevice' }) .reply(204); }); @@ -185,10 +190,7 @@ describe('Configuration API support', function() { ] }; - iotamMock - .post('/iot/protocols', configurationProvision) - .reply(200, {}); - + iotamMock.post('/iot/protocols', configurationProvision).reply(200, {}); }); it('should reject the configuration provisioning with a BAD FORMAT error', function(done) { diff --git a/test/unit/ngsiv2/subscription-management_test.js b/test/unit/ngsiv2/subscription-management_test.js index 77a1fdf1..2d4936ad 100644 --- a/test/unit/ngsiv2/subscription-management_test.js +++ b/test/unit/ngsiv2/subscription-management_test.js @@ -69,15 +69,18 @@ describe('Subscription management', function() { beforeEach(function(done) { nock.cleanAll(); - mqttClient = mqtt.connect('mqtt://' + config.mqtt.host, { - keepalive: 0, - connectTimeout: 60 * 60 * 1000 - }); + mqttClient = mqtt.connect( + 'mqtt://' + config.mqtt.host, + { + keepalive: 0, + connectTimeout: 60 * 60 * 1000 + } + ); // 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 of iotagent-node-lib - contextBrokerMock = nock('http://192.168.1.1:1026', {allowUnmocked: false}) + contextBrokerMock = nock('http://192.168.1.1:1026', { allowUnmocked: false }) .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v2/entities?options=upsert') @@ -99,31 +102,38 @@ describe('Subscription management', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/multipleMeasures.json')) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/multipleMeasures.json') + ) .reply(204); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/alternativeUpdate.json')) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/alternativeUpdate.json') + ) .reply(204); }); it('should cease sending measures to the CB', function(done) { - async.series([ - async.apply(request, provisionOptions), - sendMeasures('32', '87'), - waitForMqttRelay(50), - iotaJson.stop, - sendMeasures('53', '1'), - waitForMqttRelay(50) - ], function(error, results) { - should.not.exist(error); - contextBrokerMock.isDone().should.equal(false); - done(); - }); + async.series( + [ + async.apply(request, provisionOptions), + sendMeasures('32', '87'), + waitForMqttRelay(50), + iotaJson.stop, + sendMeasures('53', '1'), + waitForMqttRelay(50) + ], + function(error, results) { + should.not.exist(error); + contextBrokerMock.isDone().should.equal(false); + done(); + } + ); }); }); @@ -132,42 +142,46 @@ describe('Subscription management', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/multipleMeasures.json')) - .query({type: 'AnMQTTDevice'}) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/multipleMeasures.json') + ) + .query({ type: 'AnMQTTDevice' }) .reply(204); contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/alternativeUpdate.json')) - .query({type: 'AnMQTTDevice'}) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/alternativeUpdate.json') + ) + .query({ type: 'AnMQTTDevice' }) .reply(204); }); afterEach(function(done) { - async.series([ - iotAgentLib.clearAll, - iotaJson.stop - ], done); + async.series([iotAgentLib.clearAll, iotaJson.stop], done); }); it('should resume sending measures for the provisioned devices', function(done) { - async.series([ - async.apply(request, provisionOptions), - sendMeasures('32', '87'), - waitForMqttRelay(50), - iotaJson.stop, - async.apply(iotaJson.start, config), - waitForMqttRelay(50), - sendMeasures('53', '1'), - waitForMqttRelay(50) - ], function(error, results) { - should.not.exist(error); - contextBrokerMock.isDone().should.equal(true); - done(); - }); + async.series( + [ + async.apply(request, provisionOptions), + sendMeasures('32', '87'), + waitForMqttRelay(50), + iotaJson.stop, + async.apply(iotaJson.start, config), + waitForMqttRelay(50), + sendMeasures('53', '1'), + waitForMqttRelay(50) + ], + function(error, results) { + should.not.exist(error); + contextBrokerMock.isDone().should.equal(true); + done(); + } + ); }); }); }); diff --git a/test/unit/ngsiv2/supportThinkingThingModules_test.js b/test/unit/ngsiv2/supportThinkingThingModules_test.js index 99364e42..8bed4a80 100644 --- a/test/unit/ngsiv2/supportThinkingThingModules_test.js +++ b/test/unit/ngsiv2/supportThinkingThingModules_test.js @@ -49,10 +49,13 @@ describe('Support for Thinking Things Modules', function() { nock.cleanAll(); - mqttClient = mqtt.connect('mqtt://' + config.mqtt.host, { - keepalive: 0, - connectTimeout: 60 * 60 * 1000 - }); + mqttClient = mqtt.connect( + 'mqtt://' + config.mqtt.host, + { + keepalive: 0, + connectTimeout: 60 * 60 * 1000 + } + ); // 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 @@ -73,11 +76,7 @@ describe('Support for Thinking Things Modules', function() { afterEach(function(done) { nock.cleanAll(); mqttClient.end(); - async.series([ - iotAgentLib.clearAll, - iotaJson.stop - ], done); - + async.series([iotAgentLib.clearAll, iotaJson.stop], done); }); describe('When a new measure with Thinking Thing module P1 arrives to a multiattribute topic', function() { @@ -85,9 +84,11 @@ describe('Support for Thinking Things Modules', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/TTModuleP1.json')) - .query({type: 'AnMQTTDevice'}) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/TTModuleP1.json') + ) + .query({ type: 'AnMQTTDevice' }) .reply(204); }); it('should send its value to the Context Broker', function(done) { @@ -110,9 +111,11 @@ describe('Support for Thinking Things Modules', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/TTModuleP1Single.json')) - .query({type: 'AnMQTTDevice'}) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/TTModuleP1Single.json') + ) + .query({ type: 'AnMQTTDevice' }) .reply(204); }); it('should send its value to the Context Broker', function(done) { @@ -132,9 +135,11 @@ describe('Support for Thinking Things Modules', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/TTModuleC1.json')) - .query({type: 'AnMQTTDevice'}) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/TTModuleC1.json') + ) + .query({ type: 'AnMQTTDevice' }) .reply(204); }); it('should send its value to the Context Broker', function(done) { @@ -157,9 +162,11 @@ describe('Support for Thinking Things Modules', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/TTModuleC1Single.json')) - .query({type: 'AnMQTTDevice'}) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/TTModuleC1Single.json') + ) + .query({ type: 'AnMQTTDevice' }) .reply(204); }); it('should send its value to the Context Broker', function(done) { @@ -179,9 +186,11 @@ describe('Support for Thinking Things Modules', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/TTModuleB.json')) - .query({type: 'AnMQTTDevice'}) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/TTModuleB.json') + ) + .query({ type: 'AnMQTTDevice' }) .reply(204); }); it('should send its value to the Context Broker', function(done) { @@ -204,9 +213,11 @@ describe('Support for Thinking Things Modules', function() { contextBrokerMock .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') - .post('/v2/entities/Second%20MQTT%20Device/attrs', - utils.readExampleFile('./test/unit/ngsiv2/contextRequests/TTModuleBLong.json')) - .query({type: 'AnMQTTDevice'}) + .post( + '/v2/entities/Second%20MQTT%20Device/attrs', + utils.readExampleFile('./test/unit/ngsiv2/contextRequests/TTModuleBLong.json') + ) + .query({ type: 'AnMQTTDevice' }) .reply(204); }); it('should send its value to the Context Broker', function(done) { @@ -223,5 +234,4 @@ describe('Support for Thinking Things Modules', function() { }); }); }); - }); diff --git a/test/unit/startup-test.js b/test/unit/startup-test.js index 27263098..8bc26700 100644 --- a/test/unit/startup-test.js +++ b/test/unit/startup-test.js @@ -34,15 +34,15 @@ describe('Startup tests', function() { beforeEach(function() { sinon.stub(fs, 'readFileSync'); sinon.stub(mqtt, 'connect').returns({ - end: sinon.stub().callsFake(function (force, callback) { + end: sinon.stub().callsFake(function(force, callback) { callback(); }), - on: sinon.stub().callsFake(function (type, listener) { + on: sinon.stub().callsFake(function(type, listener) { if (type === 'connect') { listener(); } }), - subscribe: sinon.stub().callsFake(function (topics, _, callback) { + subscribe: sinon.stub().callsFake(function(topics, _, callback) { callback(false); }), unsubscribe: sinon.spy() @@ -81,6 +81,7 @@ describe('Startup tests', function() { iotagentJSON.start(iotAgentConfig, function(error) { should.not.exist(error); + //prettier-ignore mqtt.connect.calledOnceWithExactly({ ca: null, cert: null, @@ -93,7 +94,8 @@ describe('Startup tests', function() { protocol: 'mqtt', rejectUnauthorized: true, username: 'usermqtt' - }).should.equal(true); + }) + .should.equal(true); var mqttConfig = config.getConfig().mqtt; mqttConfig.host.should.equal('127.0.0.1'); @@ -118,6 +120,7 @@ describe('Startup tests', function() { iotagentJSON.start(iotAgentConfig, function(error) { should.not.exist(error); + //prettier-ignore mqtt.connect.calledOnceWithExactly({ ca: null, cert: null, @@ -130,7 +133,8 @@ describe('Startup tests', function() { protocol: 'mqtts', rejectUnauthorized: false, username: null - }).should.equal(true); + }) + .should.equal(true); var mqttConfig = config.getConfig().mqtt; mqttConfig.protocol.should.equal('mqtts'); @@ -151,8 +155,8 @@ describe('Startup tests', function() { process.env.IOTA_MQTT_CA = '/run/secrets/ca.pem'; process.env.IOTA_MQTT_REJECT_UNAUTHORIZED = 'true'; - fs.readFileSync.callsFake(function (filename) { - switch(filename) { + fs.readFileSync.callsFake(function(filename) { + switch (filename) { case process.env.IOTA_MQTT_CERT: return 'certcontent'; case process.env.IOTA_MQTT_KEY: @@ -165,6 +169,7 @@ describe('Startup tests', function() { iotagentJSON.start(iotAgentConfig, function(error) { should.not.exist(error); + //prettier-ignore mqtt.connect.calledOnceWithExactly({ ca: 'cacontent', cert: 'certcontent', @@ -177,7 +182,8 @@ describe('Startup tests', function() { protocol: 'mqtts', rejectUnauthorized: true, username: null - }).should.equal(true); + }) + .should.equal(true); var mqttConfig = config.getConfig().mqtt; mqttConfig.protocol.should.equal('mqtts'); diff --git a/test/unit/subscription-management_test.js b/test/unit/subscription-management_test.js index 8ef1e56b..7242e29f 100644 --- a/test/unit/subscription-management_test.js +++ b/test/unit/subscription-management_test.js @@ -67,12 +67,15 @@ describe('Subscription management', function() { beforeEach(function(done) { nock.cleanAll(); - mqttClient = mqtt.connect('mqtt://' + config.mqtt.host, { - keepalive: 0, - connectTimeout: 60 * 60 * 1000 - }); - - contextBrokerMock = nock('http://192.168.1.1:1026', {allowUnmocked: false}) + mqttClient = mqtt.connect( + 'mqtt://' + config.mqtt.host, + { + keepalive: 0, + connectTimeout: 60 * 60 * 1000 + } + ); + + contextBrokerMock = nock('http://192.168.1.1:1026', { allowUnmocked: false }) .matchHeader('fiware-service', 'smartGondor') .matchHeader('fiware-servicepath', '/gardens') .post('/v1/updateContext') @@ -105,18 +108,21 @@ describe('Subscription management', function() { }); it('should cease sending measures to the CB', function(done) { - async.series([ - async.apply(request, provisionOptions), - sendMeasures('32', '87'), - waitForMqttRelay(50), - iotagentMqtt.stop, - sendMeasures('53', '1'), - waitForMqttRelay(50) - ], function(error, results) { - should.not.exist(error); - contextBrokerMock.isDone().should.equal(false); - done(); - }); + async.series( + [ + async.apply(request, provisionOptions), + sendMeasures('32', '87'), + waitForMqttRelay(50), + iotagentMqtt.stop, + sendMeasures('53', '1'), + waitForMqttRelay(50) + ], + function(error, results) { + should.not.exist(error); + contextBrokerMock.isDone().should.equal(false); + done(); + } + ); }); }); @@ -136,27 +142,27 @@ describe('Subscription management', function() { }); afterEach(function(done) { - async.series([ - iotAgentLib.clearAll, - iotagentMqtt.stop - ], done); + async.series([iotAgentLib.clearAll, iotagentMqtt.stop], done); }); it('should resume sending measures for the provisioned devices', function(done) { - async.series([ - async.apply(request, provisionOptions), - sendMeasures('32', '87'), - waitForMqttRelay(50), - iotagentMqtt.stop, - async.apply(iotagentMqtt.start, config), - waitForMqttRelay(50), - sendMeasures('53', '1'), - waitForMqttRelay(50) - ], function(error, results) { - should.not.exist(error); - contextBrokerMock.isDone().should.equal(true); - done(); - }); + async.series( + [ + async.apply(request, provisionOptions), + sendMeasures('32', '87'), + waitForMqttRelay(50), + iotagentMqtt.stop, + async.apply(iotagentMqtt.start, config), + waitForMqttRelay(50), + sendMeasures('53', '1'), + waitForMqttRelay(50) + ], + function(error, results) { + should.not.exist(error); + contextBrokerMock.isDone().should.equal(true); + done(); + } + ); }); }); }); diff --git a/test/unit/supportThinkingThingModules_test.js b/test/unit/supportThinkingThingModules_test.js index 44f68eee..8c74689d 100644 --- a/test/unit/supportThinkingThingModules_test.js +++ b/test/unit/supportThinkingThingModules_test.js @@ -47,10 +47,13 @@ describe('Support for Thinking Things Modules', function() { nock.cleanAll(); - mqttClient = mqtt.connect('mqtt://' + config.mqtt.host, { - keepalive: 0, - connectTimeout: 60 * 60 * 1000 - }); + mqttClient = mqtt.connect( + 'mqtt://' + config.mqtt.host, + { + keepalive: 0, + connectTimeout: 60 * 60 * 1000 + } + ); contextBrokerMock = nock('http://192.168.1.1:1026') .matchHeader('fiware-service', 'smartGondor') @@ -68,11 +71,7 @@ describe('Support for Thinking Things Modules', function() { afterEach(function(done) { nock.cleanAll(); mqttClient.end(); - async.series([ - iotAgentLib.clearAll, - iotagentMqtt.stop - ], done); - + async.series([iotAgentLib.clearAll, iotagentMqtt.stop], done); }); describe('When a new measure with Thinking Thing module P1 arrives to a multiattribute topic', function() {