From d02d14f39e9736163de2b4b9bb9abd9cad7d15b9 Mon Sep 17 00:00:00 2001 From: Jason Fox Date: Mon, 28 Jan 2019 12:28:40 +0100 Subject: [PATCH 01/11] Add prettier, husky and lint-staged --- package.json | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/package.json b/package.json index e7558f96..041641de 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,7 @@ { "name": "perseo", "description": "IOT CEP front End", + "license": "AGPL-3.0-only", "version": "1.7.0-next", "homepage": "", "author": { @@ -23,16 +24,20 @@ "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 --single-quote --trailing-comma es5 --write **/*.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", "istanbul": "~0.4.5", "jshint": "~2.9.6", + "lint-staged": "^7.3.0", "mocha": "5.2.0", "proxyquire": "0.5.1", + "prettier": "^1.14.2", "should": "8.2.2", "watch": "~1.0.2" }, @@ -50,5 +55,16 @@ "utm-converter": "~0.1.1", "uuid": "~1.4.2", "smpp": "0.3.1" + }, + "husky": { + "hooks": { + "pre-commit": "lint-staged" + } + }, + "lint-staged": { + "*.js": [ + "prettier --parser flow --single-quote --trailing-comma es5 --write", + "git add" + ] } } From b468187d280c1cb9562630aa0545412b3cdb654f Mon Sep 17 00:00:00 2001 From: Jason Fox Date: Mon, 28 Jan 2019 12:28:58 +0100 Subject: [PATCH 02/11] Run `npm run prettier` to format files - whitespace changes only. --- config.js | 118 +++++++------- index.js | 2 +- lib/alarm.js | 49 +++--- lib/appContext.js | 13 +- lib/constants.js | 13 +- lib/db.js | 188 +++++++++++---------- lib/myutils.js | 399 ++++++++++++++++++++++++++------------------- lib/perseo.js | 251 ++++++++++++++-------------- lib/refreshCore.js | 60 ++++--- 9 files changed, 587 insertions(+), 506 deletions(-) diff --git a/config.js b/config.js index 291b524d..0c678025 100644 --- a/config.js +++ b/config.js @@ -31,21 +31,20 @@ var config = {}; */ config.logLevel = 'INFO'; - /** * Configures the exposed API. */ config.endpoint = { - host: 'localhost', - port: 9090, - rulesPath : '/rules', - actionsPath : '/actions/do', - noticesPath : '/notices', - vrPath : '/m2m/vrules', - checkPath : '/check', - versionPath : '/version', - logPath: '/admin/log', - metricsPath: '/admin/metrics' + host: 'localhost', + port: 9090, + rulesPath: '/rules', + actionsPath: '/actions/do', + noticesPath: '/notices', + vrPath: '/m2m/vrules', + checkPath: '/check', + versionPath: '/version', + logPath: '/admin/log', + metricsPath: '/admin/metrics', }; /** @@ -58,28 +57,26 @@ config.isMaster = true; */ config.slaveDelay = 500; - /** * DB Configuration. */ config.mongo = { - // The URI to use for the database connection. It supports replica set URIs. - // mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]] - // I.e.: 'mongodb://user:pass@host1:27017,host2:27018,host3:27019/cep?replicaSet=myrep' - url : 'mongodb://localhost:27017/cep' + // The URI to use for the database connection. It supports replica set URIs. + // mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]] + // I.e.: 'mongodb://user:pass@host1:27017,host2:27018,host3:27019/cep?replicaSet=myrep' + url: 'mongodb://localhost:27017/cep', }; /** * OrionDB Configuration. */ config.orionDb = { - url : 'mongodb://localhost:27017/orion', - collection : 'entities', - prefix : 'orion', - batchSize: 500 + url: 'mongodb://localhost:27017/orion', + collection: 'entities', + prefix: 'orion', + batchSize: 500, }; - /** * EPL core options * @@ -87,83 +84,80 @@ config.orionDb = { * at core. Each <> ms, the rules are sent to core. */ config.perseoCore = { - rulesURL : 'http://localhost:8080/perseo-core/rules', - noticesURL : 'http://localhost:8080/perseo-core/events', - interval: 60e3*5 + rulesURL: 'http://localhost:8080/perseo-core/rules', + noticesURL: 'http://localhost:8080/perseo-core/events', + interval: 60e3 * 5, }; /** * NEXT EPL core options (with HA) */ config.nextCore = { - // - // Note this parameter is empty, so Perseo will not use HA by default - // - /* + // + // Note this parameter is empty, so Perseo will not use HA by default + // + /* rulesURL : 'http://next-core:8080/perseo-core/rules', noticesURL : 'http://next-core:8080/perseo-core/events' */ }; - /** * SMTP endpoint options */ config.smtp = { - port: 25, - host: 'smtpserver', - secure: false - /* + port: 25, + host: 'smtpserver', + secure: false, + /* , auth: { user: 'abc', pass: 'xyz' } */ - , - tls: { - // keep rejectUnauthorized to false when secure is also false - rejectUnauthorized: false - } - + tls: { + // keep rejectUnauthorized to false when secure is also false + rejectUnauthorized: false, + }, }; /** * SMS endpoint options */ config.sms = { - URL : 'http://sms-endpoint/smsoutbound', - API_KEY : '', - API_SECRET: '', - from: 'tel:22012;phone-context=+34' + URL: 'http://sms-endpoint/smsoutbound', + API_KEY: '', + API_SECRET: '', + from: 'tel:22012;phone-context=+34', }; /** * SMPP endpoint options */ config.smpp = { - host: '', - port: '', - systemid: '', - password: '', - from: '346666666', - enabled: false + host: '', + port: '', + systemid: '', + password: '', + from: '346666666', + enabled: false, }; /** * Orion (Context Broker) endpoint options */ config.orion = { - URL : 'http://orion-endpoint:1026/NGSI10/updateContext' + URL: 'http://orion-endpoint:1026/NGSI10/updateContext', }; /** * Authorization endpoint */ config.authentication = { - host: 'keystone', - port: '5001', - user: 'user', - password: 'password' + host: 'keystone', + port: '5001', + user: 'user', + password: 'password', }; /** @@ -171,8 +165,8 @@ config.authentication = { * @type {{}} */ config.collections = { - rules : 'rules', - executions: 'executions' + rules: 'rules', + executions: 'executions', }; /** @@ -190,8 +184,8 @@ config.executionsTTL = 1 * 24 * 60 * 60; * * @type {{}} */ -config.DEFAULT_SUBSERVICE= '/'; -config.DEFAULT_SERVICE= 'unknownt'; +config.DEFAULT_SUBSERVICE = '/'; +config.DEFAULT_SERVICE = 'unknownt'; /** * CheckDB configuration @@ -203,10 +197,10 @@ config.DEFAULT_SERVICE= 'unknownt'; * @type {Number} */ config.checkDB = { - delay: 5e3, - reconnectTries: 1e3, - reconnectInterval: 5e3, - bufferMaxEntries: 5 + delay: 5e3, + reconnectTries: 1e3, + reconnectInterval: 5e3, + bufferMaxEntries: 5, }; /** diff --git a/index.js b/index.js index 05555f9a..9c4145de 100644 --- a/index.js +++ b/index.js @@ -1 +1 @@ -module.exports = require('./lib/perseo'); \ No newline at end of file +module.exports = require('./lib/perseo'); diff --git a/lib/alarm.js b/lib/alarm.js index 6b1571c3..eceb3eb5 100644 --- a/lib/alarm.js +++ b/lib/alarm.js @@ -24,35 +24,34 @@ 'use strict'; var util = require('util'), - logger = require('logops'), - alarms = {}; - + logger = require('logops'), + alarms = {}; function raise(alarm, context, message) { - var state = alarms[alarm]; - context = (process.domain && process.domain.context) || {}; - if (typeof message === 'object' && message) { - message = util.format('%j', message); - } - message = message || ''; - if (state !== true) { - // emit ERROR alarm ON - logger.error(context, 'ALARM-ON [' + alarm + '] ' + message); - } - alarms[alarm] = true; + var state = alarms[alarm]; + context = (process.domain && process.domain.context) || {}; + if (typeof message === 'object' && message) { + message = util.format('%j', message); + } + message = message || ''; + if (state !== true) { + // emit ERROR alarm ON + logger.error(context, 'ALARM-ON [' + alarm + '] ' + message); + } + alarms[alarm] = true; } function release(alarm, context, message) { - var state = alarms[alarm]; - context = (process.domain && process.domain.context) || {}; - if (typeof message === 'object' && message) { - message = util.format('%j', message); - } - message = message || ''; - if (state === true) { - // emit ERROR alarm OFF - logger.error(context, 'ALARM-OFF [' + alarm + '] ' + message); - } - alarms[alarm] = false; + var state = alarms[alarm]; + context = (process.domain && process.domain.context) || {}; + if (typeof message === 'object' && message) { + message = util.format('%j', message); + } + message = message || ''; + if (state === true) { + // emit ERROR alarm OFF + logger.error(context, 'ALARM-OFF [' + alarm + '] ' + message); + } + alarms[alarm] = false; } module.exports.raise = raise; diff --git a/lib/appContext.js b/lib/appContext.js index c662912e..bb42196b 100644 --- a/lib/appContext.js +++ b/lib/appContext.js @@ -22,23 +22,21 @@ */ 'use strict'; -var - database, - orionDatabase; +var database, orionDatabase; function SetDB(db) { - database = db; + database = db; } function DB() { - return database; + return database; } function SetOrionDB(db) { - orionDatabase = db; + orionDatabase = db; } function OrionDB(database) { - return orionDatabase.db(database); + return orionDatabase.db(database); } /** @@ -67,4 +65,3 @@ module.exports.SetOrionDB = SetOrionDB; * @return {Object} db connection */ module.exports.OrionDb = OrionDB; - diff --git a/lib/constants.js b/lib/constants.js index ef8e1c4b..01c48d26 100644 --- a/lib/constants.js +++ b/lib/constants.js @@ -27,11 +27,10 @@ * */ module.exports = { - SUBSERVICE_HEADER: 'fiware-servicepath', - SERVICE_HEADER: 'fiware-service', - CORRELATOR_HEADER: 'fiware-correlator', - AUTH_HEADER: 'X-Auth-Token', - REALIP_HEADER: 'X-Real-IP', - COMPONENT_NAME: 'perseo-fe' + SUBSERVICE_HEADER: 'fiware-servicepath', + SERVICE_HEADER: 'fiware-service', + CORRELATOR_HEADER: 'fiware-correlator', + AUTH_HEADER: 'X-Auth-Token', + REALIP_HEADER: 'X-Real-IP', + COMPONENT_NAME: 'perseo-fe', }; - diff --git a/lib/db.js b/lib/db.js index 8027ed17..e3093d3a 100644 --- a/lib/db.js +++ b/lib/db.js @@ -22,111 +22,129 @@ */ 'use strict'; var async = require('async'), - logger = require('logops'), - config = require('../config'), - rulesCollection = require('../config').collections.rules, - executionsCollection = require('../config').collections.executions, - myutils = require('./myutils'), - constants = require('./constants'), - alarm = require('./alarm'), - database, - orionDb, - delay = config.checkDB.delay, - context = {comp: constants.COMPONENT_NAME, op: 'checkDB'}; + logger = require('logops'), + config = require('../config'), + rulesCollection = require('../config').collections.rules, + executionsCollection = require('../config').collections.executions, + myutils = require('./myutils'), + constants = require('./constants'), + alarm = require('./alarm'), + database, + orionDb, + delay = config.checkDB.delay, + context = { comp: constants.COMPONENT_NAME, op: 'checkDB' }; function pingAux(db, component, callback) { - db.command({ping: 1}, function(err, result) { - if (err) { - alarm.raise(component, context, err.message); - } - else { - alarm.release(component, context, result); - } - return callback(err, result); - }); + db.command({ ping: 1 }, function(err, result) { + if (err) { + alarm.raise(component, context, err.message); + } else { + alarm.release(component, context, result); + } + return callback(err, result); + }); } function getDbAux(url, component, callback) { - var client = require('mongodb').MongoClient, - checkDbHealthFunc; - client.connect(url, { - db: { - bufferMaxEntries: config.checkDB.bufferMaxEntries, - domainsEnabled: true - }, - server: { - reconnectTries: config.checkDB.reconnectTries, - reconnectInterval: config.checkDB.reconnectInterval, - domainsEnabled: true - } - }, function(err, db) { - if (err) { - myutils.logErrorIf(err, 'connect', context); - return callback(err, null); - } + var client = require('mongodb').MongoClient, + checkDbHealthFunc; + client.connect( + url, + { + db: { + bufferMaxEntries: config.checkDB.bufferMaxEntries, + domainsEnabled: true, + }, + server: { + reconnectTries: config.checkDB.reconnectTries, + reconnectInterval: config.checkDB.reconnectInterval, + domainsEnabled: true, + }, + }, + function(err, db) { + if (err) { + myutils.logErrorIf(err, 'connect', context); + return callback(err, null); + } - // This event is emitted only by Server topology (standalone) - // The driver has given up getting a connection, so we will die (restart perseo usually) - // and re-try from scratch. - // The ReplSet does not emit 'reconnectFailed' - db.serverConfig.on('reconnectFailed', function() { - logger.fatal('too many tries to reconnect to database, dying ...'); - process.exit(-2); - }); + // This event is emitted only by Server topology (standalone) + // The driver has given up getting a connection, so we will die (restart perseo usually) + // and re-try from scratch. + // The ReplSet does not emit 'reconnectFailed' + db.serverConfig.on('reconnectFailed', function() { + logger.fatal('too many tries to reconnect to database, dying ...'); + process.exit(-2); + }); - checkDbHealthFunc = function checkDbHealth() { - pingAux(db, component, function(err, result) { - logger.debug('ping (%s) %j', component, err || result); - }); - }; - setInterval(checkDbHealthFunc, delay); - return callback(null, db); - }); + checkDbHealthFunc = function checkDbHealth() { + pingAux(db, component, function(err, result) { + logger.debug('ping (%s) %j', component, err || result); + }); + }; + setInterval(checkDbHealthFunc, delay); + return callback(null, db); + } + ); } function getDb(callback) { - getDbAux(config.mongo.url, alarm.DATABASE, function cb(err, db) { - database = db; - callback(err, db); - }); + getDbAux(config.mongo.url, alarm.DATABASE, function cb(err, db) { + database = db; + callback(err, db); + }); } function getOrionDb(callback) { - getDbAux(config.orionDb.url, alarm.DATABASE_ORION, function cb(err, db) { - orionDb = db; - callback(err, db); - }); + getDbAux(config.orionDb.url, alarm.DATABASE_ORION, function cb(err, db) { + orionDb = db; + callback(err, db); + }); } function ensureIndex(collection, fields, callback) { - database.collection(collection, function(err, collection) { - myutils.logErrorIf(err, collection, context); - collection.ensureIndex(fields, {unique: true}, function(err, indexName) { - myutils.logErrorIf(err, 'ensureIndex ' + collection, context); - callback(err, indexName); - }); + database.collection(collection, function(err, collection) { + myutils.logErrorIf(err, collection, context); + collection.ensureIndex(fields, { unique: true }, function(err, indexName) { + myutils.logErrorIf(err, 'ensureIndex ' + collection, context); + callback(err, indexName); }); + }); } function ensureIndexTTL(collection, fields, ttl, callback) { - database.collection(collection, function(err, collection) { - myutils.logErrorIf(err, collection); - collection.ensureIndex(fields, {expireAfterSeconds: ttl}, function(err, indexName) { - myutils.logErrorIf(err, 'ensureIndex ' + collection, context); - callback(err, indexName); - }); + database.collection(collection, function(err, collection) { + myutils.logErrorIf(err, collection); + collection.ensureIndex(fields, { expireAfterSeconds: ttl }, function( + err, + indexName + ) { + myutils.logErrorIf(err, 'ensureIndex ' + collection, context); + callback(err, indexName); }); + }); } function setUp(cbSU) { - async.parallel([ - ensureIndex.bind(null, rulesCollection, {name: 1, subservice: 1, service: 1}), - ensureIndexTTL.bind(null, executionsCollection, {lastTime: 1}, config.executionsTTL) - ], cbSU); + async.parallel( + [ + ensureIndex.bind(null, rulesCollection, { + name: 1, + subservice: 1, + service: 1, + }), + ensureIndexTTL.bind( + null, + executionsCollection, + { lastTime: 1 }, + config.executionsTTL + ), + ], + cbSU + ); } function closeAux(db, callback) { - db.close(function(err) { - myutils.logErrorIf(err, 'close', context); - callback(err); - }); + db.close(function(err) { + myutils.logErrorIf(err, 'close', context); + callback(err); + }); } /** @@ -148,7 +166,7 @@ module.exports.getOrionDb = getOrionDb; * @param {function} callback function(error, commandResult) */ module.exports.ping = function(callback) { - pingAux(database, alarm.DATABASE, callback); + pingAux(database, alarm.DATABASE, callback); }; /** @@ -157,7 +175,7 @@ module.exports.ping = function(callback) { * @param {function} callback function(error, commandResult) */ module.exports.orionPing = function(callback) { - pingAux(orionDb, alarm.DATABASE_ORION, callback); + pingAux(orionDb, alarm.DATABASE_ORION, callback); }; /** @@ -175,7 +193,7 @@ module.exports.setUp = setUp; * @param {function} callback function(error) */ module.exports.close = function(callback) { - closeAux(database, callback); + closeAux(database, callback); }; /** @@ -185,5 +203,5 @@ module.exports.close = function(callback) { * @param {function} callback function(error) */ module.exports.orionClose = function(callback) { - closeAux(orionDb, callback); + closeAux(orionDb, callback); }; diff --git a/lib/myutils.js b/lib/myutils.js index 7cc12c28..1694b2b6 100644 --- a/lib/myutils.js +++ b/lib/myutils.js @@ -24,235 +24,290 @@ 'use strict'; var request = require('request'), - util = require('util'), - logger = require('logops'), - constants = require('./constants'), - metrics = require('./models/metrics'); + util = require('util'), + logger = require('logops'), + constants = require('./constants'), + metrics = require('./models/metrics'); function logErrorIf(err, message, context) { - var level = 'error'; - if (context === undefined) { - context = process.domain && process.domain.context; + var level = 'error'; + if (context === undefined) { + context = process.domain && process.domain.context; + } + if (err) { + message = message || ''; + if (context) { + context.op = + context.op || + new Error().stack + .split('\n')[2] + .trim() + .substr(3); + context.comp = context.comp || constants.COMPONENT_NAME; + logger[level](context, message, err.message || JSON.stringify(err)); + } else { + logger[level](message, err.message || JSON.stringify(err)); } - if (err) { - message = message || ''; - if (context) { - context.op = context.op || new Error().stack.split('\n')[2].trim().substr(3); - context.comp = context.comp || constants.COMPONENT_NAME; - logger[level](context, message, err.message || JSON.stringify(err)); - } - else { - logger[level](message, err.message || JSON.stringify(err)); - } - } - + } } function expandVar(val, mapping) { - if (typeof val === 'string') { - Object.keys(mapping).forEach(function(p) { - - val = val.replace( - new RegExp('\\$\\{' + p + '\\}', 'g'), - mapping[p] - ); - - }); - val = val.replace(/\$\{\w*\}/g, '[?]'); - } - return val; + if (typeof val === 'string') { + Object.keys(mapping).forEach(function(p) { + val = val.replace(new RegExp('\\$\\{' + p + '\\}', 'g'), mapping[p]); + }); + val = val.replace(/\$\{\w*\}/g, '[?]'); + } + return val; } function expandObject(templateObj, dictionary) { - var res = {}; - if (templateObj && typeof templateObj === 'object') { - Object.keys(templateObj).forEach(function(key) { - if (typeof templateObj[key] === 'string') { - res[expandVar(key, dictionary)] = expandVar(templateObj[key], dictionary); - } else if (typeof templateObj[key] === 'object') { - res[expandVar(key, dictionary)] = expandObject(templateObj[key], dictionary); - } - }); - } - return res; + var res = {}; + if (templateObj && typeof templateObj === 'object') { + Object.keys(templateObj).forEach(function(key) { + if (typeof templateObj[key] === 'string') { + res[expandVar(key, dictionary)] = expandVar( + templateObj[key], + dictionary + ); + } else if (typeof templateObj[key] === 'object') { + res[expandVar(key, dictionary)] = expandObject( + templateObj[key], + dictionary + ); + } + }); + } + return res; } // Think better if this is the best way function flattenMap(key, targetMap) { - var newMap = {}, v, flattened, fv; - Object.keys(targetMap).forEach(function(k) { - v = targetMap[k]; - if (v && typeof v === 'object') { - flattened = flattenMap(k + '__', v); - Object.keys(flattened).forEach(function(fk) { - fv = flattened[fk]; - newMap[key + fk] = fv; - }); - } else { - newMap[key + k] = v; - } - }); - return newMap; + var newMap = {}, + v, + flattened, + fv; + Object.keys(targetMap).forEach(function(k) { + v = targetMap[k]; + if (v && typeof v === 'object') { + flattened = flattenMap(k + '__', v); + Object.keys(flattened).forEach(function(fk) { + fv = flattened[fk]; + newMap[key + fk] = fv; + }); + } else { + newMap[key + k] = v; + } + }); + return newMap; } function requestHelperAux(method, options, withMetrics, callback) { - var localError, respObj, headers, - domain = process.domain; - logger.info('making %s to %s', method, options.url); - if (withMetrics && domain.context) { - metrics.IncMetrics(domain.context.srv, domain.context.subsrv, metrics.outgoingTransactions); + var localError, + respObj, + headers, + domain = process.domain; + logger.info('making %s to %s', method, options.url); + if (withMetrics && domain.context) { + metrics.IncMetrics( + domain.context.srv, + domain.context.subsrv, + metrics.outgoingTransactions + ); + } + headers = options.headers || {}; + if (domain && domain.context) { + headers[constants.CORRELATOR_HEADER] = domain.context.corr; + if (domain.context.srv && headers[constants.SERVICE_HEADER] === undefined) { + headers[constants.SERVICE_HEADER] = domain.context.srv; } - headers = options.headers || {}; - if (domain && domain.context) { - headers[constants.CORRELATOR_HEADER] = domain.context.corr; - if (domain.context.srv && headers[constants.SERVICE_HEADER] === undefined) { - headers[constants.SERVICE_HEADER] = domain.context.srv; - } - if (domain.context.subsrv && headers[constants.SUBSERVICE_HEADER] === undefined) { - headers[constants.SUBSERVICE_HEADER] = domain.context.subsrv; - } - if (domain.context.from && headers[constants.REALIP_HEADER] === undefined) { - headers[constants.REALIP_HEADER] = domain.context.from; - } + if ( + domain.context.subsrv && + headers[constants.SUBSERVICE_HEADER] === undefined + ) { + headers[constants.SUBSERVICE_HEADER] = domain.context.subsrv; } - options.headers = headers; - if (withMetrics && options.json && domain.context) { - try { - metrics.IncMetrics(domain.context.srv, domain.context.subsrv, metrics.outgoingTransactionsRequestSize, - Buffer.byteLength(JSON.stringify(options.body), 'utf-8')); - } catch (exception) { - logger.warn(exception); - } + if (domain.context.from && headers[constants.REALIP_HEADER] === undefined) { + headers[constants.REALIP_HEADER] = domain.context.from; } - request[method](options, function cbRequest2core(err, response, body) { - var bodySz = 0; - if (withMetrics && domain.context) { - if (body) { - if (typeof body === 'string') { - bodySz = Buffer.byteLength(body); - } else { - try { - bodySz = Buffer.byteLength(JSON.stringify(body)); - } catch (ex) { - logger.warn(ex); - } - } - metrics.IncMetrics(domain.context.srv, domain.context.subsrv, - metrics.outgoingTransactionsResponseSize, bodySz); - } - } - if (err) { - logErrorIf(err, util.format('error %s to %s', method, options.url)); - if (withMetrics && domain.context) { - metrics.IncMetrics(domain.context.srv, domain.context.subsrv, metrics.outgoingTransactionsErrors); - } - return callback(err, null); - } - respObj = {code: response.statusCode, body: body}; - logger.debug('%s to %s returns %j', method, options.url, respObj); - if (response.statusCode < 200 || response.statusCode >= 300) { - localError = new Error(util.format('error %s to %s (%s)', method, options.url, - (body && body.error) || (body && JSON.stringify(body)) || response.statusCode)); - localError.httpCode = 500; - logErrorIf(localError, domain && domain.context); - if (withMetrics && domain.context) { - metrics.IncMetrics(domain.context.srv, domain.context.subsrv, metrics.outgoingTransactionsErrors); - } - return callback(localError, respObj); + } + options.headers = headers; + if (withMetrics && options.json && domain.context) { + try { + metrics.IncMetrics( + domain.context.srv, + domain.context.subsrv, + metrics.outgoingTransactionsRequestSize, + Buffer.byteLength(JSON.stringify(options.body), 'utf-8') + ); + } catch (exception) { + logger.warn(exception); + } + } + request[method](options, function cbRequest2core(err, response, body) { + var bodySz = 0; + if (withMetrics && domain.context) { + if (body) { + if (typeof body === 'string') { + bodySz = Buffer.byteLength(body); + } else { + try { + bodySz = Buffer.byteLength(JSON.stringify(body)); + } catch (ex) { + logger.warn(ex); + } } - logger.info('done %s to %s', method, options.url); - return callback(err, respObj); - }); + metrics.IncMetrics( + domain.context.srv, + domain.context.subsrv, + metrics.outgoingTransactionsResponseSize, + bodySz + ); + } + } + if (err) { + logErrorIf(err, util.format('error %s to %s', method, options.url)); + if (withMetrics && domain.context) { + metrics.IncMetrics( + domain.context.srv, + domain.context.subsrv, + metrics.outgoingTransactionsErrors + ); + } + return callback(err, null); + } + respObj = { code: response.statusCode, body: body }; + logger.debug('%s to %s returns %j', method, options.url, respObj); + if (response.statusCode < 200 || response.statusCode >= 300) { + localError = new Error( + util.format( + 'error %s to %s (%s)', + method, + options.url, + (body && body.error) || + (body && JSON.stringify(body)) || + response.statusCode + ) + ); + localError.httpCode = 500; + logErrorIf(localError, domain && domain.context); + if (withMetrics && domain.context) { + metrics.IncMetrics( + domain.context.srv, + domain.context.subsrv, + metrics.outgoingTransactionsErrors + ); + } + return callback(localError, respObj); + } + logger.info('done %s to %s', method, options.url); + return callback(err, respObj); + }); } function requestHelper(method, options, callback) { - return requestHelperAux(method, options, true, callback); + return requestHelperAux(method, options, true, callback); } function requestHelperWOMetrics(method, options, callback) { - return requestHelperAux(method, options, false, callback); + return requestHelperAux(method, options, false, callback); } function respondAux(resp, err, data, withCount, raw, withMetrics) { - var statusCode = 200, - errMsg = null, - respObj, respStr, - domain = process.domain; - if (err) { - errMsg = err.message; - statusCode = err.httpCode || 500; - data = null; - } - - if (raw === true) { - if (err) { - respObj = err; - delete respObj.httpCode; - } else { - respObj = data; - } + var statusCode = 200, + errMsg = null, + respObj, + respStr, + domain = process.domain; + if (err) { + errMsg = err.message; + statusCode = err.httpCode || 500; + data = null; + } + if (raw === true) { + if (err) { + respObj = err; + delete respObj.httpCode; + } else { + respObj = data; } - else { // non-raw - respObj = {error: errMsg, data: data}; - if (withCount === true && data && util.isArray(data)) { - respObj.count = data.length; - } + } else { + // non-raw + respObj = { error: errMsg, data: data }; + if (withCount === true && data && util.isArray(data)) { + respObj.count = data.length; } - logger.info('sending response: %s %j', statusCode, - respObj); - respStr = JSON.stringify(respObj); - if (withMetrics && domain && domain.context) { - metrics.IncMetrics(domain.context.srv, domain.context.subsrv, - metrics.incomingTransactionsResponseSize, Buffer.byteLength(respStr, 'utf-8')); - if (err) { - metrics.IncMetrics(domain.context.srv, domain.context.subsrv, metrics.incomingTransactionsErrors); - } + } + logger.info('sending response: %s %j', statusCode, respObj); + respStr = JSON.stringify(respObj); + if (withMetrics && domain && domain.context) { + metrics.IncMetrics( + domain.context.srv, + domain.context.subsrv, + metrics.incomingTransactionsResponseSize, + Buffer.byteLength(respStr, 'utf-8') + ); + if (err) { + metrics.IncMetrics( + domain.context.srv, + domain.context.subsrv, + metrics.incomingTransactionsErrors + ); } - resp.set('Content-Type', 'application/json'); - resp.status(statusCode); - resp.send(respStr); + } + resp.set('Content-Type', 'application/json'); + resp.status(statusCode); + resp.send(respStr); } function respond(resp, err, data, withCount, raw) { - return respondAux(resp, err, data, withCount, raw, true); + return respondAux(resp, err, data, withCount, raw, true); } function respondWOMetrics(resp, err, data, withCount, raw, withMetrics) { - return respondAux(resp, err, data, withCount, raw, false); + return respondAux(resp, err, data, withCount, raw, false); } function firstChars(result) { - var text; - if (result === undefined) { - result = 'undefined'; - } - text = JSON.stringify(result); - if (text.length > 125) { - text = text.substr(0, 125) + ' [...]'; - } - return text; + var text; + if (result === undefined) { + result = 'undefined'; + } + text = JSON.stringify(result); + if (text.length > 125) { + text = text.substr(0, 125) + ' [...]'; + } + return text; } function purgeName(name) { - return name ? name.replace(/\//g, '$') : name; + return name ? name.replace(/\//g, '$') : name; } function contextName(rule) { - return util.format('ctxt$%s%s', purgeName(rule.service), purgeName(rule.subservice)); + return util.format( + 'ctxt$%s%s', + purgeName(rule.service), + purgeName(rule.subservice) + ); } function ruleUniqueName(rule) { - return util.format('%s@%s%s', rule.name, rule.service, rule.subservice); + return util.format('%s@%s%s', rule.name, rule.service, rule.subservice); } function contextEPL(rule) { - return util.format('create context %s partition by service from iotEvent(service="%s" and subservice="%s")', - contextName(rule), rule.service, rule.subservice); + return util.format( + 'create context %s partition by service from iotEvent(service="%s" and subservice="%s")', + contextName(rule), + rule.service, + rule.subservice + ); } function ruleWithContext(rule) { - return util.format('context %s %s', contextName(rule), rule.text); + return util.format('context %s %s', contextName(rule), rule.text); } /** diff --git a/lib/perseo.js b/lib/perseo.js index 1b865903..ee784e00 100644 --- a/lib/perseo.js +++ b/lib/perseo.js @@ -24,138 +24,147 @@ 'use strict'; var domain = require('domain'), - express = require('express'), - bodyParser = require('body-parser'), - async = require('async'), - constants = require('./constants'), - appContext = require('./appContext'), - config = require('../config'), - db = require('./db'), - actionsRoutes = require('./routes/actionsController'), - rulesRoutes = require('./routes/rulesController'), - noticesRoutes = require('./routes/noticesController'), - visualRulesRoutes = require('./routes/visualRulesController'), - checkRoutes = require('./routes/checkController'), - versionRoutes = require('./routes/versionController'), - metricsRoutes = require('./routes/metricsController'), - rules = require('./models/rules'), - metrics = require('./models/metrics'), - app = express(), - server, - logger = require('logops'), - domainMiddleware = require('./middleware/domain').requestDomain(), - logRequestMiddleware = require('./middleware/logRequest'), - serviceMiddleware = require('./middleware/service'), - errorMiddleware = require('./middleware/error'), - myutils = require('./myutils'), - d = domain.create(); + express = require('express'), + bodyParser = require('body-parser'), + async = require('async'), + constants = require('./constants'), + appContext = require('./appContext'), + config = require('../config'), + db = require('./db'), + actionsRoutes = require('./routes/actionsController'), + rulesRoutes = require('./routes/rulesController'), + noticesRoutes = require('./routes/noticesController'), + visualRulesRoutes = require('./routes/visualRulesController'), + checkRoutes = require('./routes/checkController'), + versionRoutes = require('./routes/versionController'), + metricsRoutes = require('./routes/metricsController'), + rules = require('./models/rules'), + metrics = require('./models/metrics'), + app = express(), + server, + logger = require('logops'), + domainMiddleware = require('./middleware/domain').requestDomain(), + logRequestMiddleware = require('./middleware/logRequest'), + serviceMiddleware = require('./middleware/service'), + errorMiddleware = require('./middleware/error'), + myutils = require('./myutils'), + d = domain.create(); function start(callbackStart) { - var context = {op: 'start', comp: constants.COMPONENT_NAME}; + var context = { op: 'start', comp: constants.COMPONENT_NAME }; - logger.info(context, 'starting perseo'); - logger.setLevel(config.logLevel); + logger.info(context, 'starting perseo'); + logger.setLevel(config.logLevel); - logger.getContext = function getDomainContext() { - if (process.domain) { - return process.domain.context; - } - }; + logger.getContext = function getDomainContext() { + if (process.domain) { + return process.domain.context; + } + }; - d.run(function() { - app.disable('etag'); - app.use(serviceMiddleware.middleware()); - app.use(domainMiddleware); - app.use(bodyParser.json({ - verify: function(req, res, buf, encoding) { - // actions are internal, not to be included - if (req.url !== config.endpoint.actionsPath && - req.url !== config.endpoint.checkPath && - req.url !== config.endpoint.versionPath && - req.url !== config.endpoint.logPath && - req.url !== config.endpoint.metricsPath - ) { - metrics.IncMetrics(req.service, req.subservice, - metrics.incomingTransactionsRequestSize, buf.length); - } - } - })); - app.use(logRequestMiddleware.middleware()); - app.use(errorMiddleware.middleware()); + d.run(function() { + app.disable('etag'); + app.use(serviceMiddleware.middleware()); + app.use(domainMiddleware); + app.use( + bodyParser.json({ + verify: function(req, res, buf, encoding) { + // actions are internal, not to be included + if ( + req.url !== config.endpoint.actionsPath && + req.url !== config.endpoint.checkPath && + req.url !== config.endpoint.versionPath && + req.url !== config.endpoint.logPath && + req.url !== config.endpoint.metricsPath + ) { + metrics.IncMetrics( + req.service, + req.subservice, + metrics.incomingTransactionsRequestSize, + buf.length + ); + } + }, + }) + ); + app.use(logRequestMiddleware.middleware()); + app.use(errorMiddleware.middleware()); - actionsRoutes.AddTo(app); - rulesRoutes.AddTo(app); - noticesRoutes.AddTo(app); - visualRulesRoutes.AddTo(app); - checkRoutes.AddTo(app); - versionRoutes.AddTo(app); - metricsRoutes.AddTo(app); + actionsRoutes.AddTo(app); + rulesRoutes.AddTo(app); + noticesRoutes.AddTo(app); + visualRulesRoutes.AddTo(app); + checkRoutes.AddTo(app); + versionRoutes.AddTo(app); + metricsRoutes.AddTo(app); - async.series( + async.series( + [ + function(callback) { + async.waterfall( [ - function(callback) { - async.waterfall([ - db.getDb, - function(db0, cbwf) { - appContext.SetDB(db0); - cbwf(null); - } - ], callback); - }, - db.ping, - db.setUp, - function(callback) { - async.waterfall([ - db.getOrionDb, - function(dbO, cbwf) { - appContext.SetOrionDB(dbO); - cbwf(null); - } - ], callback); - }, - db.orionPing, - function(callback) { - var domain = require('domain').create(); - domain.context = {}; - domain.context.op = 'initialRefresh'; - domain.context.comp = constants.COMPONENT_NAME; - domain.context.trans = 'n/a'; - domain.context.corr = domain.context.trans; - domain.context.srv = 'n/a'; - domain.context.subsrv = 'n/a'; - domain.run(function() { - rules.Refresh(callback); - }); - }, - function(callback) { - server = app.listen(config.endpoint.port, function() { - logger.info(context, 'listening on port %d', server.address().port); - return callback(null, server); - }); - } + db.getDb, + function(db0, cbwf) { + appContext.SetDB(db0); + cbwf(null); + }, ], - function(err) { - myutils.logErrorIf(err, context); - require('./refreshCore'); // Start periodical update of rules at core - return callbackStart(err); - } - ); - }); - + callback + ); + }, + db.ping, + db.setUp, + function(callback) { + async.waterfall( + [ + db.getOrionDb, + function(dbO, cbwf) { + appContext.SetOrionDB(dbO); + cbwf(null); + }, + ], + callback + ); + }, + db.orionPing, + function(callback) { + var domain = require('domain').create(); + domain.context = {}; + domain.context.op = 'initialRefresh'; + domain.context.comp = constants.COMPONENT_NAME; + domain.context.trans = 'n/a'; + domain.context.corr = domain.context.trans; + domain.context.srv = 'n/a'; + domain.context.subsrv = 'n/a'; + domain.run(function() { + rules.Refresh(callback); + }); + }, + function(callback) { + server = app.listen(config.endpoint.port, function() { + logger.info(context, 'listening on port %d', server.address().port); + return callback(null, server); + }); + }, + ], + function(err) { + myutils.logErrorIf(err, context); + require('./refreshCore'); // Start periodical update of rules at core + return callbackStart(err); + } + ); + }); } function stop(callback) { - var context = {op: 'stop', comp: constants.COMPONENT_NAME}; - logger.info(context, 'stopping perseo'); - async.series([ - server.close.bind(server), - db.close, - db.orionClose - ], - function(err) { - myutils.logErrorIf(err); - return callback(err); - }); + var context = { op: 'stop', comp: constants.COMPONENT_NAME }; + logger.info(context, 'stopping perseo'); + async.series([server.close.bind(server), db.close, db.orionClose], function( + err + ) { + myutils.logErrorIf(err); + return callback(err); + }); } /** @@ -170,5 +179,3 @@ module.exports.start = start; * @param {function} callback function(error) */ module.exports.stop = stop; - - diff --git a/lib/refreshCore.js b/lib/refreshCore.js index 55d5db3d..d9985993 100644 --- a/lib/refreshCore.js +++ b/lib/refreshCore.js @@ -22,34 +22,48 @@ */ 'use strict'; var config = require('../config'), - constants = require('./constants'), - rules = require('./models/rules'), - logger = require('logops'), - alarm = require('./alarm'), - interval, domain, - MAX_INTERVAL = Math.pow(2, 31) - 1, - MIN_INTERVAL = 1000, - context = {op: 'refreshCore', comp: constants.COMPONENT_NAME, trans: 'n/a', corr: 'n/a', srv: 'n/a', subsrv: 'n/a'}; + constants = require('./constants'), + rules = require('./models/rules'), + logger = require('logops'), + alarm = require('./alarm'), + interval, + domain, + MAX_INTERVAL = Math.pow(2, 31) - 1, + MIN_INTERVAL = 1000, + context = { + op: 'refreshCore', + comp: constants.COMPONENT_NAME, + trans: 'n/a', + corr: 'n/a', + srv: 'n/a', + subsrv: 'n/a', + }; function refreshCore() { - rules.Refresh(function(error) { - logger.debug(error, 'refresh core', context); - if (error) { - alarm.raise(alarm.CORE); - } else { - alarm.release(alarm.CORE); - } - }); + rules.Refresh(function(error) { + logger.debug(error, 'refresh core', context); + if (error) { + alarm.raise(alarm.CORE); + } else { + alarm.release(alarm.CORE); + } + }); } if (config.perseoCore.interval >= MAX_INTERVAL) { - logger.error('Invalid value for config.perseoCore.interval, too large (%d >= %d)', - config.perseoCore.interval, MAX_INTERVAL); - process.abort(); + logger.error( + 'Invalid value for config.perseoCore.interval, too large (%d >= %d)', + config.perseoCore.interval, + MAX_INTERVAL + ); + process.abort(); } if (config.perseoCore.interval <= MIN_INTERVAL) { - logger.error('Invalid value for config.perseoCore.interval, too small (%d <= %d)', - config.perseoCore.interval, MIN_INTERVAL); - process.abort(); + logger.error( + 'Invalid value for config.perseoCore.interval, too small (%d <= %d)', + config.perseoCore.interval, + MIN_INTERVAL + ); + process.abort(); } domain = require('domain').create(); @@ -58,6 +72,4 @@ domain.context = context; interval = setInterval(refreshCore, config.perseoCore.interval); domain.add(interval); - interval.unref(); - From 54e4cff929c86786a4445509b899c75790cfc3b8 Mon Sep 17 00:00:00 2001 From: Jason Fox Date: Tue, 29 Jan 2019 09:43:10 +0100 Subject: [PATCH 03/11] Husky Update --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 041641de..0ce85a6b 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,7 @@ }, "devDependencies": { "coveralls": "~3.0.2", - "husky": "^1.1.0", + "husky": "~1.1.0", "istanbul": "~0.4.5", "jshint": "~2.9.6", "lint-staged": "^7.3.0", From 89c7b7a75397bc59ace9aafa6abaa14b47e4998b Mon Sep 17 00:00:00 2001 From: Jason Fox Date: Wed, 30 Jan 2019 13:31:10 +0100 Subject: [PATCH 04/11] Amend tab width --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 0ce85a6b..3b3b8bb8 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,7 @@ "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 --single-quote --trailing-comma es5 --write **/*.js *.js", + "prettier": "prettier --tab-width 4 --single-quote --trailing-comma es5 --write **/*.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" @@ -63,7 +63,7 @@ }, "lint-staged": { "*.js": [ - "prettier --parser flow --single-quote --trailing-comma es5 --write", + "prettier --tab-width 4 --parser flow --single-quote --trailing-comma es5 --write", "git add" ] } From ea6740b816e02785c1381ec5fe24b43afb4e01da Mon Sep 17 00:00:00 2001 From: Jason Fox Date: Wed, 30 Jan 2019 13:32:48 +0100 Subject: [PATCH 05/11] Rerun prettier across all files --- config.js | 108 +++++------ lib/alarm.js | 48 ++--- lib/appContext.js | 8 +- lib/constants.js | 12 +- lib/db.js | 211 +++++++++++---------- lib/myutils.js | 459 +++++++++++++++++++++++---------------------- lib/perseo.js | 262 +++++++++++++------------- lib/refreshCore.js | 72 +++---- 8 files changed, 599 insertions(+), 581 deletions(-) diff --git a/config.js b/config.js index 0c678025..569d2cb2 100644 --- a/config.js +++ b/config.js @@ -35,16 +35,16 @@ config.logLevel = 'INFO'; * Configures the exposed API. */ config.endpoint = { - host: 'localhost', - port: 9090, - rulesPath: '/rules', - actionsPath: '/actions/do', - noticesPath: '/notices', - vrPath: '/m2m/vrules', - checkPath: '/check', - versionPath: '/version', - logPath: '/admin/log', - metricsPath: '/admin/metrics', + host: 'localhost', + port: 9090, + rulesPath: '/rules', + actionsPath: '/actions/do', + noticesPath: '/notices', + vrPath: '/m2m/vrules', + checkPath: '/check', + versionPath: '/version', + logPath: '/admin/log', + metricsPath: '/admin/metrics', }; /** @@ -61,20 +61,20 @@ config.slaveDelay = 500; * DB Configuration. */ config.mongo = { - // The URI to use for the database connection. It supports replica set URIs. - // mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]] - // I.e.: 'mongodb://user:pass@host1:27017,host2:27018,host3:27019/cep?replicaSet=myrep' - url: 'mongodb://localhost:27017/cep', + // The URI to use for the database connection. It supports replica set URIs. + // mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]] + // I.e.: 'mongodb://user:pass@host1:27017,host2:27018,host3:27019/cep?replicaSet=myrep' + url: 'mongodb://localhost:27017/cep', }; /** * OrionDB Configuration. */ config.orionDb = { - url: 'mongodb://localhost:27017/orion', - collection: 'entities', - prefix: 'orion', - batchSize: 500, + url: 'mongodb://localhost:27017/orion', + collection: 'entities', + prefix: 'orion', + batchSize: 500, }; /** @@ -84,18 +84,18 @@ config.orionDb = { * at core. Each <> ms, the rules are sent to core. */ config.perseoCore = { - rulesURL: 'http://localhost:8080/perseo-core/rules', - noticesURL: 'http://localhost:8080/perseo-core/events', - interval: 60e3 * 5, + rulesURL: 'http://localhost:8080/perseo-core/rules', + noticesURL: 'http://localhost:8080/perseo-core/events', + interval: 60e3 * 5, }; /** * NEXT EPL core options (with HA) */ config.nextCore = { - // - // Note this parameter is empty, so Perseo will not use HA by default - // - /* + // + // Note this parameter is empty, so Perseo will not use HA by default + // + /* rulesURL : 'http://next-core:8080/perseo-core/rules', noticesURL : 'http://next-core:8080/perseo-core/events' */ @@ -105,59 +105,59 @@ config.nextCore = { * SMTP endpoint options */ config.smtp = { - port: 25, - host: 'smtpserver', - secure: false, - /* + port: 25, + host: 'smtpserver', + secure: false, + /* , auth: { user: 'abc', pass: 'xyz' } */ - tls: { - // keep rejectUnauthorized to false when secure is also false - rejectUnauthorized: false, - }, + tls: { + // keep rejectUnauthorized to false when secure is also false + rejectUnauthorized: false, + }, }; /** * SMS endpoint options */ config.sms = { - URL: 'http://sms-endpoint/smsoutbound', - API_KEY: '', - API_SECRET: '', - from: 'tel:22012;phone-context=+34', + URL: 'http://sms-endpoint/smsoutbound', + API_KEY: '', + API_SECRET: '', + from: 'tel:22012;phone-context=+34', }; /** * SMPP endpoint options */ config.smpp = { - host: '', - port: '', - systemid: '', - password: '', - from: '346666666', - enabled: false, + host: '', + port: '', + systemid: '', + password: '', + from: '346666666', + enabled: false, }; /** * Orion (Context Broker) endpoint options */ config.orion = { - URL: 'http://orion-endpoint:1026/NGSI10/updateContext', + URL: 'http://orion-endpoint:1026/NGSI10/updateContext', }; /** * Authorization endpoint */ config.authentication = { - host: 'keystone', - port: '5001', - user: 'user', - password: 'password', + host: 'keystone', + port: '5001', + user: 'user', + password: 'password', }; /** @@ -165,8 +165,8 @@ config.authentication = { * @type {{}} */ config.collections = { - rules: 'rules', - executions: 'executions', + rules: 'rules', + executions: 'executions', }; /** @@ -197,10 +197,10 @@ config.DEFAULT_SERVICE = 'unknownt'; * @type {Number} */ config.checkDB = { - delay: 5e3, - reconnectTries: 1e3, - reconnectInterval: 5e3, - bufferMaxEntries: 5, + delay: 5e3, + reconnectTries: 1e3, + reconnectInterval: 5e3, + bufferMaxEntries: 5, }; /** diff --git a/lib/alarm.js b/lib/alarm.js index eceb3eb5..a9fe7f09 100644 --- a/lib/alarm.js +++ b/lib/alarm.js @@ -24,34 +24,34 @@ 'use strict'; var util = require('util'), - logger = require('logops'), - alarms = {}; + logger = require('logops'), + alarms = {}; function raise(alarm, context, message) { - var state = alarms[alarm]; - context = (process.domain && process.domain.context) || {}; - if (typeof message === 'object' && message) { - message = util.format('%j', message); - } - message = message || ''; - if (state !== true) { - // emit ERROR alarm ON - logger.error(context, 'ALARM-ON [' + alarm + '] ' + message); - } - alarms[alarm] = true; + var state = alarms[alarm]; + context = (process.domain && process.domain.context) || {}; + if (typeof message === 'object' && message) { + message = util.format('%j', message); + } + message = message || ''; + if (state !== true) { + // emit ERROR alarm ON + logger.error(context, 'ALARM-ON [' + alarm + '] ' + message); + } + alarms[alarm] = true; } function release(alarm, context, message) { - var state = alarms[alarm]; - context = (process.domain && process.domain.context) || {}; - if (typeof message === 'object' && message) { - message = util.format('%j', message); - } - message = message || ''; - if (state === true) { - // emit ERROR alarm OFF - logger.error(context, 'ALARM-OFF [' + alarm + '] ' + message); - } - alarms[alarm] = false; + var state = alarms[alarm]; + context = (process.domain && process.domain.context) || {}; + if (typeof message === 'object' && message) { + message = util.format('%j', message); + } + message = message || ''; + if (state === true) { + // emit ERROR alarm OFF + logger.error(context, 'ALARM-OFF [' + alarm + '] ' + message); + } + alarms[alarm] = false; } module.exports.raise = raise; diff --git a/lib/appContext.js b/lib/appContext.js index bb42196b..357cc11d 100644 --- a/lib/appContext.js +++ b/lib/appContext.js @@ -25,18 +25,18 @@ var database, orionDatabase; function SetDB(db) { - database = db; + database = db; } function DB() { - return database; + return database; } function SetOrionDB(db) { - orionDatabase = db; + orionDatabase = db; } function OrionDB(database) { - return orionDatabase.db(database); + return orionDatabase.db(database); } /** diff --git a/lib/constants.js b/lib/constants.js index 01c48d26..cbae47ba 100644 --- a/lib/constants.js +++ b/lib/constants.js @@ -27,10 +27,10 @@ * */ module.exports = { - SUBSERVICE_HEADER: 'fiware-servicepath', - SERVICE_HEADER: 'fiware-service', - CORRELATOR_HEADER: 'fiware-correlator', - AUTH_HEADER: 'X-Auth-Token', - REALIP_HEADER: 'X-Real-IP', - COMPONENT_NAME: 'perseo-fe', + SUBSERVICE_HEADER: 'fiware-servicepath', + SERVICE_HEADER: 'fiware-service', + CORRELATOR_HEADER: 'fiware-correlator', + AUTH_HEADER: 'X-Auth-Token', + REALIP_HEADER: 'X-Real-IP', + COMPONENT_NAME: 'perseo-fe', }; diff --git a/lib/db.js b/lib/db.js index e3093d3a..54e65814 100644 --- a/lib/db.js +++ b/lib/db.js @@ -22,129 +22,134 @@ */ 'use strict'; var async = require('async'), - logger = require('logops'), - config = require('../config'), - rulesCollection = require('../config').collections.rules, - executionsCollection = require('../config').collections.executions, - myutils = require('./myutils'), - constants = require('./constants'), - alarm = require('./alarm'), - database, - orionDb, - delay = config.checkDB.delay, - context = { comp: constants.COMPONENT_NAME, op: 'checkDB' }; + logger = require('logops'), + config = require('../config'), + rulesCollection = require('../config').collections.rules, + executionsCollection = require('../config').collections.executions, + myutils = require('./myutils'), + constants = require('./constants'), + alarm = require('./alarm'), + database, + orionDb, + delay = config.checkDB.delay, + context = { comp: constants.COMPONENT_NAME, op: 'checkDB' }; function pingAux(db, component, callback) { - db.command({ ping: 1 }, function(err, result) { - if (err) { - alarm.raise(component, context, err.message); - } else { - alarm.release(component, context, result); - } - return callback(err, result); - }); + db.command({ ping: 1 }, function(err, result) { + if (err) { + alarm.raise(component, context, err.message); + } else { + alarm.release(component, context, result); + } + return callback(err, result); + }); } function getDbAux(url, component, callback) { - var client = require('mongodb').MongoClient, - checkDbHealthFunc; - client.connect( - url, - { - db: { - bufferMaxEntries: config.checkDB.bufferMaxEntries, - domainsEnabled: true, - }, - server: { - reconnectTries: config.checkDB.reconnectTries, - reconnectInterval: config.checkDB.reconnectInterval, - domainsEnabled: true, - }, - }, - function(err, db) { - if (err) { - myutils.logErrorIf(err, 'connect', context); - return callback(err, null); - } + var client = require('mongodb').MongoClient, + checkDbHealthFunc; + client.connect( + url, + { + db: { + bufferMaxEntries: config.checkDB.bufferMaxEntries, + domainsEnabled: true, + }, + server: { + reconnectTries: config.checkDB.reconnectTries, + reconnectInterval: config.checkDB.reconnectInterval, + domainsEnabled: true, + }, + }, + function(err, db) { + if (err) { + myutils.logErrorIf(err, 'connect', context); + return callback(err, null); + } - // This event is emitted only by Server topology (standalone) - // The driver has given up getting a connection, so we will die (restart perseo usually) - // and re-try from scratch. - // The ReplSet does not emit 'reconnectFailed' - db.serverConfig.on('reconnectFailed', function() { - logger.fatal('too many tries to reconnect to database, dying ...'); - process.exit(-2); - }); + // This event is emitted only by Server topology (standalone) + // The driver has given up getting a connection, so we will die (restart perseo usually) + // and re-try from scratch. + // The ReplSet does not emit 'reconnectFailed' + db.serverConfig.on('reconnectFailed', function() { + logger.fatal( + 'too many tries to reconnect to database, dying ...' + ); + process.exit(-2); + }); - checkDbHealthFunc = function checkDbHealth() { - pingAux(db, component, function(err, result) { - logger.debug('ping (%s) %j', component, err || result); - }); - }; - setInterval(checkDbHealthFunc, delay); - return callback(null, db); - } - ); + checkDbHealthFunc = function checkDbHealth() { + pingAux(db, component, function(err, result) { + logger.debug('ping (%s) %j', component, err || result); + }); + }; + setInterval(checkDbHealthFunc, delay); + return callback(null, db); + } + ); } function getDb(callback) { - getDbAux(config.mongo.url, alarm.DATABASE, function cb(err, db) { - database = db; - callback(err, db); - }); + getDbAux(config.mongo.url, alarm.DATABASE, function cb(err, db) { + database = db; + callback(err, db); + }); } function getOrionDb(callback) { - getDbAux(config.orionDb.url, alarm.DATABASE_ORION, function cb(err, db) { - orionDb = db; - callback(err, db); - }); + getDbAux(config.orionDb.url, alarm.DATABASE_ORION, function cb(err, db) { + orionDb = db; + callback(err, db); + }); } function ensureIndex(collection, fields, callback) { - database.collection(collection, function(err, collection) { - myutils.logErrorIf(err, collection, context); - collection.ensureIndex(fields, { unique: true }, function(err, indexName) { - myutils.logErrorIf(err, 'ensureIndex ' + collection, context); - callback(err, indexName); + database.collection(collection, function(err, collection) { + myutils.logErrorIf(err, collection, context); + collection.ensureIndex(fields, { unique: true }, function( + err, + indexName + ) { + myutils.logErrorIf(err, 'ensureIndex ' + collection, context); + callback(err, indexName); + }); }); - }); } function ensureIndexTTL(collection, fields, ttl, callback) { - database.collection(collection, function(err, collection) { - myutils.logErrorIf(err, collection); - collection.ensureIndex(fields, { expireAfterSeconds: ttl }, function( - err, - indexName - ) { - myutils.logErrorIf(err, 'ensureIndex ' + collection, context); - callback(err, indexName); + database.collection(collection, function(err, collection) { + myutils.logErrorIf(err, collection); + collection.ensureIndex(fields, { expireAfterSeconds: ttl }, function( + err, + indexName + ) { + myutils.logErrorIf(err, 'ensureIndex ' + collection, context); + callback(err, indexName); + }); }); - }); } function setUp(cbSU) { - async.parallel( - [ - ensureIndex.bind(null, rulesCollection, { - name: 1, - subservice: 1, - service: 1, - }), - ensureIndexTTL.bind( - null, - executionsCollection, - { lastTime: 1 }, - config.executionsTTL - ), - ], - cbSU - ); + async.parallel( + [ + ensureIndex.bind(null, rulesCollection, { + name: 1, + subservice: 1, + service: 1, + }), + ensureIndexTTL.bind( + null, + executionsCollection, + { lastTime: 1 }, + config.executionsTTL + ), + ], + cbSU + ); } function closeAux(db, callback) { - db.close(function(err) { - myutils.logErrorIf(err, 'close', context); - callback(err); - }); + db.close(function(err) { + myutils.logErrorIf(err, 'close', context); + callback(err); + }); } /** @@ -166,7 +171,7 @@ module.exports.getOrionDb = getOrionDb; * @param {function} callback function(error, commandResult) */ module.exports.ping = function(callback) { - pingAux(database, alarm.DATABASE, callback); + pingAux(database, alarm.DATABASE, callback); }; /** @@ -175,7 +180,7 @@ module.exports.ping = function(callback) { * @param {function} callback function(error, commandResult) */ module.exports.orionPing = function(callback) { - pingAux(orionDb, alarm.DATABASE_ORION, callback); + pingAux(orionDb, alarm.DATABASE_ORION, callback); }; /** @@ -193,7 +198,7 @@ module.exports.setUp = setUp; * @param {function} callback function(error) */ module.exports.close = function(callback) { - closeAux(database, callback); + closeAux(database, callback); }; /** @@ -203,5 +208,5 @@ module.exports.close = function(callback) { * @param {function} callback function(error) */ module.exports.orionClose = function(callback) { - closeAux(orionDb, callback); + closeAux(orionDb, callback); }; diff --git a/lib/myutils.js b/lib/myutils.js index 1694b2b6..3a1766e2 100644 --- a/lib/myutils.js +++ b/lib/myutils.js @@ -24,290 +24,299 @@ 'use strict'; var request = require('request'), - util = require('util'), - logger = require('logops'), - constants = require('./constants'), - metrics = require('./models/metrics'); + util = require('util'), + logger = require('logops'), + constants = require('./constants'), + metrics = require('./models/metrics'); function logErrorIf(err, message, context) { - var level = 'error'; - if (context === undefined) { - context = process.domain && process.domain.context; - } - if (err) { - message = message || ''; - if (context) { - context.op = - context.op || - new Error().stack - .split('\n')[2] - .trim() - .substr(3); - context.comp = context.comp || constants.COMPONENT_NAME; - logger[level](context, message, err.message || JSON.stringify(err)); - } else { - logger[level](message, err.message || JSON.stringify(err)); + var level = 'error'; + if (context === undefined) { + context = process.domain && process.domain.context; + } + if (err) { + message = message || ''; + if (context) { + context.op = + context.op || + new Error().stack + .split('\n')[2] + .trim() + .substr(3); + context.comp = context.comp || constants.COMPONENT_NAME; + logger[level](context, message, err.message || JSON.stringify(err)); + } else { + logger[level](message, err.message || JSON.stringify(err)); + } } - } } function expandVar(val, mapping) { - if (typeof val === 'string') { - Object.keys(mapping).forEach(function(p) { - val = val.replace(new RegExp('\\$\\{' + p + '\\}', 'g'), mapping[p]); - }); - val = val.replace(/\$\{\w*\}/g, '[?]'); - } - return val; + if (typeof val === 'string') { + Object.keys(mapping).forEach(function(p) { + val = val.replace( + new RegExp('\\$\\{' + p + '\\}', 'g'), + mapping[p] + ); + }); + val = val.replace(/\$\{\w*\}/g, '[?]'); + } + return val; } function expandObject(templateObj, dictionary) { - var res = {}; - if (templateObj && typeof templateObj === 'object') { - Object.keys(templateObj).forEach(function(key) { - if (typeof templateObj[key] === 'string') { - res[expandVar(key, dictionary)] = expandVar( - templateObj[key], - dictionary - ); - } else if (typeof templateObj[key] === 'object') { - res[expandVar(key, dictionary)] = expandObject( - templateObj[key], - dictionary - ); - } - }); - } - return res; + var res = {}; + if (templateObj && typeof templateObj === 'object') { + Object.keys(templateObj).forEach(function(key) { + if (typeof templateObj[key] === 'string') { + res[expandVar(key, dictionary)] = expandVar( + templateObj[key], + dictionary + ); + } else if (typeof templateObj[key] === 'object') { + res[expandVar(key, dictionary)] = expandObject( + templateObj[key], + dictionary + ); + } + }); + } + return res; } // Think better if this is the best way function flattenMap(key, targetMap) { - var newMap = {}, - v, - flattened, - fv; - Object.keys(targetMap).forEach(function(k) { - v = targetMap[k]; - if (v && typeof v === 'object') { - flattened = flattenMap(k + '__', v); - Object.keys(flattened).forEach(function(fk) { - fv = flattened[fk]; - newMap[key + fk] = fv; - }); - } else { - newMap[key + k] = v; - } - }); - return newMap; + var newMap = {}, + v, + flattened, + fv; + Object.keys(targetMap).forEach(function(k) { + v = targetMap[k]; + if (v && typeof v === 'object') { + flattened = flattenMap(k + '__', v); + Object.keys(flattened).forEach(function(fk) { + fv = flattened[fk]; + newMap[key + fk] = fv; + }); + } else { + newMap[key + k] = v; + } + }); + return newMap; } function requestHelperAux(method, options, withMetrics, callback) { - var localError, - respObj, - headers, - domain = process.domain; - logger.info('making %s to %s', method, options.url); - if (withMetrics && domain.context) { - metrics.IncMetrics( - domain.context.srv, - domain.context.subsrv, - metrics.outgoingTransactions - ); - } - headers = options.headers || {}; - if (domain && domain.context) { - headers[constants.CORRELATOR_HEADER] = domain.context.corr; - if (domain.context.srv && headers[constants.SERVICE_HEADER] === undefined) { - headers[constants.SERVICE_HEADER] = domain.context.srv; - } - if ( - domain.context.subsrv && - headers[constants.SUBSERVICE_HEADER] === undefined - ) { - headers[constants.SUBSERVICE_HEADER] = domain.context.subsrv; - } - if (domain.context.from && headers[constants.REALIP_HEADER] === undefined) { - headers[constants.REALIP_HEADER] = domain.context.from; - } - } - options.headers = headers; - if (withMetrics && options.json && domain.context) { - try { - metrics.IncMetrics( - domain.context.srv, - domain.context.subsrv, - metrics.outgoingTransactionsRequestSize, - Buffer.byteLength(JSON.stringify(options.body), 'utf-8') - ); - } catch (exception) { - logger.warn(exception); - } - } - request[method](options, function cbRequest2core(err, response, body) { - var bodySz = 0; + var localError, + respObj, + headers, + domain = process.domain; + logger.info('making %s to %s', method, options.url); if (withMetrics && domain.context) { - if (body) { - if (typeof body === 'string') { - bodySz = Buffer.byteLength(body); - } else { - try { - bodySz = Buffer.byteLength(JSON.stringify(body)); - } catch (ex) { - logger.warn(ex); - } - } metrics.IncMetrics( - domain.context.srv, - domain.context.subsrv, - metrics.outgoingTransactionsResponseSize, - bodySz + domain.context.srv, + domain.context.subsrv, + metrics.outgoingTransactions ); - } } - if (err) { - logErrorIf(err, util.format('error %s to %s', method, options.url)); - if (withMetrics && domain.context) { - metrics.IncMetrics( - domain.context.srv, - domain.context.subsrv, - metrics.outgoingTransactionsErrors - ); - } - return callback(err, null); + headers = options.headers || {}; + if (domain && domain.context) { + headers[constants.CORRELATOR_HEADER] = domain.context.corr; + if ( + domain.context.srv && + headers[constants.SERVICE_HEADER] === undefined + ) { + headers[constants.SERVICE_HEADER] = domain.context.srv; + } + if ( + domain.context.subsrv && + headers[constants.SUBSERVICE_HEADER] === undefined + ) { + headers[constants.SUBSERVICE_HEADER] = domain.context.subsrv; + } + if ( + domain.context.from && + headers[constants.REALIP_HEADER] === undefined + ) { + headers[constants.REALIP_HEADER] = domain.context.from; + } } - respObj = { code: response.statusCode, body: body }; - logger.debug('%s to %s returns %j', method, options.url, respObj); - if (response.statusCode < 200 || response.statusCode >= 300) { - localError = new Error( - util.format( - 'error %s to %s (%s)', - method, - options.url, - (body && body.error) || - (body && JSON.stringify(body)) || - response.statusCode - ) - ); - localError.httpCode = 500; - logErrorIf(localError, domain && domain.context); - if (withMetrics && domain.context) { - metrics.IncMetrics( - domain.context.srv, - domain.context.subsrv, - metrics.outgoingTransactionsErrors - ); - } - return callback(localError, respObj); + options.headers = headers; + if (withMetrics && options.json && domain.context) { + try { + metrics.IncMetrics( + domain.context.srv, + domain.context.subsrv, + metrics.outgoingTransactionsRequestSize, + Buffer.byteLength(JSON.stringify(options.body), 'utf-8') + ); + } catch (exception) { + logger.warn(exception); + } } - logger.info('done %s to %s', method, options.url); - return callback(err, respObj); - }); + request[method](options, function cbRequest2core(err, response, body) { + var bodySz = 0; + if (withMetrics && domain.context) { + if (body) { + if (typeof body === 'string') { + bodySz = Buffer.byteLength(body); + } else { + try { + bodySz = Buffer.byteLength(JSON.stringify(body)); + } catch (ex) { + logger.warn(ex); + } + } + metrics.IncMetrics( + domain.context.srv, + domain.context.subsrv, + metrics.outgoingTransactionsResponseSize, + bodySz + ); + } + } + if (err) { + logErrorIf(err, util.format('error %s to %s', method, options.url)); + if (withMetrics && domain.context) { + metrics.IncMetrics( + domain.context.srv, + domain.context.subsrv, + metrics.outgoingTransactionsErrors + ); + } + return callback(err, null); + } + respObj = { code: response.statusCode, body: body }; + logger.debug('%s to %s returns %j', method, options.url, respObj); + if (response.statusCode < 200 || response.statusCode >= 300) { + localError = new Error( + util.format( + 'error %s to %s (%s)', + method, + options.url, + (body && body.error) || + (body && JSON.stringify(body)) || + response.statusCode + ) + ); + localError.httpCode = 500; + logErrorIf(localError, domain && domain.context); + if (withMetrics && domain.context) { + metrics.IncMetrics( + domain.context.srv, + domain.context.subsrv, + metrics.outgoingTransactionsErrors + ); + } + return callback(localError, respObj); + } + logger.info('done %s to %s', method, options.url); + return callback(err, respObj); + }); } function requestHelper(method, options, callback) { - return requestHelperAux(method, options, true, callback); + return requestHelperAux(method, options, true, callback); } function requestHelperWOMetrics(method, options, callback) { - return requestHelperAux(method, options, false, callback); + return requestHelperAux(method, options, false, callback); } function respondAux(resp, err, data, withCount, raw, withMetrics) { - var statusCode = 200, - errMsg = null, - respObj, - respStr, - domain = process.domain; - if (err) { - errMsg = err.message; - statusCode = err.httpCode || 500; - data = null; - } - - if (raw === true) { + var statusCode = 200, + errMsg = null, + respObj, + respStr, + domain = process.domain; if (err) { - respObj = err; - delete respObj.httpCode; - } else { - respObj = data; + errMsg = err.message; + statusCode = err.httpCode || 500; + data = null; } - } else { - // non-raw - respObj = { error: errMsg, data: data }; - if (withCount === true && data && util.isArray(data)) { - respObj.count = data.length; + + if (raw === true) { + if (err) { + respObj = err; + delete respObj.httpCode; + } else { + respObj = data; + } + } else { + // non-raw + respObj = { error: errMsg, data: data }; + if (withCount === true && data && util.isArray(data)) { + respObj.count = data.length; + } } - } - logger.info('sending response: %s %j', statusCode, respObj); - respStr = JSON.stringify(respObj); - if (withMetrics && domain && domain.context) { - metrics.IncMetrics( - domain.context.srv, - domain.context.subsrv, - metrics.incomingTransactionsResponseSize, - Buffer.byteLength(respStr, 'utf-8') - ); - if (err) { - metrics.IncMetrics( - domain.context.srv, - domain.context.subsrv, - metrics.incomingTransactionsErrors - ); + logger.info('sending response: %s %j', statusCode, respObj); + respStr = JSON.stringify(respObj); + if (withMetrics && domain && domain.context) { + metrics.IncMetrics( + domain.context.srv, + domain.context.subsrv, + metrics.incomingTransactionsResponseSize, + Buffer.byteLength(respStr, 'utf-8') + ); + if (err) { + metrics.IncMetrics( + domain.context.srv, + domain.context.subsrv, + metrics.incomingTransactionsErrors + ); + } } - } - resp.set('Content-Type', 'application/json'); - resp.status(statusCode); - resp.send(respStr); + resp.set('Content-Type', 'application/json'); + resp.status(statusCode); + resp.send(respStr); } function respond(resp, err, data, withCount, raw) { - return respondAux(resp, err, data, withCount, raw, true); + return respondAux(resp, err, data, withCount, raw, true); } function respondWOMetrics(resp, err, data, withCount, raw, withMetrics) { - return respondAux(resp, err, data, withCount, raw, false); + return respondAux(resp, err, data, withCount, raw, false); } function firstChars(result) { - var text; - if (result === undefined) { - result = 'undefined'; - } - text = JSON.stringify(result); - if (text.length > 125) { - text = text.substr(0, 125) + ' [...]'; - } - return text; + var text; + if (result === undefined) { + result = 'undefined'; + } + text = JSON.stringify(result); + if (text.length > 125) { + text = text.substr(0, 125) + ' [...]'; + } + return text; } function purgeName(name) { - return name ? name.replace(/\//g, '$') : name; + return name ? name.replace(/\//g, '$') : name; } function contextName(rule) { - return util.format( - 'ctxt$%s%s', - purgeName(rule.service), - purgeName(rule.subservice) - ); + return util.format( + 'ctxt$%s%s', + purgeName(rule.service), + purgeName(rule.subservice) + ); } function ruleUniqueName(rule) { - return util.format('%s@%s%s', rule.name, rule.service, rule.subservice); + return util.format('%s@%s%s', rule.name, rule.service, rule.subservice); } function contextEPL(rule) { - return util.format( - 'create context %s partition by service from iotEvent(service="%s" and subservice="%s")', - contextName(rule), - rule.service, - rule.subservice - ); + return util.format( + 'create context %s partition by service from iotEvent(service="%s" and subservice="%s")', + contextName(rule), + rule.service, + rule.subservice + ); } function ruleWithContext(rule) { - return util.format('context %s %s', contextName(rule), rule.text); + return util.format('context %s %s', contextName(rule), rule.text); } /** diff --git a/lib/perseo.js b/lib/perseo.js index ee784e00..2bfadc3c 100644 --- a/lib/perseo.js +++ b/lib/perseo.js @@ -24,147 +24,151 @@ 'use strict'; var domain = require('domain'), - express = require('express'), - bodyParser = require('body-parser'), - async = require('async'), - constants = require('./constants'), - appContext = require('./appContext'), - config = require('../config'), - db = require('./db'), - actionsRoutes = require('./routes/actionsController'), - rulesRoutes = require('./routes/rulesController'), - noticesRoutes = require('./routes/noticesController'), - visualRulesRoutes = require('./routes/visualRulesController'), - checkRoutes = require('./routes/checkController'), - versionRoutes = require('./routes/versionController'), - metricsRoutes = require('./routes/metricsController'), - rules = require('./models/rules'), - metrics = require('./models/metrics'), - app = express(), - server, - logger = require('logops'), - domainMiddleware = require('./middleware/domain').requestDomain(), - logRequestMiddleware = require('./middleware/logRequest'), - serviceMiddleware = require('./middleware/service'), - errorMiddleware = require('./middleware/error'), - myutils = require('./myutils'), - d = domain.create(); + express = require('express'), + bodyParser = require('body-parser'), + async = require('async'), + constants = require('./constants'), + appContext = require('./appContext'), + config = require('../config'), + db = require('./db'), + actionsRoutes = require('./routes/actionsController'), + rulesRoutes = require('./routes/rulesController'), + noticesRoutes = require('./routes/noticesController'), + visualRulesRoutes = require('./routes/visualRulesController'), + checkRoutes = require('./routes/checkController'), + versionRoutes = require('./routes/versionController'), + metricsRoutes = require('./routes/metricsController'), + rules = require('./models/rules'), + metrics = require('./models/metrics'), + app = express(), + server, + logger = require('logops'), + domainMiddleware = require('./middleware/domain').requestDomain(), + logRequestMiddleware = require('./middleware/logRequest'), + serviceMiddleware = require('./middleware/service'), + errorMiddleware = require('./middleware/error'), + myutils = require('./myutils'), + d = domain.create(); function start(callbackStart) { - var context = { op: 'start', comp: constants.COMPONENT_NAME }; + var context = { op: 'start', comp: constants.COMPONENT_NAME }; - logger.info(context, 'starting perseo'); - logger.setLevel(config.logLevel); + logger.info(context, 'starting perseo'); + logger.setLevel(config.logLevel); - logger.getContext = function getDomainContext() { - if (process.domain) { - return process.domain.context; - } - }; + logger.getContext = function getDomainContext() { + if (process.domain) { + return process.domain.context; + } + }; - d.run(function() { - app.disable('etag'); - app.use(serviceMiddleware.middleware()); - app.use(domainMiddleware); - app.use( - bodyParser.json({ - verify: function(req, res, buf, encoding) { - // actions are internal, not to be included - if ( - req.url !== config.endpoint.actionsPath && - req.url !== config.endpoint.checkPath && - req.url !== config.endpoint.versionPath && - req.url !== config.endpoint.logPath && - req.url !== config.endpoint.metricsPath - ) { - metrics.IncMetrics( - req.service, - req.subservice, - metrics.incomingTransactionsRequestSize, - buf.length - ); - } - }, - }) - ); - app.use(logRequestMiddleware.middleware()); - app.use(errorMiddleware.middleware()); + d.run(function() { + app.disable('etag'); + app.use(serviceMiddleware.middleware()); + app.use(domainMiddleware); + app.use( + bodyParser.json({ + verify: function(req, res, buf, encoding) { + // actions are internal, not to be included + if ( + req.url !== config.endpoint.actionsPath && + req.url !== config.endpoint.checkPath && + req.url !== config.endpoint.versionPath && + req.url !== config.endpoint.logPath && + req.url !== config.endpoint.metricsPath + ) { + metrics.IncMetrics( + req.service, + req.subservice, + metrics.incomingTransactionsRequestSize, + buf.length + ); + } + }, + }) + ); + app.use(logRequestMiddleware.middleware()); + app.use(errorMiddleware.middleware()); - actionsRoutes.AddTo(app); - rulesRoutes.AddTo(app); - noticesRoutes.AddTo(app); - visualRulesRoutes.AddTo(app); - checkRoutes.AddTo(app); - versionRoutes.AddTo(app); - metricsRoutes.AddTo(app); + actionsRoutes.AddTo(app); + rulesRoutes.AddTo(app); + noticesRoutes.AddTo(app); + visualRulesRoutes.AddTo(app); + checkRoutes.AddTo(app); + versionRoutes.AddTo(app); + metricsRoutes.AddTo(app); - async.series( - [ - function(callback) { - async.waterfall( + async.series( [ - db.getDb, - function(db0, cbwf) { - appContext.SetDB(db0); - cbwf(null); - }, + function(callback) { + async.waterfall( + [ + db.getDb, + function(db0, cbwf) { + appContext.SetDB(db0); + cbwf(null); + }, + ], + callback + ); + }, + db.ping, + db.setUp, + function(callback) { + async.waterfall( + [ + db.getOrionDb, + function(dbO, cbwf) { + appContext.SetOrionDB(dbO); + cbwf(null); + }, + ], + callback + ); + }, + db.orionPing, + function(callback) { + var domain = require('domain').create(); + domain.context = {}; + domain.context.op = 'initialRefresh'; + domain.context.comp = constants.COMPONENT_NAME; + domain.context.trans = 'n/a'; + domain.context.corr = domain.context.trans; + domain.context.srv = 'n/a'; + domain.context.subsrv = 'n/a'; + domain.run(function() { + rules.Refresh(callback); + }); + }, + function(callback) { + server = app.listen(config.endpoint.port, function() { + logger.info( + context, + 'listening on port %d', + server.address().port + ); + return callback(null, server); + }); + }, ], - callback - ); - }, - db.ping, - db.setUp, - function(callback) { - async.waterfall( - [ - db.getOrionDb, - function(dbO, cbwf) { - appContext.SetOrionDB(dbO); - cbwf(null); - }, - ], - callback - ); - }, - db.orionPing, - function(callback) { - var domain = require('domain').create(); - domain.context = {}; - domain.context.op = 'initialRefresh'; - domain.context.comp = constants.COMPONENT_NAME; - domain.context.trans = 'n/a'; - domain.context.corr = domain.context.trans; - domain.context.srv = 'n/a'; - domain.context.subsrv = 'n/a'; - domain.run(function() { - rules.Refresh(callback); - }); - }, - function(callback) { - server = app.listen(config.endpoint.port, function() { - logger.info(context, 'listening on port %d', server.address().port); - return callback(null, server); - }); - }, - ], - function(err) { - myutils.logErrorIf(err, context); - require('./refreshCore'); // Start periodical update of rules at core - return callbackStart(err); - } - ); - }); + function(err) { + myutils.logErrorIf(err, context); + require('./refreshCore'); // Start periodical update of rules at core + return callbackStart(err); + } + ); + }); } function stop(callback) { - var context = { op: 'stop', comp: constants.COMPONENT_NAME }; - logger.info(context, 'stopping perseo'); - async.series([server.close.bind(server), db.close, db.orionClose], function( - err - ) { - myutils.logErrorIf(err); - return callback(err); - }); + var context = { op: 'stop', comp: constants.COMPONENT_NAME }; + logger.info(context, 'stopping perseo'); + async.series([server.close.bind(server), db.close, db.orionClose], function( + err + ) { + myutils.logErrorIf(err); + return callback(err); + }); } /** diff --git a/lib/refreshCore.js b/lib/refreshCore.js index d9985993..167bc5e8 100644 --- a/lib/refreshCore.js +++ b/lib/refreshCore.js @@ -22,48 +22,48 @@ */ 'use strict'; var config = require('../config'), - constants = require('./constants'), - rules = require('./models/rules'), - logger = require('logops'), - alarm = require('./alarm'), - interval, - domain, - MAX_INTERVAL = Math.pow(2, 31) - 1, - MIN_INTERVAL = 1000, - context = { - op: 'refreshCore', - comp: constants.COMPONENT_NAME, - trans: 'n/a', - corr: 'n/a', - srv: 'n/a', - subsrv: 'n/a', - }; + constants = require('./constants'), + rules = require('./models/rules'), + logger = require('logops'), + alarm = require('./alarm'), + interval, + domain, + MAX_INTERVAL = Math.pow(2, 31) - 1, + MIN_INTERVAL = 1000, + context = { + op: 'refreshCore', + comp: constants.COMPONENT_NAME, + trans: 'n/a', + corr: 'n/a', + srv: 'n/a', + subsrv: 'n/a', + }; function refreshCore() { - rules.Refresh(function(error) { - logger.debug(error, 'refresh core', context); - if (error) { - alarm.raise(alarm.CORE); - } else { - alarm.release(alarm.CORE); - } - }); + rules.Refresh(function(error) { + logger.debug(error, 'refresh core', context); + if (error) { + alarm.raise(alarm.CORE); + } else { + alarm.release(alarm.CORE); + } + }); } if (config.perseoCore.interval >= MAX_INTERVAL) { - logger.error( - 'Invalid value for config.perseoCore.interval, too large (%d >= %d)', - config.perseoCore.interval, - MAX_INTERVAL - ); - process.abort(); + logger.error( + 'Invalid value for config.perseoCore.interval, too large (%d >= %d)', + config.perseoCore.interval, + MAX_INTERVAL + ); + process.abort(); } if (config.perseoCore.interval <= MIN_INTERVAL) { - logger.error( - 'Invalid value for config.perseoCore.interval, too small (%d <= %d)', - config.perseoCore.interval, - MIN_INTERVAL - ); - process.abort(); + logger.error( + 'Invalid value for config.perseoCore.interval, too small (%d <= %d)', + config.perseoCore.interval, + MIN_INTERVAL + ); + process.abort(); } domain = require('domain').create(); From 20603670c69eef73cde2649765f0936779fa4927 Mon Sep 17 00:00:00 2001 From: Jason Fox Date: Wed, 30 Jan 2019 13:48:41 +0100 Subject: [PATCH 06/11] Replace ^ with ~ in dependencies --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 3b3b8bb8..986b7569 100644 --- a/package.json +++ b/package.json @@ -34,10 +34,10 @@ "husky": "~1.1.0", "istanbul": "~0.4.5", "jshint": "~2.9.6", - "lint-staged": "^7.3.0", + "lint-staged": "~7.3.0", "mocha": "5.2.0", "proxyquire": "0.5.1", - "prettier": "^1.14.2", + "prettier": "~1.14.2", "should": "8.2.2", "watch": "~1.0.2" }, From 3e7333f5dce2ef17a4835a05c76f5bdfe7837e8e Mon Sep 17 00:00:00 2001 From: Jason Fox Date: Thu, 31 Jan 2019 10:11:08 +0100 Subject: [PATCH 07/11] Create Prettier Config --- .prettierrc.json | 9 +++++++++ package.json | 4 ++-- 2 files changed, 11 insertions(+), 2 deletions(-) create mode 100644 .prettierrc.json diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 00000000..6bc2f8e4 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,9 @@ +{ + "arrowParens": "always", + "bracketSpacing": true, + "singleQuote": true, + "parser": "flow", + "printWidth": 120, + "trailingComma": "es5", + "tabWidth": 4 +} \ No newline at end of file diff --git a/package.json b/package.json index 986b7569..4fc4395d 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,7 @@ "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 --tab-width 4 --single-quote --trailing-comma es5 --write **/*.js *.js", + "prettier": "prettier --tab-width 4 --print-width 120 --single-quote --trailing-comma es5 --write ./**/**/*.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" @@ -63,7 +63,7 @@ }, "lint-staged": { "*.js": [ - "prettier --tab-width 4 --parser flow --single-quote --trailing-comma es5 --write", + "prettier --config .prettierrc.json --write", "git add" ] } From 26b337010167f05f85139e47255023d13437fd4f Mon Sep 17 00:00:00 2001 From: Jason Fox Date: Thu, 31 Jan 2019 10:13:42 +0100 Subject: [PATCH 08/11] Rerun prettier - 120 width --- ghpages/javascripts/scale.fix.js | 20 +- lib/db.js | 21 +- lib/middleware/domain.js | 6 +- lib/middleware/error.js | 1 - lib/middleware/logRequest.js | 11 +- lib/middleware/service.js | 34 +- lib/models/actions.js | 149 ++++--- lib/models/actionsStore.js | 8 +- lib/models/emailAction.js | 8 +- lib/models/entitiesStore.js | 54 +-- lib/models/executionsStore.js | 88 ++-- lib/models/keystone.js | 27 +- lib/models/metrics.js | 14 +- lib/models/noSignal.js | 81 ++-- lib/models/notices.js | 93 +++-- lib/models/paths.js | 15 +- lib/models/postAction.js | 13 +- lib/models/rules.js | 110 +++-- lib/models/rulesStore.js | 140 ++++--- lib/models/smppAction.js | 89 ++-- lib/models/smsAction.js | 50 +-- lib/models/twitterAction.js | 11 +- lib/models/updateAction.js | 54 +-- lib/models/visualRules.js | 274 ++++++------ lib/myutils.js | 64 +-- lib/perseo.js | 10 +- lib/routes/actionsController.js | 41 +- lib/routes/checkController.js | 4 +- lib/routes/metricsController.js | 1 - lib/routes/noticesController.js | 1 - lib/routes/rulesController.js | 8 +- lib/routes/versionController.js | 17 +- lib/routes/visualRulesController.js | 5 +- test/component/actions_elapsed_test.js | 106 ++--- test/component/actions_test.js | 494 ++++++++++++---------- test/component/auth_test.js | 91 ++-- test/component/config.js | 53 ++- test/component/db_test.js | 3 - test/component/error_in_axn.js | 114 ++--- test/component/loglevel_test.js | 82 ++-- test/component/myutils_test.js | 5 +- test/component/notices_test.js | 81 ++-- test/component/nsr_test.js | 109 ++--- test/component/rules_test.js | 363 +++++++++------- test/component/version_test.js | 4 +- test/component/visualrules_test.js | 558 ++++++++++++++----------- test/unit/axn_param_utest.js | 142 ++++--- test/unit/metrics_servicetime_avg.js | 25 +- test/unit/notice_location.js | 12 +- test/unit/notice_timestamp.js | 70 ++-- test/unit/nsr_utest.js | 60 ++- test/unit/paths_utest.js | 2 - test/unit/service_middlewr_utest.js | 6 +- test/unit/visualrules_utest.js | 16 +- test/utils/clients.js | 65 ++- test/utils/testEnvironment.js | 7 +- test/utils/utilsT.js | 229 +++++----- 57 files changed, 2225 insertions(+), 1994 deletions(-) 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) { count++; @@ -262,16 +278,21 @@ function refreshAllRules(rules) { deleteNSRuleIf(function(srv, subsrv, nm) { return !ruleSet.includes(srv, subsrv, nm); }); - logger.debug(context, util.format('no-signal rules %d/%d, checkers: %d', - count, rules.length, Object.keys(checkers).length)); + logger.debug( + context, + util.format('no-signal rules %d/%d, checkers: %d', count, rules.length, Object.keys(checkers).length) + ); } - module.exports.AddNSRule = addNSRule; module.exports.DeleteNSRule = deleteNSRule; module.exports.RefreshAllRules = refreshAllRules; module.exports.GetNSArrRule = getNSRule; module.exports.CheckNoSignal = checkNoSignal; module.exports.Nsr2Arr = nsr2arr; -module.exports.getMinIntervalMs = function() { return MIN_INTERVAL_MS; }; -module.exports.getIntervalUnit = function() { return intervalUnit; }; +module.exports.getMinIntervalMs = function() { + return MIN_INTERVAL_MS; +}; +module.exports.getIntervalUnit = function() { + return intervalUnit; +}; diff --git a/lib/models/notices.js b/lib/models/notices.js index f0ff8459..17e9ecf0 100644 --- a/lib/models/notices.js +++ b/lib/models/notices.js @@ -34,10 +34,7 @@ var util = require('util'), errors = {}; function parseLocation(locStr) { - var position, - lat, - lon, - utmResult; + var position, lat, lon, utmResult; position = locStr.split(',', 3); if (position.length !== 2) { @@ -51,21 +48,19 @@ function parseLocation(locStr) { if (isNaN(lon) || !isFinite(lon)) { return new errors.InvalidLongitude(lon); } - utmResult = converter.toUtm({coord: [lon, lat]}); // CAUTION: Longitude first element + utmResult = converter.toUtm({ coord: [lon, lat] }); // CAUTION: Longitude first element return { lat: lat, lon: lon, x: utmResult.coord.x, - y: utmResult.coord.y + y: utmResult.coord.y, }; } // http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15 function parseDate(isoStr) { - var date, - ts, - error; + var date, ts, error; ts = Date.parse(isoStr); if (isNaN(ts)) { @@ -89,7 +84,7 @@ function parseDate(isoStr) { hourUTC: date.getUTCHours(), minuteUTC: date.getUTCMinutes(), secondUTC: date.getUTCSeconds(), - millisecondUTC: date.getUTCMilliseconds() + millisecondUTC: date.getUTCMilliseconds(), }; } } @@ -129,8 +124,7 @@ function processCBNotice(service, subservice, ncr, ix) { localError = new errors.IdAsAttribute(JSON.stringify(attr)); } else if (attr.name === 'type') { localError = new errors.TypeAsAttribute(JSON.stringify(attr)); - } - else { + } else { n[attr.name] = attr.value; n[attr.name + '__type'] = attr.type; @@ -140,9 +134,11 @@ function processCBNotice(service, subservice, ncr, ix) { location = parseLocation(attr.value); } - if (attr.name === 'TimeInstant' || + if ( + attr.name === 'TimeInstant' || attr.type === 'urn:x-ogc:def:trs:IDAS:1.0:ISO8601' || - attr.type === 'DateTime') { + attr.type === 'DateTime' + ) { timeInfo = parseDate(attr.value); addTimeInfo(n, attr.name, timeInfo); } @@ -152,9 +148,11 @@ function processCBNotice(service, subservice, ncr, ix) { n[attr.name + '__metadata__' + attr.metadatas[i].name] = attr.metadatas[i].value; n[attr.name + '__metadata__' + attr.metadatas[i].name + '__type'] = attr.metadatas[i].type; - if (attr.metadatas[i].name === 'TimeInstant' || + if ( + attr.metadatas[i].name === 'TimeInstant' || attr.metadatas[i].type === 'urn:x-ogc:def:trs:IDAS:1.0:ISO8601' || - attr.metadatas[i].type === 'DateTime') { + attr.metadatas[i].type === 'DateTime' + ) { timeInfo = parseDate(attr.metadatas[i].value); addTimeInfo(n, attr.name + '__metadata__' + attr.metadatas[i].name, timeInfo); } @@ -169,13 +167,11 @@ function processCBNotice(service, subservice, ncr, ix) { if (location !== null) { if (location instanceof Error) { localError = location; - } - else { + } else { n[attr.name + '__lat'] = location.lat; n[attr.name + '__lon'] = location.lon; n[attr.name + '__x'] = location.x; n[attr.name + '__y'] = location.y; - } } } @@ -193,8 +189,8 @@ function processCBNotice(service, subservice, ncr, ix) { }); n = myutils.flattenMap('', n); - - } catch (ex) { // SHOULD BE ex instanceof TypeError. Do not do anything else inside try + } catch (ex) { + // SHOULD BE ex instanceof TypeError. Do not do anything else inside try localError = new errors.InvalidNotice(JSON.stringify(ncr)); myutils.logErrorIf(localError); return localError; @@ -209,39 +205,39 @@ function DoNotice(orionN, callback) { notice, sps; - // ServicePath may be a comma-separated list of servicePath // when an initial notification for a just created subscription // is created sps = orionN.subservice.split(','); if (!util.isArray(orionN.contextResponses)) { - return callback( - new errors.ContextResponsesNotArray('(' + typeof(orionN.contextResponses) + ')') - ); + return callback(new errors.ContextResponsesNotArray('(' + typeof orionN.contextResponses + ')')); } if (orionN.contextResponses.length !== sps.length) { - return callback( - new errors.ServipathCountMismatch('(' + sps.length + ',' + orionN.contextResponses.length + ')') - ); + return callback( + new errors.ServipathCountMismatch('(' + sps.length + ',' + orionN.contextResponses.length + ')') + ); } for (var j = 0; j < sps.length; j++) { notice = processCBNotice(orionN.service, sps[j].trim(), orionN, j); if (notice instanceof Error) { myutils.logErrorIf(notice); noticesErr.push(notice); - } - else { + } else { notices.push(notice); } } - async.each(notices, function(notice, cbEach) { + async.each( + notices, + function(notice, cbEach) { var h = {}; h[constants.SUBSERVICE_HEADER] = notice.subservice; - myutils.requestHelperWOMetrics('post', { - url: config.perseoCore.noticesURL, - json: notice, - headers: h - }, + myutils.requestHelperWOMetrics( + 'post', + { + url: config.perseoCore.noticesURL, + json: notice, + headers: h, + }, function(err, data) { if (err) { alarm.raise(alarm.POST_EVENT); @@ -252,18 +248,25 @@ function DoNotice(orionN, callback) { } // Don't wait propagation to next core to finish, asynchronously ... if (config.nextCore && config.nextCore.noticesURL) { - myutils.requestHelperWOMetrics('post', { - url: config.nextCore.noticesURL, - json: notice, - headers: h - }, myutils.logErrorIf); + myutils.requestHelperWOMetrics( + 'post', + { + url: config.nextCore.noticesURL, + json: notice, + headers: h, + }, + myutils.logErrorIf + ); } cbEach(); - }); + } + ); }, function endEach() { - var msgArr = [], statusCode = 400; - if (noticesErr.length === 0) { // No error happened + var msgArr = [], + statusCode = 400; + if (noticesErr.length === 0) { + // No error happened return callback(null, dataArr); // signal no error to callback function } noticesErr.forEach(function(e) { @@ -272,7 +275,7 @@ function DoNotice(orionN, callback) { statusCode = 500; } }); - return callback({httpCode: statusCode, message: msgArr}); + return callback({ httpCode: statusCode, message: msgArr }); } ); } diff --git a/lib/models/paths.js b/lib/models/paths.js index df8bc325..dafe9d16 100644 --- a/lib/models/paths.js +++ b/lib/models/paths.js @@ -33,11 +33,9 @@ function validComponent(component) { if (component.length === 0) { err = new errors.EmptyComponent(''); - } - else if (component.length > maxComponentLength) { + } else if (component.length > maxComponentLength) { err = new errors.TooLong(component); - } - else if (!componentPattern.test(component)) { + } else if (!componentPattern.test(component)) { err = new errors.InvalidCharacter(component); } return err; @@ -46,13 +44,15 @@ function validService(service) { return validComponent(service); } function validServicePath(servicepath) { - var err = null, parts; + var err = null, + parts; if (servicepath === '/') { return null; } parts = servicepath.split('/'); - if (parts[0] !== '') { // chars before /, not absolute + if (parts[0] !== '') { + // chars before /, not absolute return new errors.AbsolutePath(parts[0]); } if (parts.length > maxComponents) { @@ -78,7 +78,6 @@ module.exports.validServicePath = validServicePath; module.exports.errors = errors; (function() { - errors.EmptyComponent = function EmptyComponent(msg) { this.name = 'EMPTY'; this.message = 'service/subservice: empty component ' + msg; @@ -87,7 +86,7 @@ module.exports.errors = errors; errors.InvalidCharacter = function InvalidCharacter(msg) { this.name = 'INVALID_CHAR'; - this.message = 'service/subservice: invalid character \'' + msg + '\''; + this.message = "service/subservice: invalid character '" + msg + "'"; this.httpCode = 400; }; errors.AbsolutePath = function AbsolutePath(msg) { diff --git a/lib/models/postAction.js b/lib/models/postAction.js index 243dc6d2..86a71408 100644 --- a/lib/models/postAction.js +++ b/lib/models/postAction.js @@ -26,20 +26,17 @@ var myutils = require('../myutils'), logger = require('logops'), metrics = require('./metrics'); - - function buildPostOptions(action, event) { var options = { method: action.parameters.method || 'post', url: myutils.expandVar(action.parameters.url, event), qs: myutils.expandObject(action.parameters.qs, event), - headers: myutils.expandObject(action.parameters.headers, event) + headers: myutils.expandObject(action.parameters.headers, event), }; if (action.parameters.json) { options.json = myutils.expandObject(action.parameters.json, event); - } - else if (action.template) { + } else if (action.template) { options.text = myutils.expandVar(action.template, event); } @@ -53,13 +50,12 @@ function doIt(action, event, callback) { requestOptions = { url: options.url, qs: options.qs, - headers: options.headers + headers: options.headers, }; if (options.json) { requestOptions.json = true; requestOptions.body = options.json; - } - else if (options.text) { + } else if (options.text) { requestOptions.body = options.text; } @@ -85,4 +81,3 @@ function doIt(action, event, callback) { module.exports.doIt = doIt; module.exports.buildPostOptions = buildPostOptions; - diff --git a/lib/models/rules.js b/lib/models/rules.js index 5e9ec496..53ba9285 100644 --- a/lib/models/rules.js +++ b/lib/models/rules.js @@ -44,9 +44,11 @@ function validNSRule(rule) { function validRule(rule) { var err = null; - if (typeof rule.name !== 'string') { //includes null ('object') and undefined ('undefined') + if (typeof rule.name !== 'string') { + //includes null ('object') and undefined ('undefined') return new errors.MustBeStringRuleName(typeof rule.name); - } else if (rule.name.length === 0) { //empty string "" + } else if (rule.name.length === 0) { + //empty string "" return new errors.MissingRuleName(JSON.stringify(rule.name)); } else if (rule.name.length > MaxNameLength) { return new errors.TooLongRuleName(JSON.stringify(rule.name)); @@ -55,7 +57,8 @@ function validRule(rule) { } else if (!rule.text && !rule.nosignal) { return new errors.EmptyRule(JSON.stringify(rule)); } - if (rule.nosignal) { //Specific checks for no-signal rules + if (rule.nosignal) { + //Specific checks for no-signal rules err = validNSRule(rule); if (err !== null) { return err; @@ -68,30 +71,41 @@ function postR2core(rule, callback) { if (rule.text) { var eplRule = { name: myutils.ruleUniqueName(rule), - text: myutils.ruleWithContext(rule) + text: myutils.ruleWithContext(rule), }, context = { name: myutils.contextName(rule), - text: myutils.contextEPL(rule)}; + text: myutils.contextEPL(rule), + }; - async.series([ - myutils.requestHelperWOMetrics.bind(null, 'post', {url: config.perseoCore.rulesURL, json: context}), - myutils.requestHelperWOMetrics.bind(null, 'post', {url: config.perseoCore.rulesURL, json: eplRule}), - function propagateRule(cb) { - if (config.nextCore && config.nextCore.rulesURL) { - async.series([ - myutils.requestHelperWOMetrics.bind(null, - 'post', {url: config.nextCore.rulesURL, json: context}), - myutils.requestHelperWOMetrics.bind(null, - 'post', {url: config.nextCore.rulesURL, json: eplRule}) - ], function(/*error*/) { - cb(null); // Do not propagate error - }); - } else { - cb(null); - } - } - ], callback); + async.series( + [ + myutils.requestHelperWOMetrics.bind(null, 'post', { url: config.perseoCore.rulesURL, json: context }), + myutils.requestHelperWOMetrics.bind(null, 'post', { url: config.perseoCore.rulesURL, json: eplRule }), + function propagateRule(cb) { + if (config.nextCore && config.nextCore.rulesURL) { + async.series( + [ + myutils.requestHelperWOMetrics.bind(null, 'post', { + url: config.nextCore.rulesURL, + json: context, + }), + myutils.requestHelperWOMetrics.bind(null, 'post', { + url: config.nextCore.rulesURL, + json: eplRule, + }), + ], + function(/*error*/) { + cb(null); // Do not propagate error + } + ); + } else { + cb(null); + } + }, + ], + callback + ); } else { callback(null, rule); } @@ -100,19 +114,25 @@ function postR2core(rule, callback) { function delR2core(rule, callback) { var wholeName = myutils.ruleUniqueName(rule); //Now we don't know if it is EPL or N-S, it's safe to try to remove any case - async.series([ - myutils.requestHelperWOMetrics.bind(null, 'del', {url: config.perseoCore.rulesURL + '/' + wholeName}), - function propagateDel(cb) { - if (config.nextCore && config.nextCore.rulesURL) { - myutils.requestHelperWOMetrics('del', {url: config.nextCore.rulesURL + '/' + wholeName}, - function(/*error*/) { - cb(null); // Do not propagate error - }); - } else { - cb(null); - } - } - ], callback); + async.series( + [ + myutils.requestHelperWOMetrics.bind(null, 'del', { url: config.perseoCore.rulesURL + '/' + wholeName }), + function propagateDel(cb) { + if (config.nextCore && config.nextCore.rulesURL) { + myutils.requestHelperWOMetrics( + 'del', + { url: config.nextCore.rulesURL + '/' + wholeName }, + function(/*error*/) { + cb(null); // Do not propagate error + } + ); + } else { + cb(null); + } + }, + ], + callback + ); } function putR2core(rules, callback) { @@ -121,15 +141,15 @@ function putR2core(rules, callback) { if (rule.text) { rulesAndContexts.push({ name: myutils.contextName(rule), - text: myutils.contextEPL(rule) + text: myutils.contextEPL(rule), }); rulesAndContexts.push({ name: myutils.ruleUniqueName(rule), - text: myutils.ruleWithContext(rule) + text: myutils.ruleWithContext(rule), }); } }); - myutils.requestHelperWOMetrics('put', {url: config.perseoCore.rulesURL, json: rulesAndContexts}, callback); + myutils.requestHelperWOMetrics('put', { url: config.perseoCore.rulesURL, json: rulesAndContexts }, callback); } module.exports = { @@ -170,7 +190,7 @@ module.exports = { noSignal.AddNSRule(rule.service, rule.subservice, rule.name, rule.nosignal); } cb(null); - } + }, ], callback ); @@ -183,7 +203,7 @@ module.exports = { function(cb) { noSignal.DeleteNSRule(rule.service, rule.subservice, rule.name); cb(null); - } + }, ], callback ); @@ -196,7 +216,7 @@ module.exports = { noSignal.RefreshAllRules(rules); cb(null, rules); }, - putR2core + putR2core, ], callback ); @@ -224,11 +244,11 @@ module.exports = { } cb(null); }, - rulesStore.Update.bind(null, id, rule) + rulesStore.Update.bind(null, id, rule), ], callback ); - } + }, }; /** * Constructors for possible errors from this module @@ -278,5 +298,3 @@ module.exports.errors = errors; util.inherits(errors[element], Error); }); })(); - - diff --git a/lib/models/rulesStore.js b/lib/models/rulesStore.js index 64c23857..8b9b8cf0 100644 --- a/lib/models/rulesStore.js +++ b/lib/models/rulesStore.js @@ -84,12 +84,15 @@ function stringifyPostAxnParams(rule) { function search(rule, callback) { var db = appContext.Db(); - async.waterfall([ - db.collection.bind(db, rulesCollectionName, {strict: true}), - function(col, cb) { - col.findOne({name: rule.name, subservice: rule.subservice, service: rule.service}, cb); - } - ], callback); + async.waterfall( + [ + db.collection.bind(db, rulesCollectionName, { strict: true }), + function(col, cb) { + col.findOne({ name: rule.name, subservice: rule.subservice, service: rule.service }, cb); + }, + ], + callback + ); } function findAll(service, subservice, callback) { @@ -102,23 +105,26 @@ function findAll(service, subservice, callback) { criterion.subservice = subservice; } var db = appContext.Db(); - async.waterfall([ - db.collection.bind(db, rulesCollectionName, {strict: true}), - function(col, cb) { - col.find(criterion).toArray(function(err, rules) { - if (rules && util.isArray(rules)) { - rules.forEach(function(r) { - parsePostAxnParams(r); - }); - } - cb(err, rules); - }); + async.waterfall( + [ + db.collection.bind(db, rulesCollectionName, { strict: true }), + function(col, cb) { + col.find(criterion).toArray(function(err, rules) { + if (rules && util.isArray(rules)) { + rules.forEach(function(r) { + parsePostAxnParams(r); + }); + } + cb(err, rules); + }); + }, + ], + function(err, result) { + myutils.logErrorIf(err); + logger.info('rulesStore.FindAll %s', myutils.firstChars(result)); + return callback(err, result); } - ], function(err, result) { - myutils.logErrorIf(err); - logger.info('rulesStore.FindAll %s', myutils.firstChars(result)); - return callback(err, result); - }); + ); } module.exports = { @@ -145,55 +151,68 @@ module.exports = { FindAll: findAll, Remove: function Remove(rule, callback) { var db = appContext.Db(); - async.waterfall([ - db.collection.bind(db, rulesCollectionName, {strict: true}), - function(col, cb) { - col.remove({name: rule.name, subservice: rule.subservice, service: rule.service}, cb); + async.waterfall( + [ + db.collection.bind(db, rulesCollectionName, { strict: true }), + function(col, cb) { + col.remove({ name: rule.name, subservice: rule.subservice, service: rule.service }, cb); + }, + ], + function(err, result) { + myutils.logErrorIf(err); + logger.info('rulesStore.Remove %j', myutils.firstChars(result)); + return callback(err, result); } - ], function(err, result) { - myutils.logErrorIf(err); - logger.info('rulesStore.Remove %j', myutils.firstChars(result)); - return callback(err, result); - }); + ); }, Save: function Save(r, callback) { var db = appContext.Db(); stringifyPostAxnParams(r); - async.waterfall([ - db.collection.bind(db, rulesCollectionName, {strict: true}), - function(col, cb) { - col.save(r, cb); + async.waterfall( + [ + db.collection.bind(db, rulesCollectionName, { strict: true }), + function(col, cb) { + col.save(r, cb); + }, + ], + function(err, result) { + myutils.logErrorIf(err); + logger.info('rulesStore.Save %j', myutils.firstChars(result)); + return callback(err, result); } - ], function(err, result) { - myutils.logErrorIf(err); - logger.info('rulesStore.Save %j', myutils.firstChars(result)); - return callback(err, result); - }); + ); }, Update: function Update(id, r, callback) { var db = appContext.Db(); stringifyPostAxnParams(r); - async.waterfall([ - db.collection.bind(db, rulesCollectionName, {strict: true}), - function(col, cb) { - - col.findOneAndUpdate({name: id}, r, { - upsert: false, - returnOriginal: false - }, function(err, result) { - if (result && result.lastErrorObject && result.lastErrorObject.updatedExisting === false) { - return cb(new errors.NotFoundRule(id), null); - } - parsePostAxnParams(r); - return cb(err, r); - }); + async.waterfall( + [ + db.collection.bind(db, rulesCollectionName, { strict: true }), + function(col, cb) { + col.findOneAndUpdate( + { name: id }, + r, + { + upsert: false, + returnOriginal: false, + }, + function(err, result) { + if (result && result.lastErrorObject && result.lastErrorObject.updatedExisting === false) { + return cb(new errors.NotFoundRule(id), null); + } + parsePostAxnParams(r); + return cb(err, r); + } + ); + }, + ], + function(err, result) { + myutils.logErrorIf(err); + logger.info('rulesStore.Update %j', myutils.firstChars(result)); + return callback(err, result); } - ], function(err, result) { - myutils.logErrorIf(err); - logger.info('rulesStore.Update %j', myutils.firstChars(result)); - return callback(err, result); - }); - } + ); + }, }; /** * Constructors for possible errors from this module @@ -203,7 +222,6 @@ module.exports = { module.exports.errors = errors; (function() { - errors.NotFoundRule = function NotFoundRule(msg) { this.name = 'RULE_NOTFOUND'; this.message = 'rule not found ' + msg; diff --git a/lib/models/smppAction.js b/lib/models/smppAction.js index 73c1888d..d203b7ab 100644 --- a/lib/models/smppAction.js +++ b/lib/models/smppAction.js @@ -29,21 +29,19 @@ var logger = require('logops'), alarm = require('../alarm'), metrics = require('./metrics'); - function buildSMSOptions(action, event) { return { text: myutils.expandVar(action.template, event), - to: myutils.expandVar(action.parameters.to, event) + to: myutils.expandVar(action.parameters.to, event), }; } - function doIt(action, event, callback) { var session; try { var options, msg; options = buildSMSOptions(action, event); - msg = {to: ['tel:' + options.to], message: options.text, from: config.smpp.from}; + msg = { to: ['tel:' + options.to], message: options.text, from: config.smpp.from }; metrics.IncMetrics(event.service, event.subservice, metrics.actionSMPP); @@ -68,33 +66,32 @@ function doIt(action, event, callback) { to = to.toString(); logger.debug('smpp sms from: %s, to: %s, text: %s', from, to, text); - session.submit_sm({ - source_addr: from, - destination_addr: to, - short_message: text - }, function(pdu) { - if (pdu.command_status === 0) { - // Message successfully sent - logger.info('Message %j successfully sent', pdu.message_id); - metrics.IncMetrics(event.service, event.subservice, - metrics.okActionSMPP); - alarm.release(alarm.SMPP); - } else { - logger.warn('Message not successfully sent'); - logger.debug('sendSMPP submit_sm pdu status %s', - lookupPDUStatusKey(pdu.command_status)); - metrics.IncMetrics(event.service, event.subservice, - metrics.failedActionSMPP); - alarm.raise(alarm.SMPP); + session.submit_sm( + { + source_addr: from, + destination_addr: to, + short_message: text, + }, + function(pdu) { + if (pdu.command_status === 0) { + // Message successfully sent + logger.info('Message %j successfully sent', pdu.message_id); + metrics.IncMetrics(event.service, event.subservice, metrics.okActionSMPP); + alarm.release(alarm.SMPP); + } else { + logger.warn('Message not successfully sent'); + logger.debug('sendSMPP submit_sm pdu status %s', lookupPDUStatusKey(pdu.command_status)); + metrics.IncMetrics(event.service, event.subservice, metrics.failedActionSMPP); + alarm.raise(alarm.SMPP); + } } - }); + ); }; - logger.debug('smpp session host: %s, port: %s', - config.smpp.host, config.smpp.port); + logger.debug('smpp session host: %s, port: %s', config.smpp.host, config.smpp.port); session = new smpp.Session({ - host: config.smpp.host, - port: config.smpp.port + host: config.smpp.host, + port: config.smpp.port, }); // We will track connection state for re-connecting @@ -103,23 +100,27 @@ function doIt(action, event, callback) { session.on('connect', function() { /*jshint camelcase:false */ didConnect = true; - logger.debug('smpp session on connect system_id: %s, password: %s', - config.smpp.systemid, config.smpp.password); - session.bind_transceiver({ - system_id: config.smpp.systemid, - password: config.smpp.password - }, function(pdu) { - if (pdu.command_status === 0) { - logger.info('SMPP Successfully bound'); - sendSMPP(config.smpp.from, options.to, options.text); - } else { - logger.warn('SMPP not successfully bound'); - logger.debug('SMPP bind pdu status: %s', - lookupPDUStatusKey(pdu.command_status)); - metrics.IncMetrics(event.service, event.subservice, - metrics.failedActionSMPP); + logger.debug( + 'smpp session on connect system_id: %s, password: %s', + config.smpp.systemid, + config.smpp.password + ); + session.bind_transceiver( + { + system_id: config.smpp.systemid, + password: config.smpp.password, + }, + function(pdu) { + if (pdu.command_status === 0) { + logger.info('SMPP Successfully bound'); + sendSMPP(config.smpp.from, options.to, options.text); + } else { + logger.warn('SMPP not successfully bound'); + logger.debug('SMPP bind pdu status: %s', lookupPDUStatusKey(pdu.command_status)); + metrics.IncMetrics(event.service, event.subservice, metrics.failedActionSMPP); + } } - }); + ); }); session.on('close', function() { @@ -135,7 +136,6 @@ function doIt(action, event, callback) { }); return callback; - } catch (ex) { metrics.IncMetrics(event.service, event.subservice, metrics.failedActionSMPP); return callback(ex); @@ -144,4 +144,3 @@ function doIt(action, event, callback) { module.exports.doIt = doIt; module.exports.buildSMSOptions = buildSMSOptions; - diff --git a/lib/models/smsAction.js b/lib/models/smsAction.js index 04967c36..815f77bb 100644 --- a/lib/models/smsAction.js +++ b/lib/models/smsAction.js @@ -29,44 +29,47 @@ var util = require('util'), alarm = require('../alarm'), metrics = require('./metrics'); - function buildSMSOptions(action, event) { return { text: myutils.expandVar(action.template, event), - to: myutils.expandVar(action.parameters.to, event) + to: myutils.expandVar(action.parameters.to, event), }; } function doIt(action, event, callback) { try { var options, msg; options = buildSMSOptions(action, event); - msg = {to: ['tel:' + options.to], message: options.text, from: config.sms.from}; + msg = { to: ['tel:' + options.to], message: options.text, from: config.sms.from }; metrics.IncMetrics(event.service, event.subservice, metrics.actionSMS); - myutils.requestHelper('post', { - url: config.sms.URL, - json: true, - body: msg, - headers: { - 'User-Agent': 'request', - 'API_KEY': config.sms.API_KEY, - 'API_SECRET': config.sms.API_SECRET - } - }, function(err, data) { - myutils.logErrorIf(err, util.format('%s -> %s', config.sms.URL, msg.to)); - if (err) { - metrics.IncMetrics(event.service, event.subservice, metrics.failedActionSMS); + myutils.requestHelper( + 'post', + { + url: config.sms.URL, + json: true, + body: msg, + headers: { + 'User-Agent': 'request', + API_KEY: config.sms.API_KEY, + API_SECRET: config.sms.API_SECRET, + }, + }, + function(err, data) { + myutils.logErrorIf(err, util.format('%s -> %s', config.sms.URL, msg.to)); + if (err) { + metrics.IncMetrics(event.service, event.subservice, metrics.failedActionSMS); - alarm.raise(alarm.SMS); - } else { - metrics.IncMetrics(event.service, event.subservice, metrics.okActionSMS); + alarm.raise(alarm.SMS); + } else { + metrics.IncMetrics(event.service, event.subservice, metrics.okActionSMS); - alarm.release(alarm.SMS); + alarm.release(alarm.SMS); + } + logger.info('smsAction.SendSMS done url:%s result:%j, msg: %j', config.sms.URL, err || data, msg); + return callback(err, data); } - logger.info('smsAction.SendSMS done url:%s result:%j, msg: %j', config.sms.URL, err || data, msg); - return callback(err, data); - }); + ); } catch (ex) { metrics.IncMetrics(event.service, event.subservice, metrics.failedActionSMS); @@ -76,4 +79,3 @@ function doIt(action, event, callback) { module.exports.doIt = doIt; module.exports.buildSMSOptions = buildSMSOptions; - diff --git a/lib/models/twitterAction.js b/lib/models/twitterAction.js index 51b09331..dbebbd36 100644 --- a/lib/models/twitterAction.js +++ b/lib/models/twitterAction.js @@ -29,7 +29,7 @@ var myutils = require('../myutils'), metrics = require('./metrics'); function buildTwitterOptions(action, event) { - return {text: myutils.expandVar(action.template, event)}; + return { text: myutils.expandVar(action.template, event) }; } function doIt(action, event, callback) { @@ -40,7 +40,7 @@ function doIt(action, event, callback) { consumer_key: action.parameters.consumer_key, consumer_secret: action.parameters.consumer_secret, access_token_key: action.parameters.access_token_key, - access_token_secret: action.parameters.access_token_secret + access_token_secret: action.parameters.access_token_secret, /*jshint +W106 */ }, client; @@ -56,11 +56,10 @@ function doIt(action, event, callback) { client = new Twitter(options); text = buildTwitterOptions(action, event).text; - client.post('statuses/update', {status: text}, function(err, params, response) { + client.post('statuses/update', { status: text }, function(err, params, response) { if (err) { metrics.IncMetrics(event.service, event.subservice, metrics.failedActionTwitter); - } - else { + } else { metrics.IncMetrics(event.service, event.subservice, metrics.okActionTwitter); } @@ -73,9 +72,7 @@ function doIt(action, event, callback) { return callback(ex); } - } module.exports.doIt = doIt; module.exports.buildTwitterOptions = buildTwitterOptions; - diff --git a/lib/models/updateAction.js b/lib/models/updateAction.js index a5f68152..5aadfa10 100644 --- a/lib/models/updateAction.js +++ b/lib/models/updateAction.js @@ -48,7 +48,7 @@ function getCachedToken(service, subservice, name) { if (tokens[service][subservice][name] === undefined) { emitter = new events.EventEmitter(); emitter.setMaxListeners(MAX_LISTENERS); - tokens[service][subservice][name] = {token: null, generating: false, emitter: emitter}; + tokens[service][subservice][name] = { token: null, generating: false, emitter: emitter }; } return tokens[service][subservice][name]; } @@ -72,7 +72,7 @@ function generateToken(trust, cached) { function buildUpdateOptions(action, event) { var options, attr, - parameterTypeGiven = (action.parameters.type !== undefined); + parameterTypeGiven = action.parameters.type !== undefined; action.parameters.id = action.parameters.id || '${id}'; action.parameters.type = action.parameters.type || '${type}'; @@ -85,12 +85,12 @@ function buildUpdateOptions(action, event) { action.parameters.attributes.push({ name: action.parameters.name, value: action.parameters.value, - type: action.parameters.attrType + type: action.parameters.attrType, }); } options = { id: myutils.expandVar(action.parameters.id, event), - isPattern: myutils.expandVar(action.parameters.isPattern, event) + isPattern: myutils.expandVar(action.parameters.isPattern, event), }; if (action.parameters.actionType) { options.actionType = myutils.expandVar(action.parameters.actionType, event); @@ -99,7 +99,7 @@ function buildUpdateOptions(action, event) { for (var i = 0; i < action.parameters.attributes.length; i++) { attr = { name: myutils.expandVar(action.parameters.attributes[i].name, event), - value: myutils.expandVar(action.parameters.attributes[i].value, event) + value: myutils.expandVar(action.parameters.attributes[i].value, event), }; //The portal does not provide 'type' for attribute, "plain" rules could @@ -116,11 +116,7 @@ function buildUpdateOptions(action, event) { return options; } function doRequest(action, event, token, callback) { - var subservice, - service, - headers, - options, - updateOrion; + var subservice, service, headers, options, updateOrion; subservice = event.subservice; service = event.service; @@ -132,10 +128,10 @@ function doRequest(action, event, token, callback) { { isPattern: options.isPattern, id: options.id, - attributes: options.attributes - } + attributes: options.attributes, + }, ], - updateAction: 'APPEND' + updateAction: 'APPEND', }; if (options.actionType !== undefined) { updateOrion.updateAction = options.actionType; @@ -146,7 +142,7 @@ function doRequest(action, event, token, callback) { } headers = { - 'Accept': 'application/json' + Accept: 'application/json', }; if (token !== null) { headers[constants.AUTH_HEADER] = token; @@ -154,16 +150,17 @@ function doRequest(action, event, token, callback) { headers[constants.SUBSERVICE_HEADER] = subservice; headers[constants.SERVICE_HEADER] = service; - metrics.IncMetrics(event.service, event.subservice, metrics.actionEntityUpdate); logger.debug('body to post %j ', updateOrion); - myutils.requestHelper('post', + myutils.requestHelper( + 'post', { url: config.orion.URL, body: updateOrion, json: true, - headers: headers - }, function(err, data) { + headers: headers, + }, + function(err, data) { if (err) { metrics.IncMetrics(event.service, event.subservice, metrics.failedActionEntityUpdate); @@ -177,7 +174,8 @@ function doRequest(action, event, token, callback) { err = new errors.OrionError(JSON.stringify(data.body.orionError)); } callback(err, data); - }); + } + ); } function makeTokenListenerFunc(action, event, callback) { @@ -195,11 +193,7 @@ function makeTokenListenerFunc(action, event, callback) { } function doItWithToken(action, event, callback) { - var subservice, - service, - ruleName, - cached, - newTokenListener; + var subservice, service, ruleName, cached, newTokenListener; subservice = event.subservice; service = event.service; @@ -207,13 +201,15 @@ function doItWithToken(action, event, callback) { newTokenListener = makeTokenListenerFunc(action, event, callback); cached = getCachedToken(service, subservice, ruleName); - if (cached.token === null) { // First time token is generated from trust + if (cached.token === null) { + // First time token is generated from trust cached.emitter.once(newTokenEventName, newTokenListener); if (cached.generating === false) { logger.debug('generating token for %s %s %s', service, subservice, ruleName); generateToken(action.parameters.trust, cached); } - } else if (cached.generating === true) { // In the middle of getting a new one + } else if (cached.generating === true) { + // In the middle of getting a new one logger.debug('waiting token to be generated %s %s %s', service, subservice, ruleName); cached.emitter.once(newTokenEventName, newTokenListener); } else { @@ -225,8 +221,7 @@ function doItWithToken(action, event, callback) { if (cached.generating === false) { generateToken(action.parameters.trust, cached); } - } - else { + } else { return callback(error, data); } }); @@ -265,6 +260,3 @@ module.exports.errors = errors; util.inherits(errors[element], Error); }); })(); - - - diff --git a/lib/models/visualRules.js b/lib/models/visualRules.js index ddc35d3e..2900acfb 100644 --- a/lib/models/visualRules.js +++ b/lib/models/visualRules.js @@ -25,16 +25,15 @@ var util = require('util'), rules = require('./rules'), myutils = require('../myutils'), - eplTemplate = 'select *,"${name}" as ruleName' + - ' from pattern [every ev=iotEvent(${conditions})]', + eplTemplate = 'select *,"${name}" as ruleName' + ' from pattern [every ev=iotEvent(${conditions})]', operatorMap = { - 'GREATER_THAN': ' > ', - 'EQUAL_TO': ' = ', - 'MINOR_THAN': ' < ', - 'DIFFERENT_TO': ' != ', - 'GREATER_OR_EQUAL_THAN': ' >= ', - 'MINOR_OR_EQUAL_THAN': ' <= ', - 'MATCH': ' regexp ' + GREATER_THAN: ' > ', + EQUAL_TO: ' = ', + MINOR_THAN: ' < ', + DIFFERENT_TO: ' != ', + GREATER_OR_EQUAL_THAN: ' >= ', + MINOR_OR_EQUAL_THAN: ' <= ', + MATCH: ' regexp ', }, errors = {}; @@ -78,7 +77,8 @@ function makeObservationCondition(exprL, op, exprR, isNumber) { return util.format('(%s %s %s)', exprL, operatorMap[op], exprR); } function plainParams(p) { - var i, obj = {}; + var i, + obj = {}; for (i = 0; i < p.length; i += 1) { obj[p[i].name] = p[i].value; } @@ -86,135 +86,149 @@ function plainParams(p) { } function vr2rule(cardRule) { - var r, i, card, + var r, + i, + card, conditions = [], action = {}, - noSignal, id, idRegexp, type, + noSignal, + id, + idRegexp, + type, plain, checkInterval, errOp; try { - r = {VR: cardRule, name: cardRule.name}; + r = { VR: cardRule, name: cardRule.name }; for (i = 0; i < cardRule.cards.length; i += 1) { card = cardRule.cards[i]; switch (card.type) { - case 'SensorCard': - switch (card.conditionList[0].scope) { - case 'USER_PROP': - errOp = errorOperator(card.conditionList[0].operator); - if (errOp) { - return errOp; - } - conditions.push(makeUserPropCondition(card.conditionList[0].userProp, - card.conditionList[0].operator, - card.conditionList[0].parameterValue, - false)); + case 'SensorCard': + switch (card.conditionList[0].scope) { + case 'USER_PROP': + errOp = errorOperator(card.conditionList[0].operator); + if (errOp) { + return errOp; + } + conditions.push( + makeUserPropCondition( + card.conditionList[0].userProp, + card.conditionList[0].operator, + card.conditionList[0].parameterValue, + false + ) + ); - break; - case 'XPATH': - errOp = errorOperator(card.conditionList[0].operator); - if (errOp) { - return errOp; - } - conditions.push(makeObservationCondition(card.conditionList[0].parameterName, - card.conditionList[0].operator, - card.conditionList[0].parameterValue, - card.sensorData.dataType === 'Quantity')); - if (card.conditionList[0].parameterName === 'id') { - if (card.conditionList[0].operator === 'MATCH') { - idRegexp = card.conditionList[0].parameterValue; - //Just to check it is a valid regexp - new RegExp(idRegexp); - } else { - id = card.conditionList[0].parameterValue; - } - } else if (card.conditionList[0].parameterName === 'type') { - type = card.conditionList[0].parameterValue; - } - break; - case 'OBSERVATION': - errOp = errorOperator(card.conditionList[0].operator); - if (errOp) { - return errOp; + break; + case 'XPATH': + errOp = errorOperator(card.conditionList[0].operator); + if (errOp) { + return errOp; + } + conditions.push( + makeObservationCondition( + card.conditionList[0].parameterName, + card.conditionList[0].operator, + card.conditionList[0].parameterValue, + card.sensorData.dataType === 'Quantity' + ) + ); + if (card.conditionList[0].parameterName === 'id') { + if (card.conditionList[0].operator === 'MATCH') { + idRegexp = card.conditionList[0].parameterValue; + //Just to check it is a valid regexp + new RegExp(idRegexp); + } else { + id = card.conditionList[0].parameterValue; + } + } else if (card.conditionList[0].parameterName === 'type') { + type = card.conditionList[0].parameterValue; + } + break; + case 'OBSERVATION': + errOp = errorOperator(card.conditionList[0].operator); + if (errOp) { + return errOp; + } + if (card.sensorData.measureName === 'id') { + return new errors.IdAsAttribute(''); + } else if (card.sensorData.measureName === 'type') { + return new errors.TypeAsAttribute(''); + } + conditions.push( + makeObservationCondition( + card.sensorData.measureName, + card.conditionList[0].operator, + card.conditionList[0].parameterValue, + card.sensorData.dataType === 'Quantity' + ) + ); + break; + case 'LAST_MEASURE': + checkInterval = parseInt(card.timeData.interval, 10); + if (isNaN(checkInterval) || checkInterval < 1) { + return new errors.InvalidVisualRule('check interval ' + card.timeData.interval); + } + noSignal = { + checkInterval: card.timeData.interval, + attribute: card.sensorData.measureName, + reportInterval: card.conditionList[0].parameterValue, + }; + break; + default: + return new errors.NotSupportedActionScope(card.conditionList[0].scope); } - if (card.sensorData.measureName === 'id') { - return new errors.IdAsAttribute(''); - } else if (card.sensorData.measureName === 'type') { - return new errors.TypeAsAttribute(''); - } - conditions.push(makeObservationCondition(card.sensorData.measureName, - card.conditionList[0].operator, - card.conditionList[0].parameterValue, - card.sensorData.dataType === 'Quantity')); - break; - case 'LAST_MEASURE': - checkInterval = parseInt(card.timeData.interval, 10); - if (isNaN(checkInterval) || checkInterval < 1) { - return new errors.InvalidVisualRule('check interval ' + card.timeData.interval); - } - noSignal = { - checkInterval: card.timeData.interval, - attribute: card.sensorData.measureName, - reportInterval: card.conditionList[0].parameterValue - }; - break; - default: - return new errors.NotSupportedActionScope(card.conditionList[0].scope); - } - break; - case 'ActionCard': - switch (card.actionData.type) { - case 'SendEmailAction': - plain = plainParams(card.actionData.userParams); - action.type = 'email'; - action.template = plain['mail.message']; - action.parameters = { - to: plain['mail.to'], - from: plain['mail.from'], - subject: plain['mail.subject'] - }; - break; - case 'SendSmsMibAction': - plain = plainParams(card.actionData.userParams); - action.type = 'sms'; - action.template = plain['sms.message']; - action.parameters = { - to: plain['sms.to'] - }; break; - case 'updateAttribute': - action.type = 'update'; - action.parameters = { - name: card.actionData.userParams.name, - value: card.actionData.userParams.value - }; - if (card.actionData.userParams.actionType) { - action.parameters.actionType = - card.actionData.userParams.actionType; + case 'ActionCard': + switch (card.actionData.type) { + case 'SendEmailAction': + plain = plainParams(card.actionData.userParams); + action.type = 'email'; + action.template = plain['mail.message']; + action.parameters = { + to: plain['mail.to'], + from: plain['mail.from'], + subject: plain['mail.subject'], + }; + break; + case 'SendSmsMibAction': + plain = plainParams(card.actionData.userParams); + action.type = 'sms'; + action.template = plain['sms.message']; + action.parameters = { + to: plain['sms.to'], + }; + break; + case 'updateAttribute': + action.type = 'update'; + action.parameters = { + name: card.actionData.userParams.name, + value: card.actionData.userParams.value, + }; + if (card.actionData.userParams.actionType) { + action.parameters.actionType = card.actionData.userParams.actionType; + } + break; + default: + return new errors.NotSupportedActionType(card.actionData.type); } break; - default: - return new errors.NotSupportedActionType(card.actionData.type); - } - break; - case 'TimeCard': - if (card.configData) { - switch (card.configData.timeType) { - case 'timeInterval': //No signal detection - // This is different from old DCA rules. No-signal cards are now of type - // SensorCard with a timeData field. https://jirapdi.tid.es/browse/PIOTP-855 - return new errors.NotSupportedTimeCard(card.configData.timeType); - //break; not necessary with return - case 'timeElapsed': // Minimal interval for actions - action.interval = card.timeData.interval; - break; + case 'TimeCard': + if (card.configData) { + switch (card.configData.timeType) { + case 'timeInterval': //No signal detection + // This is different from old DCA rules. No-signal cards are now of type + // SensorCard with a timeData field. https://jirapdi.tid.es/browse/PIOTP-855 + return new errors.NotSupportedTimeCard(card.configData.timeType); + //break; not necessary with return + case 'timeElapsed': // Minimal interval for actions + action.interval = card.timeData.interval; + break; + } + } else { + return new errors.MissingConfigDataInTimeCard(JSON.stringify(card)); } - } - else { - return new errors.MissingConfigDataInTimeCard(JSON.stringify(card)); - } - } } @@ -231,10 +245,11 @@ function vr2rule(cardRule) { name: r.name, conditions: conditions.join(' AND '), service: r.service, - subservice: r.subservice + subservice: r.subservice, }); } - } catch (ex) { // SHOULD BE ex instanceof TypeError. Do not do anything else inside try + } catch (ex) { + // SHOULD BE ex instanceof TypeError. Do not do anything else inside try // Also it can be instance of SyntaxError: Invalid regular expression return new errors.InvalidVisualRule(ex.toString()); } @@ -247,7 +262,8 @@ module.exports = { if (err) { return callback(err, null); } - var vrdata = [], i; + var vrdata = [], + i; for (i = 0; i < data.length; i += 1) { if (data[i].VR) { vrdata.push(data[i].VR); @@ -294,7 +310,7 @@ module.exports = { } callback(err, data[0].VR); }); - } + }, }; /** * Constructors for possible errors from this module @@ -307,7 +323,6 @@ module.exports.vr2rule = vr2rule; module.exports.errorOperator = errorOperator; (function() { - errors.InvalidVisualRule = function InvalidVisualRule(msg) { this.name = 'INVALID_VISUAL_RULE'; this.message = 'invalid visual rule format ' + msg; @@ -351,6 +366,3 @@ module.exports.errorOperator = errorOperator; util.inherits(errors[element], Error); }); })(); - - - diff --git a/lib/myutils.js b/lib/myutils.js index 3a1766e2..d5deea1e 100644 --- a/lib/myutils.js +++ b/lib/myutils.js @@ -54,10 +54,7 @@ function logErrorIf(err, message, context) { function expandVar(val, mapping) { if (typeof val === 'string') { Object.keys(mapping).forEach(function(p) { - val = val.replace( - new RegExp('\\$\\{' + p + '\\}', 'g'), - mapping[p] - ); + val = val.replace(new RegExp('\\$\\{' + p + '\\}', 'g'), mapping[p]); }); val = val.replace(/\$\{\w*\}/g, '[?]'); } @@ -69,15 +66,9 @@ function expandObject(templateObj, dictionary) { if (templateObj && typeof templateObj === 'object') { Object.keys(templateObj).forEach(function(key) { if (typeof templateObj[key] === 'string') { - res[expandVar(key, dictionary)] = expandVar( - templateObj[key], - dictionary - ); + res[expandVar(key, dictionary)] = expandVar(templateObj[key], dictionary); } else if (typeof templateObj[key] === 'object') { - res[expandVar(key, dictionary)] = expandObject( - templateObj[key], - dictionary - ); + res[expandVar(key, dictionary)] = expandObject(templateObj[key], dictionary); } }); } @@ -112,31 +103,18 @@ function requestHelperAux(method, options, withMetrics, callback) { domain = process.domain; logger.info('making %s to %s', method, options.url); if (withMetrics && domain.context) { - metrics.IncMetrics( - domain.context.srv, - domain.context.subsrv, - metrics.outgoingTransactions - ); + metrics.IncMetrics(domain.context.srv, domain.context.subsrv, metrics.outgoingTransactions); } headers = options.headers || {}; if (domain && domain.context) { headers[constants.CORRELATOR_HEADER] = domain.context.corr; - if ( - domain.context.srv && - headers[constants.SERVICE_HEADER] === undefined - ) { + if (domain.context.srv && headers[constants.SERVICE_HEADER] === undefined) { headers[constants.SERVICE_HEADER] = domain.context.srv; } - if ( - domain.context.subsrv && - headers[constants.SUBSERVICE_HEADER] === undefined - ) { + if (domain.context.subsrv && headers[constants.SUBSERVICE_HEADER] === undefined) { headers[constants.SUBSERVICE_HEADER] = domain.context.subsrv; } - if ( - domain.context.from && - headers[constants.REALIP_HEADER] === undefined - ) { + if (domain.context.from && headers[constants.REALIP_HEADER] === undefined) { headers[constants.REALIP_HEADER] = domain.context.from; } } @@ -177,11 +155,7 @@ function requestHelperAux(method, options, withMetrics, callback) { if (err) { logErrorIf(err, util.format('error %s to %s', method, options.url)); if (withMetrics && domain.context) { - metrics.IncMetrics( - domain.context.srv, - domain.context.subsrv, - metrics.outgoingTransactionsErrors - ); + metrics.IncMetrics(domain.context.srv, domain.context.subsrv, metrics.outgoingTransactionsErrors); } return callback(err, null); } @@ -193,19 +167,13 @@ function requestHelperAux(method, options, withMetrics, callback) { 'error %s to %s (%s)', method, options.url, - (body && body.error) || - (body && JSON.stringify(body)) || - response.statusCode + (body && body.error) || (body && JSON.stringify(body)) || response.statusCode ) ); localError.httpCode = 500; logErrorIf(localError, domain && domain.context); if (withMetrics && domain.context) { - metrics.IncMetrics( - domain.context.srv, - domain.context.subsrv, - metrics.outgoingTransactionsErrors - ); + metrics.IncMetrics(domain.context.srv, domain.context.subsrv, metrics.outgoingTransactionsErrors); } return callback(localError, respObj); } @@ -258,11 +226,7 @@ function respondAux(resp, err, data, withCount, raw, withMetrics) { Buffer.byteLength(respStr, 'utf-8') ); if (err) { - metrics.IncMetrics( - domain.context.srv, - domain.context.subsrv, - metrics.incomingTransactionsErrors - ); + metrics.IncMetrics(domain.context.srv, domain.context.subsrv, metrics.incomingTransactionsErrors); } } resp.set('Content-Type', 'application/json'); @@ -295,11 +259,7 @@ function purgeName(name) { } function contextName(rule) { - return util.format( - 'ctxt$%s%s', - purgeName(rule.service), - purgeName(rule.subservice) - ); + return util.format('ctxt$%s%s', purgeName(rule.service), purgeName(rule.subservice)); } function ruleUniqueName(rule) { diff --git a/lib/perseo.js b/lib/perseo.js index 2bfadc3c..26b96b91 100644 --- a/lib/perseo.js +++ b/lib/perseo.js @@ -142,11 +142,7 @@ function start(callbackStart) { }, function(callback) { server = app.listen(config.endpoint.port, function() { - logger.info( - context, - 'listening on port %d', - server.address().port - ); + logger.info(context, 'listening on port %d', server.address().port); return callback(null, server); }); }, @@ -163,9 +159,7 @@ function start(callbackStart) { function stop(callback) { var context = { op: 'stop', comp: constants.COMPONENT_NAME }; logger.info(context, 'stopping perseo'); - async.series([server.close.bind(server), db.close, db.orionClose], function( - err - ) { + async.series([server.close.bind(server), db.close, db.orionClose], function(err) { myutils.logErrorIf(err); return callback(err); }); diff --git a/lib/routes/actionsController.js b/lib/routes/actionsController.js index fbf717ad..aae9ac06 100644 --- a/lib/routes/actionsController.js +++ b/lib/routes/actionsController.js @@ -30,7 +30,8 @@ var domain = require('domain'), config = require('../../config'), constants = require('../constants'), logger = require('logops'), - recentAxn = {}, corrAge = {}; + recentAxn = {}, + corrAge = {}; function PostAction(req, resp) { var firedEvent, @@ -53,17 +54,21 @@ function PostAction(req, resp) { // try detect loop corrAge[correlator] = now; rulesWithCorr = recentAxn[correlator]; - if (!rulesWithCorr) { //There is no array yet for this correlator + if (!rulesWithCorr) { + //There is no array yet for this correlator rulesWithCorr = recentAxn[correlator] = []; } if (util.isArray(rulesWithCorr)) { for (var i = 0; i < rulesWithCorr.length; i++) { if (rulesWithCorr[i] === firedEvent.ruleName) { - errMsg = util.format('check infinite loop for %s (%s) - the rule has not been triggered', - firedEvent.ruleName, correlator); + errMsg = util.format( + 'check infinite loop for %s (%s) - the rule has not been triggered', + firedEvent.ruleName, + correlator + ); logger.error(errMsg); metrics.IncMetrics(req.service, req.subservice, metrics.errAction); - myutils.respondWOMetrics(resp, {httpCode: 500, message: errMsg}); + myutils.respondWOMetrics(resp, { httpCode: 500, message: errMsg }); return; } } @@ -99,15 +104,13 @@ function PostAction(req, resp) { nextDomain.start = process.domain.start; nextDomain.context.srv = process.domain.context.srv; nextDomain.context.subsrv = process.domain.context.subsrv; - } //Don't wait until action is finished resp.end(); if (config.isMaster) { delay = 0; - } - else { + } else { delay = config.slaveDelay; } // TODO: Tricky ... To refactor? @@ -122,24 +125,21 @@ function PostAction(req, resp) { logger.debug('response-time: %s', responseTime); nextDomain.removeListener('error', domainErrorHandler); delete nextDomain.context; - }; nextDomain.on('error', domainErrorHandler); firedEvent.fiwarePerseoContext = nextDomain.context; setTimeout(function() { - nextDomain.run( - function() { - for (var p in firedEvent.ev) { - if (firedEvent[p] === undefined) { - firedEvent[p] = firedEvent.ev[p]; - } + nextDomain.run(function() { + for (var p in firedEvent.ev) { + if (firedEvent[p] === undefined) { + firedEvent[p] = firedEvent.ev[p]; } - actions.Do(firedEvent, function(err) { - myutils.logErrorIf(err); - cleanDomain(); - }); } - ); + actions.Do(firedEvent, function(err) { + myutils.logErrorIf(err); + cleanDomain(); + }); + }); }, delay); } @@ -153,4 +153,3 @@ function AddTo(app) { * @param {Object} Express application */ module.exports.AddTo = AddTo; - diff --git a/lib/routes/checkController.js b/lib/routes/checkController.js index aad59094..ad132b99 100644 --- a/lib/routes/checkController.js +++ b/lib/routes/checkController.js @@ -26,14 +26,13 @@ var config = require('../../config'), myutils = require('../myutils'), errorNotAMaster; -errorNotAMaster = new Error('I\'m not a master'); +errorNotAMaster = new Error("I'm not a master"); errorNotAMaster.httpCode = 400; function Check(req, resp) { if (config.isMaster) { myutils.respondWOMetrics(resp, null, 'OK'); } else { - myutils.respondWOMetrics(resp, errorNotAMaster, null); } } @@ -48,4 +47,3 @@ function AddTo(app) { * @param {Object} Express application */ module.exports.AddTo = AddTo; - diff --git a/lib/routes/metricsController.js b/lib/routes/metricsController.js index 3851e3c0..9e390e1a 100644 --- a/lib/routes/metricsController.js +++ b/lib/routes/metricsController.js @@ -38,7 +38,6 @@ function deleteMetrics(req, resp) { function AddTo(app) { app.get(config.endpoint.metricsPath, getMetrics); app.delete(config.endpoint.metricsPath, deleteMetrics); - } /** diff --git a/lib/routes/noticesController.js b/lib/routes/noticesController.js index a17cf192..8501dc43 100644 --- a/lib/routes/noticesController.js +++ b/lib/routes/noticesController.js @@ -54,4 +54,3 @@ function AddTo(app) { * @param {Object} Express application */ module.exports.AddTo = AddTo; - diff --git a/lib/routes/rulesController.js b/lib/routes/rulesController.js index 46736f24..04e2bd19 100644 --- a/lib/routes/rulesController.js +++ b/lib/routes/rulesController.js @@ -36,7 +36,7 @@ function GetRules(req, resp) { var rule = { name: req.params.id, subservice: req.subservice, - service: req.service + service: req.service, }; rules.Find(rule, function(err, data) { myutils.respond(resp, err, data); @@ -60,7 +60,7 @@ function DelRules(req, resp) { var rule = { name: req.params.id, subservice: req.subservice, - service: req.service + service: req.service, }; metrics.IncMetrics(req.service, req.subservice, metrics.ruleDelete); rules.Remove(rule, function(err, data) { @@ -79,7 +79,6 @@ function AddTo(app) { app.get(config.endpoint.rulesPath + '/:id', GetRules); app.post(config.endpoint.rulesPath, PostRules); app.delete(config.endpoint.rulesPath + '/:id', DelRules); - } /** @@ -88,6 +87,3 @@ function AddTo(app) { * @param {Object} Express application */ module.exports.AddTo = AddTo; - - - diff --git a/lib/routes/versionController.js b/lib/routes/versionController.js index bce1d495..f97256f9 100644 --- a/lib/routes/versionController.js +++ b/lib/routes/versionController.js @@ -30,14 +30,14 @@ var config = require('../../config'), versionObj = { name: packageObj.name, description: packageObj.description, - version: packageObj.version + version: packageObj.version, }, logLevels = { - 'DEBUG': 'DEBUG', - 'INFO': 'INFO', - 'WARN': 'WARN', - 'ERROR': 'ERROR', - 'FATAL': 'FATAL' + DEBUG: 'DEBUG', + INFO: 'INFO', + WARN: 'WARN', + ERROR: 'ERROR', + FATAL: 'FATAL', }, errors = {}, currentLevel = config.logLevel; @@ -53,8 +53,7 @@ function changeLogLevel(req, resp) { logger.setLevel(newLevel); currentLevel = newLevel; resp.status(200).end(); - } - else { + } else { logger.error({}, 'invalid log level ' + req.query.level); myutils.respond(resp, new errors.InvalidLogLevel()); } @@ -62,7 +61,7 @@ function changeLogLevel(req, resp) { function getLogLevel(req, resp) { logger.debug({}, 'getting log level'); - myutils.respondWOMetrics(resp, null, {'level': currentLevel}, /* withCount */ false, /* raw */ true); + myutils.respondWOMetrics(resp, null, { level: currentLevel }, /* withCount */ false, /* raw */ true); } function AddTo(app) { app.get(config.endpoint.versionPath, version); diff --git a/lib/routes/visualRulesController.js b/lib/routes/visualRulesController.js index b0b6193c..89d823a7 100644 --- a/lib/routes/visualRulesController.js +++ b/lib/routes/visualRulesController.js @@ -44,7 +44,7 @@ function GetVR(req, resp) { var rule = { name: req.params.id, subservice: req.subservice, - service: req.service + service: req.service, }; visualRules.Find(rule, function(err, data) { if (!err && data) { @@ -62,7 +62,6 @@ function PostVR(req, resp) { metrics.IncMetrics(req.service, req.subservice, metrics.ruleCreation); visualRules.Save(req.body, function(err, data) { - if (err) { metrics.IncMetrics(req.service, req.subservice, metrics.failedRuleCreation); } else { @@ -83,7 +82,7 @@ function DelVR(req, resp) { var rule = { name: req.params.id, subservice: req.subservice, - service: req.service + service: req.service, }; metrics.IncMetrics(req.service, req.subservice, metrics.ruleDelete); diff --git a/test/component/actions_elapsed_test.js b/test/component/actions_elapsed_test.js index 1f4c74c4..0f485681 100644 --- a/test/component/actions_elapsed_test.js +++ b/test/component/actions_elapsed_test.js @@ -23,8 +23,7 @@ 'use strict'; -var - async = require('async'), +var async = require('async'), should = require('should'), util = require('util'), clients = require('../utils/clients'), @@ -39,57 +38,60 @@ describe('Actions elapsed', function() { describe('#action.Do()', function() { var executedActions; - it('should serialize actions, executing only one when there is an elapsed condition,' + - ' even when arriving "together"', function(done) { - var rule = utilsT.loadExample('./test/data/good_vrs/time_card.json'), - action = utilsT.loadExample('./test/data/good_actions/action_sms.json'), - date = new Date(); - action.ev.id += date.getTime(); - utilsT.getConfig().sms.URL = util.format('http://localhost:%s', utilsT.fakeHttpServerPort); + it( + 'should serialize actions, executing only one when there is an elapsed condition,' + + ' even when arriving "together"', + function(done) { + var rule = utilsT.loadExample('./test/data/good_vrs/time_card.json'), + action = utilsT.loadExample('./test/data/good_actions/action_sms.json'), + date = new Date(); + action.ev.id += date.getTime(); + utilsT.getConfig().sms.URL = util.format('http://localhost:%s', utilsT.fakeHttpServerPort); + async.series( + [ + function(callback) { + clients.PostVR(rule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 201); - async.series([ - function(callback) { - clients.PostVR(rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 201); - - utilsT.setServerCallback(function(req, resp) { - executedActions++; - resp.end('ok ' + executedActions + ' executedActions'); - }); - executedActions = 0; - return callback(null); - }); - }, - function(callback) { - clients.PostAction(action, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(null); - }); - }, - function(callback) { - clients.PostAction(action, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(null); - }); - }, - function(callback) { - clients.PostAction(action, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - setTimeout(callback, EXEC_GRACE_PERIOD); - }); - }, - function(callback) { - executedActions.should.be.equal(1); - return callback(null); - } - ], done); - }); - + utilsT.setServerCallback(function(req, resp) { + executedActions++; + resp.end('ok ' + executedActions + ' executedActions'); + }); + executedActions = 0; + return callback(null); + }); + }, + function(callback) { + clients.PostAction(action, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(null); + }); + }, + function(callback) { + clients.PostAction(action, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(null); + }); + }, + function(callback) { + clients.PostAction(action, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + setTimeout(callback, EXEC_GRACE_PERIOD); + }); + }, + function(callback) { + executedActions.should.be.equal(1); + return callback(null); + }, + ], + done + ); + } + ); }); }); - diff --git a/test/component/actions_test.js b/test/component/actions_test.js index 389ce6e6..e98f8d3c 100644 --- a/test/component/actions_test.js +++ b/test/component/actions_test.js @@ -23,8 +23,7 @@ 'use strict'; -var - async = require('async'), +var async = require('async'), should = require('should'), util = require('util'), clients = require('../utils/clients'), @@ -44,146 +43,164 @@ describe('Actions', function() { describe('#PostAction()', function() { it('should return ok with a valid action', function(done) { var cases = utilsT.loadDirExamples('./test/data/good_actions'); - async.eachSeries(cases, function(c, callback) { - clients.PostAction(c.object, function(error, data) { + async.eachSeries( + cases, + function(c, callback) { + clients.PostAction(c.object, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(null); + }); + }, + function(error) { should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(null); - }); - }, function(error) { - should.not.exist(error); - done(); - }); + done(); + } + ); }); it('should return ok with a valid action with a rule for sms', function(done) { var rule = utilsT.loadExample('./test/data/good_rules/blood_rule_sms.json'), action = utilsT.loadExample('./test/data/good_actions/action_sms.json'); utilsT.getConfig().sms.URL = 'http://thisshouldbenothingnotaCB'; - async.series([ - function(callback) { - clients.PostRule(rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(null); - }); - }, - function(callback) { - clients.PostAction(action, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(); - }); - } - ], done); + async.series( + [ + function(callback) { + clients.PostRule(rule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(null); + }); + }, + function(callback) { + clients.PostAction(action, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(); + }); + }, + ], + done + ); }); it('should return ok with a valid action with a rule for update', function(done) { var rule = utilsT.loadExample('./test/data/good_rules/blood_rule_update.json'), action = utilsT.loadExample('./test/data/good_actions/action_update.json'); utilsT.getConfig().orion.URL = 'http://thisshouldbenothingnotaCB'; - async.series([ - function(callback) { - clients.PostRule(rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(null); - }); - }, - function(callback) { - clients.PostAction(action, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(); - }); - } - ], done); + async.series( + [ + function(callback) { + clients.PostRule(rule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(null); + }); + }, + function(callback) { + clients.PostAction(action, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(); + }); + }, + ], + done + ); }); it('should return ok with a valid action with a rule for email', function(done) { var rule = utilsT.loadExample('./test/data/good_rules/blood_rule_email.json'), action = utilsT.loadExample('./test/data/good_actions/action_email.json'); utilsT.getConfig().smtp.host = 'averyfarwayhosthatnotexist'; - async.series([ - function(callback) { - clients.PostRule(rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(null); - }); - }, - function(callback) { - utilsT.setServerCallback(function(req, resp) { - resp.end('ok'); - return done(); - }); - callback(); - }, - function(callback) { - clients.PostAction(action, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(); - }); - } - ], done); + async.series( + [ + function(callback) { + clients.PostRule(rule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(null); + }); + }, + function(callback) { + utilsT.setServerCallback(function(req, resp) { + resp.end('ok'); + return done(); + }); + callback(); + }, + function(callback) { + clients.PostAction(action, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(); + }); + }, + ], + done + ); }); it('should return ok with a valid action with a rule for post', function(done) { var rule = utilsT.loadExample('./test/data/good_rules/blood_rule_post.json'), action = utilsT.loadExample('./test/data/good_actions/action_post.json'); - async.series([ - function(callback) { - clients.PostRule(rule, function(error, data) { + async.series( + [ + function(callback) { + clients.PostRule(rule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(null); + }); + }, + function(callback) { + utilsT.setServerCallback(function(req, resp) { + resp.end('ok'); + return done(); + }); + callback(); + }, + function(callback) { + clients.PostAction(action, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(); + }); + }, + ], + done + ); + }); + it('should return an error if rule name is missing', function(done) { + var cases = [{}, { id: 'something' }]; + async.eachSeries( + cases, + function(c, callback) { + clients.PostAction(c, function(error, data) { should.not.exist(error); - data.should.have.property('statusCode', 200); + data.should.have.property('statusCode', 400); return callback(null); }); }, - function(callback) { - utilsT.setServerCallback(function(req, resp) { - resp.end('ok'); - return done(); - }); - callback(); - }, - function(callback) { - clients.PostAction(action, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(); - }); - } - ], done); - }); - it('should return an error if rule name is missing', function(done) { - var cases = [ - {}, - {id: 'something'} - ]; - async.eachSeries(cases, function(c, callback) { - clients.PostAction(c, function(error, data) { + function(error) { should.not.exist(error); - data.should.have.property('statusCode', 400); - return callback(null); - }); - }, function(error) { - should.not.exist(error); - done(); - }); + done(); + } + ); }); it('should return an error when executing an action without rule name', function(done) { - var cases = [ - {}, - {id: 'something'} - ]; - async.eachSeries(cases, function(c, callback) { - actions.Do(c, function(error) { - should.exist(error); - callback(null); - }); - }, function(error) { - should.not.exist(error); - done(); - }); + var cases = [{}, { id: 'something' }]; + async.eachSeries( + cases, + function(c, callback) { + actions.Do(c, function(error) { + should.exist(error); + callback(null); + }); + }, + function(error) { + should.not.exist(error); + done(); + } + ); }); }); @@ -196,108 +213,120 @@ describe('Actions', function() { date = new Date(); action.ev.id += date.getTime(); utilsT.getConfig().sms.URL = util.format('http://localhost:%s', utilsT.fakeHttpServerPort); - async.series([ - function(callback) { - clients.PostVR(rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 201); - return callback(null); - }); - }, - function(callback) { - clients.PostAction(action, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - setTimeout(callback, EXEC_GRACE_PERIOD); - }); - }, - function(callback) { - executionsStore.LastTime({ - 'event': { - service: action.ev.service, - subservice: action.ev.subservice, - ruleName: rule.name, - id: action.ev.id - }, - 'action': {index: 0} - }, - - function(error, time) { + async.series( + [ + function(callback) { + clients.PostVR(rule, function(error, data) { should.not.exist(error); - time.should.not.be.equal(0); - time.should.be.lessThan(Date.now()); - time.should.be.greaterThan(start); - return callback(); + data.should.have.property('statusCode', 201); + return callback(null); }); - } - ], done); + }, + function(callback) { + clients.PostAction(action, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + setTimeout(callback, EXEC_GRACE_PERIOD); + }); + }, + function(callback) { + executionsStore.LastTime( + { + event: { + service: action.ev.service, + subservice: action.ev.subservice, + ruleName: rule.name, + id: action.ev.id, + }, + action: { index: 0 }, + }, + + function(error, time) { + should.not.exist(error); + time.should.not.be.equal(0); + time.should.be.lessThan(Date.now()); + time.should.be.greaterThan(start); + return callback(); + } + ); + }, + ], + done + ); }); - it('should not execute an action when has been executed too recently', function(done) { + it('should not execute an action when has been executed too recently', function(done) { var rule = utilsT.loadExample('./test/data/good_vrs/time_card.json'), action = utilsT.loadExample('./test/data/good_actions/action_sms.json'), lastTime = 0, date = new Date(); action.ev.id += date.getTime(); utilsT.getConfig().sms.URL = util.format('http://localhost:%s', utilsT.fakeHttpServerPort); - async.series([ - function(callback) { - clients.PostVR(rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 201); - return callback(null); - }); - }, - function(callback) { - clients.PostAction(action, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - setTimeout(callback, EXEC_GRACE_PERIOD); - }); - }, - function(callback) { - executionsStore.LastTime({ - 'event': { - service: action.ev.service, - subservice: action.ev.subservice, - ruleName: rule.name, - id: action.ev.id - }, - 'action': {index: 0} - }, - function(error, time) { + async.series( + [ + function(callback) { + clients.PostVR(rule, function(error, data) { should.not.exist(error); - time.should.not.be.equal(0); - time.should.be.lessThan(Date.now()); - time.should.be.greaterThan(start); - lastTime = time; - return callback(); + data.should.have.property('statusCode', 201); + return callback(null); }); - }, - function(callback) { - clients.PostAction(action, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - setTimeout(callback, EXEC_GRACE_PERIOD); - }); - }, - function(callback) { - executionsStore.LastTime({ - 'event': { - service: action.ev.service, - subservice: action.ev.subservice, - ruleName: rule.name, - id: action.ev.id + }, + function(callback) { + clients.PostAction(action, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + setTimeout(callback, EXEC_GRACE_PERIOD); + }); + }, + function(callback) { + executionsStore.LastTime( + { + event: { + service: action.ev.service, + subservice: action.ev.subservice, + ruleName: rule.name, + id: action.ev.id, + }, + action: { index: 0 }, }, - 'action': {index: 0} - }, - function(error, time) { + function(error, time) { + should.not.exist(error); + time.should.not.be.equal(0); + time.should.be.lessThan(Date.now()); + time.should.be.greaterThan(start); + lastTime = time; + return callback(); + } + ); + }, + function(callback) { + clients.PostAction(action, function(error, data) { should.not.exist(error); - time.should.be.equal(lastTime); - return callback(); + data.should.have.property('statusCode', 200); + setTimeout(callback, EXEC_GRACE_PERIOD); }); - } - ], done); + }, + function(callback) { + executionsStore.LastTime( + { + event: { + service: action.ev.service, + subservice: action.ev.subservice, + ruleName: rule.name, + id: action.ev.id, + }, + action: { index: 0 }, + }, + function(error, time) { + should.not.exist(error); + time.should.be.equal(lastTime); + return callback(); + } + ); + }, + ], + done + ); }); it('should not execute an action when has been triggered with the same correlator', function(done) { @@ -311,8 +340,12 @@ describe('Actions', function() { options.headers[constants.SERVICE_HEADER] = config.DEFAULT_SERVICE; options.headers[constants.SUBSERVICE_HEADER] = config.DEFAULT_SUBSERVICE; options.headers[constants.CORRELATOR_HEADER] = 'thesamecorrelator'; - options.url = util.format('http://%s:%s%s', config.endpoint.host, - config.endpoint.port, config.endpoint.actionsPath); + options.url = util.format( + 'http://%s:%s%s', + config.endpoint.host, + config.endpoint.port, + config.endpoint.actionsPath + ); options.body = action; options.json = true; @@ -320,36 +353,41 @@ describe('Actions', function() { if (error) { return callback(error, null); } - if (response.headers['content-type'] === 'application/json; charset=utf-8' && - typeof body === 'string') { + if ( + response.headers['content-type'] === 'application/json; charset=utf-8' && + typeof body === 'string' + ) { body = JSON.parse(body); } - return callback(error, {statusCode: response.statusCode, body: body, headers: response.headers}); + return callback(error, { statusCode: response.statusCode, body: body, headers: response.headers }); }); } - async.series([ - function(callback) { - clients.PostVR(rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 201); - return callback(null); - }); - }, - function(callback) { - postAction(action, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - setTimeout(callback, EXEC_GRACE_PERIOD); - }); - }, - function(callback) { - postAction(action, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 500); - callback(); - }); - } - ], done); + async.series( + [ + function(callback) { + clients.PostVR(rule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 201); + return callback(null); + }); + }, + function(callback) { + postAction(action, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + setTimeout(callback, EXEC_GRACE_PERIOD); + }); + }, + function(callback) { + postAction(action, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 500); + callback(); + }); + }, + ], + done + ); }); }); }); diff --git a/test/component/auth_test.js b/test/component/auth_test.js index 7f2ffc7f..aa76ed4e 100644 --- a/test/component/auth_test.js +++ b/test/component/auth_test.js @@ -23,8 +23,7 @@ 'use strict'; -var - async = require('async'), +var async = require('async'), should = require('should'), util = require('util'), clients = require('../utils/clients'), @@ -51,15 +50,52 @@ describe('Auth', function() { if (error) { return done(error); } - async.series([ + async.series( + [ + function(callback) { + var respCodes = [401, 201, 200]; + utilsT.setServerCallback(function(req, resp) { + resp.writeHead(respCodes.shift(), { 'x-subject-token': 'thisIsAnAccessToken2' }); + resp.end('ok'); + if (respCodes.length === 0) { + // all requests done + updateDone.emit('updated_renew', null); + } + }); + return callback(); + }, + function(callback) { + clients.PostAction(action, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(); + }); + }, + ], + function(error) { + if (error) { + return done(error); + } + } + ); + }); + async.series( + [ + function(callback) { + clients.PostRule(rule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(); + }); + }, function(callback) { - var respCodes = [401, 201, 200]; + var respCodes = [201, 200]; utilsT.setServerCallback(function(req, resp) { - resp.writeHead(respCodes.shift(), - {'x-subject-token': 'thisIsAnAccessToken2'}); + resp.writeHead(respCodes.shift(), { 'x-subject-token': 'thisIsAnAccessToken' }); resp.end('ok'); - if (respCodes.length === 0) { // all requests done - updateDone.emit('updated_renew', null); + if (respCodes.length === 0) { + // all requests done + updateDone.emit('updated_first', null); } }); return callback(); @@ -70,45 +106,14 @@ describe('Auth', function() { data.should.have.property('statusCode', 200); return callback(); }); - } - ], function(error) { + }, + ], + function(error) { if (error) { return done(error); } - }); - }); - async.series([ - function(callback) { - clients.PostRule(rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(); - }); - }, - function(callback) { - var respCodes = [201, 200]; - utilsT.setServerCallback(function(req, resp) { - resp.writeHead(respCodes.shift(), - {'x-subject-token': 'thisIsAnAccessToken'}); - resp.end('ok'); - if (respCodes.length === 0) { // all requests done - updateDone.emit('updated_first', null); - } - }); - return callback(); - }, - function(callback) { - clients.PostAction(action, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(); - }); } - ], function(error) { - if (error) { - return done(error); - } - }); + ); }); }); }); diff --git a/test/component/config.js b/test/component/config.js index f767c4ef..5bcf3404 100644 --- a/test/component/config.js +++ b/test/component/config.js @@ -32,34 +32,41 @@ var async = require('async'), function postRuleOK(done) { var cases = utilsT.loadDirExamples('./test/data/good_rules'); utilsT.getConfig().nextCore = {}; - async.eachSeries(cases, function(c, callback) { - clients.PostRule(c.object, function(error, data) { + async.eachSeries( + cases, + function(c, callback) { + clients.PostRule(c.object, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(null); + }); + }, + function(error) { should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(null); - }); - }, function(error) { - should.not.exist(error); - return done(); - }); + return done(); + } + ); } function postNoticeOK(done) { var cases = utilsT.loadDirExamples('./test/data/good_notices'); - async.eachSeries(cases, function(c, callback) { - clients.PostNotice(c.object, function(error, data) { + async.eachSeries( + cases, + function(c, callback) { + clients.PostNotice(c.object, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(null); + }); + }, + function(error) { should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(null); - }); - }, function(error) { - should.not.exist(error); - done(); - }); + done(); + } + ); } describe('Config', function() { - beforeEach(testEnv.commonBeforeEach); afterEach(testEnv.commonAfterEach); @@ -74,21 +81,21 @@ describe('Config', function() { it('should return OK when posting a notice', postNoticeOK); }); describe('#With next core only for rules', function() { - utilsT.getConfig().nextCore = {rulesURL: 'http://averyfarwayhost:1234'}; + utilsT.getConfig().nextCore = { rulesURL: 'http://averyfarwayhost:1234' }; it('should return OK when posting a rule', postRuleOK); it('should return OK when posting a notice', postNoticeOK); }); describe('#With next core only for notices', function() { - utilsT.getConfig().nextCore = {noticesURL: 'http://averyfarwayhost:1234'}; + utilsT.getConfig().nextCore = { noticesURL: 'http://averyfarwayhost:1234' }; it('should return OK when posting a rule', postRuleOK); it('should return OK when posting a notice', postNoticeOK); }); describe('#With next core for notices and rules', function() { utilsT.getConfig().nextCore = { noticesURL: 'http://averyfarwayhost:1234', - rulesURL: 'http://averyfarwayhost:1234'}; + rulesURL: 'http://averyfarwayhost:1234', + }; it('should return OK when posting a rule', postRuleOK); it('should return OK when posting a notice', postNoticeOK); }); }); - diff --git a/test/component/db_test.js b/test/component/db_test.js index 64ceede3..d51b7959 100644 --- a/test/component/db_test.js +++ b/test/component/db_test.js @@ -43,9 +43,6 @@ describe('Db', function() { should.not.exist(database); done(); }); - }); }); }); - - diff --git a/test/component/error_in_axn.js b/test/component/error_in_axn.js index dddbdfd4..7cdd0842 100644 --- a/test/component/error_in_axn.js +++ b/test/component/error_in_axn.js @@ -23,8 +23,7 @@ 'use strict'; -var - async = require('async'), +var async = require('async'), should = require('should'), clients = require('../utils/clients'), utilsT = require('../utils/utilsT'), @@ -37,60 +36,71 @@ describe('Actions', function() { afterEach(testEnv.commonAfterEach); describe('#PostAction()', function() { - it('should not keep invalid actions in queue', function(done) { var cases = utilsT.loadDirExamples('./test/data/error_in_axn_rules/'), action = utilsT.loadExample('./test/data/good_actions/action_sms.json'); - async.eachSeries(cases, function(c, callbackES) { - var rule = c.object; - // To be sure it's the same name in rule and action - action.ruleName = rule.name; - action.ev.id = 'device_err_axn'; - action.ev.type = 'type_err_axn'; - async.series([ - function(callback) { - clients.PostRule(rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(null); - }); - }, - function(callback) { - clients.PostAction(action, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(); - }); - }, - function(callback) { - clients.PostAction(action, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(); - }); - }, - function(callback) { - clients.PostAction(action, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(); - }); - }, - function(callback) { - setTimeout(function() { - var array = actions.getInProcessArray(config.DEFAULT_SERVICE, config.DEFAULT_SUBSERVICE, - rule.name, action.ev.id, action.ev.type); - // Should not be any action in queue - should.equal(array.length(), 0); - return callback(); - }, 100); - } - ], callbackES); - }, function(error) { - should.not.exist(error); - done(); - }); + async.eachSeries( + cases, + function(c, callbackES) { + var rule = c.object; + // To be sure it's the same name in rule and action + action.ruleName = rule.name; + action.ev.id = 'device_err_axn'; + action.ev.type = 'type_err_axn'; + async.series( + [ + function(callback) { + clients.PostRule(rule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(null); + }); + }, + function(callback) { + clients.PostAction(action, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(); + }); + }, + function(callback) { + clients.PostAction(action, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(); + }); + }, + function(callback) { + clients.PostAction(action, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(); + }); + }, + function(callback) { + setTimeout(function() { + var array = actions.getInProcessArray( + config.DEFAULT_SERVICE, + config.DEFAULT_SUBSERVICE, + rule.name, + action.ev.id, + action.ev.type + ); + // Should not be any action in queue + should.equal(array.length(), 0); + return callback(); + }, 100); + }, + ], + callbackES + ); + }, + function(error) { + should.not.exist(error); + done(); + } + ); }); }); }); diff --git a/test/component/loglevel_test.js b/test/component/loglevel_test.js index 6e05c183..162df687 100644 --- a/test/component/loglevel_test.js +++ b/test/component/loglevel_test.js @@ -35,54 +35,64 @@ describe('LogLevel', function() { describe('#PutLoglevel()', function() { it('should return ok for valid log levels', function(done) { var levels = ['FATAL', 'ERROR', 'WARN', 'INFO', 'DEBUG']; - async.eachSeries(levels, function(level, callback) { - clients.PutLogLevel(level, function(error, data) { + async.eachSeries( + levels, + function(level, callback) { + clients.PutLogLevel(level, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(null); + }); + }, + function(error) { should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(null); - }); - }, function(error) { - should.not.exist(error); - done(); - }); + done(); + } + ); }); it('should return bad request for invalid log levels', function(done) { var levels = ['FANTASTIC', 'error', '', 'x']; - async.eachSeries(levels, function(level, callback) { - clients.PutLogLevel(level, function(error, data) { + async.eachSeries( + levels, + function(level, callback) { + clients.PutLogLevel(level, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 400); + data.should.have.property('body'); + data.body.should.have.property('error', 'invalid log level'); + return callback(null); + }); + }, + function(error) { should.not.exist(error); - data.should.have.property('statusCode', 400); - data.should.have.property('body'); - data.body.should.have.property('error', 'invalid log level'); - return callback(null); - }); - }, function(error) { - should.not.exist(error); - done(); - }); + done(); + } + ); }); }); describe('#GetLoglevel()', function() { it('should return the current log level', function(done) { var levels = ['FATAL', 'ERROR', 'WARN', 'INFO', 'DEBUG']; - async.eachSeries(levels, function(level, callback) { - clients.PutLogLevel(level, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - clients.GetLogLevel(function(error, response) { + async.eachSeries( + levels, + function(level, callback) { + clients.PutLogLevel(level, function(error, data) { should.not.exist(error); - response.should.have.property('statusCode', 200); - response.should.have.body; - response.body.should.have.property('level', level); - callback(null); + data.should.have.property('statusCode', 200); + clients.GetLogLevel(function(error, response) { + should.not.exist(error); + response.should.have.property('statusCode', 200); + response.should.have.body; + response.body.should.have.property('level', level); + callback(null); + }); }); - - }); - }, function(error) { - should.not.exist(error); - done(); - }); + }, + function(error) { + should.not.exist(error); + done(); + } + ); }); }); }); - diff --git a/test/component/myutils_test.js b/test/component/myutils_test.js index 44472eaa..3134eefb 100644 --- a/test/component/myutils_test.js +++ b/test/component/myutils_test.js @@ -31,7 +31,7 @@ describe('Myutils', function() { describe('When there are not variables', function() { it('should return the same string passed', function() { var str = 'a string without vars', - map = {without: 'XXXX', vars: 'YYYYY'}, + map = { without: 'XXXX', vars: 'YYYYY' }, newStr; newStr = myutils.expandVar(str, map); should.exist(newStr); @@ -43,7 +43,7 @@ describe('Myutils', function() { describe('When there is a network problem', function() { it('should return error', function(done) { var url = 'http://incredibleifthishostexistsicantbelievemyeyes.io'; - myutils.requestHelper('get', {url: url}, function(error) { + myutils.requestHelper('get', { url: url }, function(error) { should.exist(error); error.should.be.an.Error; }); @@ -52,4 +52,3 @@ describe('Myutils', function() { }); }); }); - diff --git a/test/component/notices_test.js b/test/component/notices_test.js index 6a103009..79179729 100644 --- a/test/component/notices_test.js +++ b/test/component/notices_test.js @@ -40,29 +40,37 @@ describe('Notices', function() { describe('#PosNotice()', function() { it('Good notices should be good', function(done) { var cases = utilsT.loadDirExamples('./test/data/good_notices'); - async.eachSeries(cases, function(c, callback) { - clients.PostNotice(c.object, function(error, data) { + async.eachSeries( + cases, + function(c, callback) { + clients.PostNotice(c.object, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(null); + }); + }, + function(error) { should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(null); - }); - }, function(error) { - should.not.exist(error); - done(); - }); + done(); + } + ); }); it('Invalid JSON should be an error', function(done) { var cases = ['', '{', '[1,2,]']; - async.eachSeries(cases, function(c, callback) { - clients.PostNotice(c.object, function(error, data) { + async.eachSeries( + cases, + function(c, callback) { + clients.PostNotice(c.object, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 400); + return callback(null); + }); + }, + function(error) { should.not.exist(error); - data.should.have.property('statusCode', 400); - return callback(null); - }); - }, function(error) { - should.not.exist(error); - done(); - }); + done(); + } + ); }); it('id as an attribute should be an error', function(done) { var n = utilsT.loadExample('./test/data/bad_notices/notice_id_as_attr.json'); @@ -84,16 +92,20 @@ describe('Notices', function() { var cases = utilsT.loadDirExamples('./test/data/good_notices'); utilsT.setServerCode(400); utilsT.setServerMessage('what a pity!'); - async.eachSeries(cases, function(c, callback) { - clients.PostNotice(c.object, function(error, data) { + async.eachSeries( + cases, + function(c, callback) { + clients.PostNotice(c.object, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 500); + return callback(null); + }); + }, + function(error) { should.not.exist(error); - data.should.have.property('statusCode', 500); - return callback(null); - }); - }, function(error) { - should.not.exist(error); - done(); - }); + done(); + } + ); }); it('several servicepaths should be OK', function(done) { var n = utilsT.loadExample('./test/data/notices_several_sp/several_servicepath.json'), @@ -102,22 +114,25 @@ describe('Notices', function() { options.headers = {}; options.headers[constants.SERVICE_HEADER] = config.DEFAULT_SERVICE; options.headers[constants.SUBSERVICE_HEADER] = '/A,/B,/C'; - options.url = util.format('http://%s:%s%s', + options.url = util.format( + 'http://%s:%s%s', config.endpoint.host, config.endpoint.port, - config.endpoint.noticesPath); + config.endpoint.noticesPath + ); options.json = n; request.post(options, function localPostNotice(error, response, body) { should.not.exist(error); - if (response.headers['content-type'] === 'application/json; charset=utf-8' && - typeof body === 'string') { + if ( + response.headers['content-type'] === 'application/json; charset=utf-8' && + typeof body === 'string' + ) { body = JSON.parse(body); } - data = {statusCode: response.statusCode, body: body, headers: response.headers}; + data = { statusCode: response.statusCode, body: body, headers: response.headers }; data.should.have.property('statusCode', 200); return done(); }); }); }); }); - diff --git a/test/component/nsr_test.js b/test/component/nsr_test.js index 8e87a8f9..8470fac5 100644 --- a/test/component/nsr_test.js +++ b/test/component/nsr_test.js @@ -39,24 +39,24 @@ describe('Entity', function() { describe('#alertFunc()', function() { var entities = [ { - _id: {id: 'eA', servicePath: DEFAULT_SUBSERVICE, type: 'type e1'}, + _id: { id: 'eA', servicePath: DEFAULT_SUBSERVICE, type: 'type e1' }, attrs: { - 'at': {value: 1, modDate: 0}, - 'other': {value: 'this is a value', modDate: 0} - } + at: { value: 1, modDate: 0 }, + other: { value: 'this is a value', modDate: 0 }, + }, }, { - _id: {id: 'eB', servicePath: DEFAULT_SUBSERVICE, type: ''}, + _id: { id: 'eB', servicePath: DEFAULT_SUBSERVICE, type: '' }, attrs: { - 'at': {value: 2, modDate: Date.now() / 1000 - 30 * 60} - } + at: { value: 2, modDate: Date.now() / 1000 - 30 * 60 }, + }, }, { - _id: {id: 'eC', servicePath: DEFAULT_SUBSERVICE}, + _id: { id: 'eC', servicePath: DEFAULT_SUBSERVICE }, attrs: { - 'at': {value: 3, modDate: -1} - } - } + at: { value: 3, modDate: -1 }, + }, + }, ], checkInterval = 1, rule = utilsT.loadExample('./test/data/no_signal/generic_nonsignal.json'); @@ -67,49 +67,54 @@ describe('Entity', function() { this.timeout(2 * checkInterval * 60e3); it('should return silent entities', function(done) { var start = Date.now(); - async.series([ - function(cb) { - utilsT.createEntitiesCollection.bind({}, DEFAULT_SERVICE), - async.eachSeries(entities, utilsT.addEntity.bind({}, DEFAULT_SERVICE), cb); - }, - function(callback) { - clients.PostVR(rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 201); - return callback(null); - }); - }, - function(cb) { - // wait checker set at AddNSRule to wake up, created by POST of VR - setTimeout(cb, 1.25 * checkInterval * 60e3); - }, - function(cb) { - async.eachSeries(entities, function(entity) { - executionsStore.LastTime( - { - 'event': { - service: DEFAULT_SERVICE, - subservice: DEFAULT_SUBSERVICE, - ruleName: rule.name, - id: entity._id.id - }, - 'action': {index: 0} + async.series( + [ + function(cb) { + utilsT.createEntitiesCollection.bind({}, DEFAULT_SERVICE), + async.eachSeries(entities, utilsT.addEntity.bind({}, DEFAULT_SERVICE), cb); + }, + function(callback) { + clients.PostVR(rule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 201); + return callback(null); + }); + }, + function(cb) { + // wait checker set at AddNSRule to wake up, created by POST of VR + setTimeout(cb, 1.25 * checkInterval * 60e3); + }, + function(cb) { + async.eachSeries( + entities, + function(entity) { + executionsStore.LastTime( + { + event: { + service: DEFAULT_SERVICE, + subservice: DEFAULT_SUBSERVICE, + ruleName: rule.name, + id: entity._id.id, + }, + action: { index: 0 }, + }, + function(error, time) { + should.not.exist(error); + time.should.not.be.equal(0); + time.should.be.greaterThan(start); + return cb(); + } + ); }, - function(error, time) { - should.not.exist(error); - time.should.not.be.equal(0); - time.should.be.greaterThan(start); - return cb(); - }); - }, cb); - + cb + ); + }, + ], + function(err, results) { + // asserts + done(err); } - ], function(err, results) { - // asserts - done(err); - }); + ); }); - }); }); - diff --git a/test/component/rules_test.js b/test/component/rules_test.js index e30329bf..ea39daae 100644 --- a/test/component/rules_test.js +++ b/test/component/rules_test.js @@ -31,76 +31,90 @@ var async = require('async'), rules = require('../../lib/models/rules'); describe('Rules', function() { - beforeEach(testEnv.commonBeforeEach); afterEach(testEnv.commonAfterEach); describe('#PutRules', function() { it('should return OK when refeshing rules to core', function(done) { var ruleSet = utilsT.loadDirExamples('./test/data/good_rules'); - async.eachSeries(ruleSet, function(c, callback) { - clients.PostRule(c.object, function(error, data) { + async.eachSeries( + ruleSet, + function(c, callback) { + clients.PostRule(c.object, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(null); + }); + }, + function(error) { should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(null); - }); - }, function(error) { - should.not.exist(error); - rules.Refresh(done); - }); + rules.Refresh(done); + } + ); }); }); describe('#PostRule()', function() { it('should return OK when a correct rule is POSTed', function(done) { var cases = utilsT.loadDirExamples('./test/data/good_rules'); - async.eachSeries(cases, function(c, callback) { - clients.PostRule(c.object, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(null); - }); - }, function(error) { - should.not.exist(error); - return done(); - }); - }); - it('should return the same rule was POSTed', function(done) { - var rule = utilsT.loadExample('./test/data/good_rules/blood_rule_sms.json'); - async.series([ - function(callback) { - clients.PostRule(rule, function(error, data) { + async.eachSeries( + cases, + function(c, callback) { + clients.PostRule(c.object, function(error, data) { should.not.exist(error); data.should.have.property('statusCode', 200); return callback(null); }); }, - function(callback) { - clients.GetRule(rule.name, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - data.should.have.property('body'); - data.body.data.should.have.property('name', rule.name); - data.body.data.should.have.property('text', rule.text); - return callback(); - }); + function(error) { + should.not.exist(error); + return done(); } - ], done); + ); + }); + it('should return the same rule was POSTed', function(done) { + var rule = utilsT.loadExample('./test/data/good_rules/blood_rule_sms.json'); + async.series( + [ + function(callback) { + clients.PostRule(rule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(null); + }); + }, + function(callback) { + clients.GetRule(rule.name, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + data.should.have.property('body'); + data.body.data.should.have.property('name', rule.name); + data.body.data.should.have.property('text', rule.text); + return callback(); + }); + }, + ], + done + ); }); it('should return an error if core endpoint is not working', function(done) { var cases = utilsT.loadDirExamples('./test/data/good_rules'); utilsT.setServerCode(400); utilsT.setServerMessage('what a pity!'); - async.eachSeries(cases, function(c, callback) { - clients.PostRule(c.object, function(error, data) { + async.eachSeries( + cases, + function(c, callback) { + clients.PostRule(c.object, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 500); + return callback(null); + }); + }, + function(error) { should.not.exist(error); - data.should.have.property('statusCode', 500); - return callback(null); - }); - }, function(error) { - should.not.exist(error); - done(); - }); + done(); + } + ); }); it('should return BAD REQUEST when POSTing a rule without name', function(done) { var rule = utilsT.loadExample('./test/data/bad_rules/rule_without_name.json'); @@ -174,7 +188,7 @@ describe('Rules', function() { }); it('should return BAD REQUEST when POSTing a rule with a name that is not a string', function(done) { var rule = utilsT.loadExample('./test/data/bad_rules/rule_without_name.json'); - rule.name = {x: 1}; + rule.name = { x: 1 }; clients.PostRule(rule, function(error, data) { should.not.exist(error); data.should.have.property('statusCode', 400); @@ -191,43 +205,53 @@ describe('Rules', function() { }); it('should return BAD REQUEST when POSTing an existent rule', function(done) { var rule = utilsT.loadExample('./test/data/good_rules/blood_rule_email.json'); - async.series([ - function(callback) { - clients.PostRule(rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(null); - }); - }, - function(callback) { - clients.PostRule(rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 400); - return callback(null); - }); - } - ], done); - }); - it('should return an error when something goes wrong in database', function(done) { - var cases = utilsT.loadDirExamples('./test/data/good_rules'); - async.series([ - utilsT.dropRulesCollection, - function(callback0) { - async.eachSeries(cases, function(c, callback) { - clients.PostRule(c.object, function(error, data) { + async.series( + [ + function(callback) { + clients.PostRule(rule, function(error, data) { should.not.exist(error); - data.should.have.property('statusCode', 500); + data.should.have.property('statusCode', 200); return callback(null); }); - }, function(error) { - should.not.exist(error); - callback0(); - }); + }, + function(callback) { + clients.PostRule(rule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 400); + return callback(null); + }); + }, + ], + done + ); + }); + it('should return an error when something goes wrong in database', function(done) { + var cases = utilsT.loadDirExamples('./test/data/good_rules'); + async.series( + [ + utilsT.dropRulesCollection, + function(callback0) { + async.eachSeries( + cases, + function(c, callback) { + clients.PostRule(c.object, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 500); + return callback(null); + }); + }, + function(error) { + should.not.exist(error); + callback0(); + } + ); + }, + ], + function(error) { + should.not.exist(error); + done(); } - ], function(error) { - should.not.exist(error); - done(); - }); + ); }); }); describe('#DeletetRule()', function() { @@ -240,22 +264,25 @@ describe('Rules', function() { }); it('should be OK to delete an existent rule', function(done) { var rule = utilsT.loadExample('./test/data/good_rules/blood_rule_sms.json'); - async.series([ - function(callback) { - clients.PostRule(rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(null); - }); - }, - function(callback) { - clients.DeleteRule(rule.name, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(); - }); - } - ], done); + async.series( + [ + function(callback) { + clients.PostRule(rule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(null); + }); + }, + function(callback) { + clients.DeleteRule(rule.name, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(); + }); + }, + ], + done + ); }); it('should return an error if core endpoint is not working', function(done) { utilsT.setServerCode(400); @@ -268,24 +295,31 @@ describe('Rules', function() { }); it('should return an error when something goes wrong in database', function(done) { var cases = utilsT.loadDirExamples('./test/data/good_rules'); - async.series([ - utilsT.dropRulesCollection, - function(callback0) { - async.eachSeries(cases, function(c, callback) { - clients.DeleteRule(c.object.name, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 500); - return callback(null); - }); - }, function(error) { - should.not.exist(error); - callback0(); - }); + async.series( + [ + utilsT.dropRulesCollection, + function(callback0) { + async.eachSeries( + cases, + function(c, callback) { + clients.DeleteRule(c.object.name, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 500); + return callback(null); + }); + }, + function(error) { + should.not.exist(error); + callback0(); + } + ); + }, + ], + function(error) { + should.not.exist(error); + done(); } - ], function(error) { - should.not.exist(error); - done(); - }); + ); }); }); describe('#GetRule()', function() { @@ -298,46 +332,54 @@ describe('Rules', function() { }); it('should return OK when the rule exist', function(done) { var rule = utilsT.loadExample('./test/data/good_rules/blood_rule_sms.json'); - async.series([ - function(callback) { - clients.PostRule(rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(null); - }); - }, - function(callback) { - clients.GetRule(rule.name, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(); - }); - } - ], done); - - }); - it('should return an error when something goes wrong in database', function(done) { - var cases = utilsT.loadDirExamples('./test/data/good_rules'); - async.series([ - utilsT.dropRulesCollection, - function(callback0) { - async.eachSeries(cases, function(c, callback) { - clients.GetRule(c.object.name, function(error, data) { + async.series( + [ + function(callback) { + clients.PostRule(rule, function(error, data) { should.not.exist(error); - data.should.have.property('statusCode', 500); + data.should.have.property('statusCode', 200); return callback(null); }); - }, function(error) { - should.not.exist(error); - callback0(); - }); + }, + function(callback) { + clients.GetRule(rule.name, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(); + }); + }, + ], + done + ); + }); + it('should return an error when something goes wrong in database', function(done) { + var cases = utilsT.loadDirExamples('./test/data/good_rules'); + async.series( + [ + utilsT.dropRulesCollection, + function(callback0) { + async.eachSeries( + cases, + function(c, callback) { + clients.GetRule(c.object.name, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 500); + return callback(null); + }); + }, + function(error) { + should.not.exist(error); + callback0(); + } + ); + }, + ], + function(error) { + should.not.exist(error); + done(); } - ], function(error) { - should.not.exist(error); - done(); - }); + ); }); - }); describe('#GetAllRules()', function() { it('should return an empty set when there are no rules', function(done) { @@ -348,19 +390,22 @@ describe('Rules', function() { }); }); it('should return an error when something goes wrong in database', function(done) { - async.series([ - utilsT.dropRulesCollection, - function(callback) { - clients.GetAllRules(function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 500); - return callback(null); - }); + async.series( + [ + utilsT.dropRulesCollection, + function(callback) { + clients.GetAllRules(function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 500); + return callback(null); + }); + }, + ], + function(error) { + should.not.exist(error); + done(); } - ], function(error) { - should.not.exist(error); - done(); - }); + ); }); }); }); diff --git a/test/component/version_test.js b/test/component/version_test.js index 98e01822..0eb4f5f7 100644 --- a/test/component/version_test.js +++ b/test/component/version_test.js @@ -35,7 +35,8 @@ describe('Version', function() { describe('#GetVersion()', function() { it('should return version in package.json', function(done) { var packageObj = JSON.parse(fs.readFileSync('package.json')), - body, obj; + body, + obj; clients.GetVersion(function(error, data) { should.not.exist(error); data.should.have.property('statusCode', 200); @@ -50,4 +51,3 @@ describe('Version', function() { }); }); }); - diff --git a/test/component/visualrules_test.js b/test/component/visualrules_test.js index 17255991..e2fca59b 100644 --- a/test/component/visualrules_test.js +++ b/test/component/visualrules_test.js @@ -30,76 +30,94 @@ var async = require('async'), testEnv = require('../utils/testEnvironment'); describe('VisualRules', function() { - beforeEach(testEnv.commonBeforeEach); afterEach(testEnv.commonAfterEach); describe('#PostVR()', function() { it('should return ok when posting good rules', function(done) { var cases = utilsT.loadDirExamples('./test/data/good_vrs'); - async.eachSeries(cases, function(c, callback) { - clients.PostVR(c.object, function(error, data) { + async.eachSeries( + cases, + function(c, callback) { + clients.PostVR(c.object, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 201); + return callback(null); + }); + }, + function(error) { should.not.exist(error); - data.should.have.property('statusCode', 201); - return callback(null); - }); - }, function(error) { - should.not.exist(error); - return done(); - }); + return done(); + } + ); }); it('should return error when posting bad rules', function(done) { var cases = utilsT.loadDirExamples('./test/data/bad_vrs'); - async.eachSeries(cases, function(c, callback) { - clients.PostVR(c.object, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 400); - return callback(null); - }); - }, function(error) { - should.not.exist(error); - return done(); - }); - }); - it('should return an error when core-endpoint is not working', function(done) { - var cases = utilsT.loadDirExamples('./test/data/good_vrs'); - utilsT.setServerCode(400); - utilsT.setServerMessage('what a pity!'); - async.eachSeries(cases, function(c, callback) { - if (c.object.text) { + async.eachSeries( + cases, + function(c, callback) { clients.PostVR(c.object, function(error, data) { should.not.exist(error); - data.should.have.property('statusCode', 500); + data.should.have.property('statusCode', 400); return callback(null); }); - } else { - return callback(null); + }, + function(error) { + should.not.exist(error); + return done(); } - }, function(error) { - should.not.exist(error); - done(); - }); + ); }); - it('should return an error when something goes wrong in database', function(done) { + it('should return an error when core-endpoint is not working', function(done) { var cases = utilsT.loadDirExamples('./test/data/good_vrs'); - async.series([ - utilsT.dropRulesCollection, - function(callback0) { - async.eachSeries(cases, function(c, callback) { + utilsT.setServerCode(400); + utilsT.setServerMessage('what a pity!'); + async.eachSeries( + cases, + function(c, callback) { + if (c.object.text) { clients.PostVR(c.object, function(error, data) { should.not.exist(error); data.should.have.property('statusCode', 500); return callback(null); }); - }, function(error) { - should.not.exist(error); - callback0(); - }); + } else { + return callback(null); + } + }, + function(error) { + should.not.exist(error); + done(); } - ], function(error) { - should.not.exist(error); - done(); - }); + ); + }); + it('should return an error when something goes wrong in database', function(done) { + var cases = utilsT.loadDirExamples('./test/data/good_vrs'); + async.series( + [ + utilsT.dropRulesCollection, + function(callback0) { + async.eachSeries( + cases, + function(c, callback) { + clients.PostVR(c.object, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 500); + return callback(null); + }); + }, + function(error) { + should.not.exist(error); + callback0(); + } + ); + }, + ], + function(error) { + should.not.exist(error); + done(); + } + ); }); }); describe('#DeletetVR()', function() { @@ -112,22 +130,25 @@ describe('VisualRules', function() { }); it('should return ok when deleting an existent rule', function(done) { var rule = utilsT.loadExample('./test/data/good_vrs/visual_rule_1.json'); - async.series([ - function(callback) { - clients.PostVR(rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 201); - return callback(null); - }); - }, - function(callback) { - clients.DeleteVR(rule.name, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 204); - return callback(); - }); - } - ], done); + async.series( + [ + function(callback) { + clients.PostVR(rule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 201); + return callback(null); + }); + }, + function(callback) { + clients.DeleteVR(rule.name, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 204); + return callback(); + }); + }, + ], + done + ); }); it('should return an error when core-endpoint is not working', function(done) { utilsT.setServerCode(400); @@ -140,24 +161,31 @@ describe('VisualRules', function() { }); it('should return an error when something goes wrong in database', function(done) { var cases = utilsT.loadDirExamples('./test/data/good_vrs'); - async.series([ - utilsT.dropRulesCollection, - function(callback0) { - async.eachSeries(cases, function(c, callback) { - clients.DeleteVR(c.object.name, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 500); - return callback(null); - }); - }, function(error) { - should.not.exist(error); - callback0(); - }); + async.series( + [ + utilsT.dropRulesCollection, + function(callback0) { + async.eachSeries( + cases, + function(c, callback) { + clients.DeleteVR(c.object.name, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 500); + return callback(null); + }); + }, + function(error) { + should.not.exist(error); + callback0(); + } + ); + }, + ], + function(error) { + should.not.exist(error); + done(); } - ], function(error) { - should.not.exist(error); - done(); - }); + ); }); }); describe('#GetVR()', function() { @@ -170,47 +198,57 @@ describe('VisualRules', function() { }); it('should return a rule when it exists', function(done) { var rule = utilsT.loadExample('./test/data/good_vrs/visual_rule_1.json'); - async.series([ - function(callback) { - clients.PostVR(rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 201); - return callback(null); - }); - }, - function(callback) { - clients.GetVR(rule.name, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - data.should.have.property('body'); - data.body.should.have.property('data'); - should.not.exist(data.body.error); - should.deepEqual(data.body.data, rule); - return callback(); - }); - } - ], done); - }); - it('should return an error when something goes wrong in database', function(done) { - var cases = utilsT.loadDirExamples('./test/data/good_vrs'); - async.series([ - utilsT.dropRulesCollection, - function(callback0) { - async.eachSeries(cases, function(c, callback) { - clients.GetVR(c.object.name, function(error, data) { + async.series( + [ + function(callback) { + clients.PostVR(rule, function(error, data) { should.not.exist(error); - data.should.have.property('statusCode', 500); + data.should.have.property('statusCode', 201); return callback(null); }); - }, function(error) { - should.not.exist(error); - callback0(); - }); + }, + function(callback) { + clients.GetVR(rule.name, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + data.should.have.property('body'); + data.body.should.have.property('data'); + should.not.exist(data.body.error); + should.deepEqual(data.body.data, rule); + return callback(); + }); + }, + ], + done + ); + }); + it('should return an error when something goes wrong in database', function(done) { + var cases = utilsT.loadDirExamples('./test/data/good_vrs'); + async.series( + [ + utilsT.dropRulesCollection, + function(callback0) { + async.eachSeries( + cases, + function(c, callback) { + clients.GetVR(c.object.name, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 500); + return callback(null); + }); + }, + function(error) { + should.not.exist(error); + callback0(); + } + ); + }, + ], + function(error) { + should.not.exist(error); + done(); } - ], function(error) { - should.not.exist(error); - done(); - }); + ); }); }); describe('#GetAllVR()', function() { @@ -223,41 +261,47 @@ describe('VisualRules', function() { }); it('should return a rule when it exists', function(done) { var rule = utilsT.loadExample('./test/data/good_vrs/visual_rule_1.json'); - async.series([ - function(callback) { - clients.PostVR(rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 201); - return callback(null); - }); - }, - function(callback) { - clients.GetAllVR(function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - data.should.have.property('body'); - data.body.should.have.property('data'); - should.not.exist(data.body.error); - should.deepEqual(data.body.data[0], rule); - return callback(); - }); - } - ], done); + async.series( + [ + function(callback) { + clients.PostVR(rule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 201); + return callback(null); + }); + }, + function(callback) { + clients.GetAllVR(function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + data.should.have.property('body'); + data.body.should.have.property('data'); + should.not.exist(data.body.error); + should.deepEqual(data.body.data[0], rule); + return callback(); + }); + }, + ], + done + ); }); it('should return an error when something goes wrong in database', function(done) { - async.series([ - utilsT.dropRulesCollection, - function(callback) { - clients.GetAllVR(function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 500); - return callback(null); - }); + async.series( + [ + utilsT.dropRulesCollection, + function(callback) { + clients.GetAllVR(function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 500); + return callback(null); + }); + }, + ], + function(error) { + should.not.exist(error); + done(); } - ], function(error) { - should.not.exist(error); - done(); - }); + ); }); }); @@ -272,62 +316,71 @@ describe('VisualRules', function() { }); it('should return ok when updating an existent rule', function(done) { var rule = utilsT.loadExample('./test/data/good_vrs/visual_rule_1.json'); - async.series([ - function(callback) { - clients.PostVR(rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 201); - return callback(null); - }); - }, - function(callback) { - clients.PutVR(rule.name, rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - return callback(); - }); - } - ], done); + async.series( + [ + function(callback) { + clients.PostVR(rule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 201); + return callback(null); + }); + }, + function(callback) { + clients.PutVR(rule.name, rule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + return callback(); + }); + }, + ], + done + ); }); it('should return an error when updating an rule without name', function(done) { var rule = utilsT.loadExample('./test/data/good_vrs/visual_rule_1.json'); - async.series([ - function(callback) { - clients.PostVR(rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 201); - return callback(null); - }); - }, - function(callback) { - delete rule.name; - clients.PutVR('anothernameshouldnotbestored', rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 400); - return callback(); - }); - } - ], done); + async.series( + [ + function(callback) { + clients.PostVR(rule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 201); + return callback(null); + }); + }, + function(callback) { + delete rule.name; + clients.PutVR('anothernameshouldnotbestored', rule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 400); + return callback(); + }); + }, + ], + done + ); }); it('should return an error when updating an invalid rule', function(done) { var goodRule = utilsT.loadExample('./test/data/good_vrs/visual_rule_1.json'), badRule = utilsT.loadExample('./test/data/bad_vrs/not_supported_action.json'); - async.series([ - function(callback) { - clients.PostVR(goodRule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 201); - return callback(null); - }); - }, - function(callback) { - clients.PutVR(goodRule.name, badRule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 400); - return callback(); - }); - } - ], done); + async.series( + [ + function(callback) { + clients.PostVR(goodRule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 201); + return callback(null); + }); + }, + function(callback) { + clients.PutVR(goodRule.name, badRule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 400); + return callback(); + }); + }, + ], + done + ); }); it('should return an error when core-endpoint is not working', function(done) { var rule = utilsT.loadExample('./test/data/good_vrs/visual_rule_1.json'); @@ -341,61 +394,70 @@ describe('VisualRules', function() { }); it('should return an error when something goes wrong in database', function(done) { var cases = utilsT.loadDirExamples('./test/data/good_vrs'); - async.series([ - utilsT.dropRulesCollection, - function(callback0) { - async.eachSeries(cases, function(c, callback) { - clients.PutVR(c.object.name, c.object, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 500); - return callback(null); - }); - }, function(error) { - should.not.exist(error); - callback0(); - }); + async.series( + [ + utilsT.dropRulesCollection, + function(callback0) { + async.eachSeries( + cases, + function(c, callback) { + clients.PutVR(c.object.name, c.object, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 500); + return callback(null); + }); + }, + function(error) { + should.not.exist(error); + callback0(); + } + ); + }, + ], + function(error) { + should.not.exist(error); + done(); } - ], function(error) { - should.not.exist(error); - done(); - }); + ); }); it('should not save a VR not compiled by core', function(done) { var rule = utilsT.loadExample('./test/data/good_vrs/visual_rule_1.json'), originalID = 'ORIGINAL_ID'; - async.series([ - function(callback) { - // Set mark for tracking a possible change after update - rule.cards[0].id = originalID; - clients.PostVR(rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 201); - return callback(null); - }); - }, - function(callback) { - // new version of the rule - rule.cards[0].id = 'MOFIFIED_VR'; - // simulate a compile error - utilsT.setServerCode(500); - utilsT.setServerMessage('what a pity!'); - clients.PutVR(rule.name, rule, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 500); - return callback(); - }); - }, - // The rule is the first version - function(callback) { - clients.GetVR(rule.name, function(error, data) { - should.not.exist(error); - data.should.have.property('statusCode', 200); - data.body.data.cards[0].id.should.be.equal(originalID); - return callback(); - }); - } - ], done); + async.series( + [ + function(callback) { + // Set mark for tracking a possible change after update + rule.cards[0].id = originalID; + clients.PostVR(rule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 201); + return callback(null); + }); + }, + function(callback) { + // new version of the rule + rule.cards[0].id = 'MOFIFIED_VR'; + // simulate a compile error + utilsT.setServerCode(500); + utilsT.setServerMessage('what a pity!'); + clients.PutVR(rule.name, rule, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 500); + return callback(); + }); + }, + // The rule is the first version + function(callback) { + clients.GetVR(rule.name, function(error, data) { + should.not.exist(error); + data.should.have.property('statusCode', 200); + data.body.data.cards[0].id.should.be.equal(originalID); + return callback(); + }); + }, + ], + done + ); }); }); }); - diff --git a/test/unit/axn_param_utest.js b/test/unit/axn_param_utest.js index afd01167..74b9f9aa 100644 --- a/test/unit/axn_param_utest.js +++ b/test/unit/axn_param_utest.js @@ -31,17 +31,16 @@ var should = require('should'), updateAction = require('../../lib/models/updateAction'); describe('AxnParams', function() { - describe('#buildMailOptions()', function() { it('should substitute params', function() { - var event = {x: 1, y: 'abc', z: '***', t: 'some text'}, + var event = { x: 1, y: 'abc', z: '***', t: 'some text' }, action = { parameters: { from: ' x = ${x}', to: 'y is ${y} ', - subject: '${z} ${z} ${z}' + subject: '${z} ${z} ${z}', }, - template: 'this is "${t}"' + template: 'this is "${t}"', }, options = emailAction.buildMailOptions(action, event); @@ -51,38 +50,38 @@ describe('AxnParams', function() { should.equal(options.text, 'this is "some text"'); }); it('should keep params without placeholders', function() { - var event = {x: 1, y: 'abc', z: '***', t: 'some text'}, + var event = { x: 1, y: 'abc', z: '***', t: 'some text' }, action = { parameters: { from: ' x = 1', to: 'y is y ', - subject: '{z} $z $ { z }' + subject: '{z} $z $ { z }', }, - template: 'this is \"$\"' + template: 'this is "$"', }, options = emailAction.buildMailOptions(action, event); should.equal(options.from, ' x = 1'); should.equal(options.to, 'y is y '); should.equal(options.subject, '{z} $z $ { z }'); - should.equal(options.text, 'this is \"$\"'); + should.equal(options.text, 'this is "$"'); }); }); describe('#buildPostOptions()', function() { it('should substitute params', function() { - var event = {x: 1, y: 'abc', z: '***', t: 'some text'}, + var event = { x: 1, y: 'abc', z: '***', t: 'some text' }, action = { parameters: { url: 'http://${x}/${y}/${z}', - qs: { '${x}': 'Y${y}Y'}, - headers: { 'X-${x}': '-${z}-', 'X-${y}': '+${z}+'} + qs: { '${x}': 'Y${y}Y' }, + headers: { 'X-${x}': '-${z}-', 'X-${y}': '+${z}+' }, }, - template: 'this is \"${t}\"' + template: 'this is "${t}"', }, options = postAction.buildPostOptions(action, event); should.equal(options.url, 'http://1/abc/***'); - should.equal(options.text, 'this is \"some text\"'); + should.equal(options.text, 'this is "some text"'); should.equal(Object.keys(options.qs).length, 1); should.equal(options.qs['1'], 'YabcY'); should.equal(Object.keys(options.headers).length, 2); @@ -90,13 +89,13 @@ describe('AxnParams', function() { should.equal(options.headers['X-abc'], '+***+'); }); it('should substitute params w/o template also', function() { - var event = {x: 1, y: 'abc', z: '***', t: 'some text'}, + var event = { x: 1, y: 'abc', z: '***', t: 'some text' }, action = { parameters: { url: 'http://${x}/${y}/${z}', - qs: { '${x}': 'Y${y}Y'}, - headers: { 'X-${x}': '-${z}-', 'X-${y}': '+${z}+'} - } + qs: { '${x}': 'Y${y}Y' }, + headers: { 'X-${x}': '-${z}-', 'X-${y}': '+${z}+' }, + }, }, options = postAction.buildPostOptions(action, event); @@ -106,19 +105,19 @@ describe('AxnParams', function() { should.not.exist(options.text); }); it('should keep params without placeholders', function() { - var event = {x: 1, y: 'abc', z: '***', t: 'some text'}, + var event = { x: 1, y: 'abc', z: '***', t: 'some text' }, action = { parameters: { url: 'http://localhost:8080/path/entity', - headers: {'Content-type': 'application/json', 'X-Something': 'in the way she moves'}, - qs: {'George': 'Harrison', 'Paul': 'McCartney', 'John': 'Lennon', 'Ringo': '*'} + headers: { 'Content-type': 'application/json', 'X-Something': 'in the way she moves' }, + qs: { George: 'Harrison', Paul: 'McCartney', John: 'Lennon', Ringo: '*' }, }, - template: 'this is \"$\"' + template: 'this is "$"', }, options = postAction.buildPostOptions(action, event); should.equal(options.url, 'http://localhost:8080/path/entity'); - should.equal(options.text, 'this is \"$\"'); + should.equal(options.text, 'this is "$"'); should.equal(Object.keys(options.qs).length, 4); should.equal(options.qs.John, 'Lennon'); should.equal(options.qs.Ringo, '*'); @@ -129,12 +128,12 @@ describe('AxnParams', function() { }); describe('#buildSMSOptions()', function() { it('should substitute params', function() { - var event = {x: 1, y: 'abc', z: '***', t: 'some text'}, + var event = { x: 1, y: 'abc', z: '***', t: 'some text' }, action = { parameters: { - to: 'http://${x}/${y}/${z}' + to: 'http://${x}/${y}/${z}', }, - template: 'this is \"${t}\"' + template: 'this is "${t}"', }, options = smsAction.buildSMSOptions(action, event); @@ -142,42 +141,42 @@ describe('AxnParams', function() { should.equal(options.text, 'this is "some text"'); }); it('should keep params without placeholders', function() { - var event = {x: 1, y: 'abc', z: '***', t: 'some text'}, + var event = { x: 1, y: 'abc', z: '***', t: 'some text' }, action = { parameters: { - to: 'http://localhost:8080/path/entity' + to: 'http://localhost:8080/path/entity', }, - template: 'this is \'$\'' + template: "this is '$'", }, options = smsAction.buildSMSOptions(action, event); should.equal(options.to, 'http://localhost:8080/path/entity'); - should.equal(options.text, 'this is \'$\''); + should.equal(options.text, "this is '$'"); }); }); describe('#buildTwitterOptions()', function() { it('should substitute params', function() { - var event = {t: 'some text'}, + var event = { t: 'some text' }, action = { - template: 'this is \'${t}\'' + template: "this is '${t}'", }, options = twitterAction.buildTwitterOptions(action, event); - should.equal(options.text, 'this is \'some text\''); + should.equal(options.text, "this is 'some text'"); }); it('should keep params without placeholders', function() { - var event = {x: 1, y: 'abc', z: '***', t: 'some text'}, + var event = { x: 1, y: 'abc', z: '***', t: 'some text' }, action = { - template: 'this is \'$\'' + template: "this is '$'", }, options = twitterAction.buildTwitterOptions(action, event); - should.equal(options.text, 'this is \'$\''); + should.equal(options.text, "this is '$'"); }); }); describe('#buildUpdateOptions()', function() { it('should substitute params (old format)', function() { - var event = {a: 'ID', b: 'TYPE', c: 'NAME', d: 'VALUE', e: 'ISPATTERN', f: 'ATTRTYPE'}, + var event = { a: 'ID', b: 'TYPE', c: 'NAME', d: 'VALUE', e: 'ISPATTERN', f: 'ATTRTYPE' }, action = { parameters: { id: '${a}', @@ -185,8 +184,8 @@ describe('AxnParams', function() { name: '${c}', value: '${d}', isPattern: '${e}', - attrType: '${f}' - } + attrType: '${f}', + }, }, options = updateAction.buildUpdateOptions(action, event); @@ -198,13 +197,13 @@ describe('AxnParams', function() { should.equal(options.attributes[0].type, 'ATTRTYPE'); }); it('should keep params without placeholders (old format)', function() { - var event = {id: 'ID', type: 'TYPE'}, + var event = { id: 'ID', type: 'TYPE' }, action = { parameters: { name: 'NAME', value: 'VALUE', - attrType: 'ATTRTYPE' - } + attrType: 'ATTRTYPE', + }, }, options = updateAction.buildUpdateOptions(action, event); @@ -223,13 +222,13 @@ describe('AxnParams', function() { and the incoming event has not 'type' neither, options should not include a 'type' */ - var event = {id: 'ID', x: 'X'}, + var event = { id: 'ID', x: 'X' }, action = { parameters: { name: 'NAME', value: 'VALUE', - attrType: '${x}' - } + attrType: '${x}', + }, }, options = updateAction.buildUpdateOptions(action, event); @@ -241,9 +240,20 @@ describe('AxnParams', function() { should.equal(options.attributes[0].type, 'X'); }); it('should substitute params (array format)', function() { - var event = {a: 'ID', b: 'TYPE', c: 'NAME', d: 'VALUE', e: 'ISPATTERN', f: 'ATTRTYPE', - c1: 'NAME1', d1: 'VALUE1', f1: 'ATTRTYPE1', - c2: 'NAME2', d2: 'VALUE2', f2: 'ATTRTYPE2' }, + var event = { + a: 'ID', + b: 'TYPE', + c: 'NAME', + d: 'VALUE', + e: 'ISPATTERN', + f: 'ATTRTYPE', + c1: 'NAME1', + d1: 'VALUE1', + f1: 'ATTRTYPE1', + c2: 'NAME2', + d2: 'VALUE2', + f2: 'ATTRTYPE2', + }, action = { parameters: { id: '${a}', @@ -253,20 +263,20 @@ describe('AxnParams', function() { { name: '${c}', value: '${d}', - type: '${f}' + type: '${f}', }, { name: '${c1}', value: '${d1}', - type: '${f1}' + type: '${f1}', }, { name: '${c2}', value: '${d2}', - type: '${f2}' - } - ] - } + type: '${f2}', + }, + ], + }, }, options = updateAction.buildUpdateOptions(action, event); @@ -287,27 +297,27 @@ describe('AxnParams', function() { should.equal(options.attributes[2].type, 'ATTRTYPE2'); }); it('should keep params without placeholders (array format)', function() { - var event = {id: 'ID', type: 'TYPE'}, + var event = { id: 'ID', type: 'TYPE' }, action = { parameters: { attributes: [ { name: 'NAME', value: 'VALUE', - type: 'ATTRTYPE' + type: 'ATTRTYPE', }, { name: 'NAME1', value: 'VALUE1', - type: 'ATTRTYPE1' + type: 'ATTRTYPE1', }, { name: 'NAME2', value: 'VALUE2', - type: 'ATTRTYPE2' - } - ] - } + type: 'ATTRTYPE2', + }, + ], + }, }, options = updateAction.buildUpdateOptions(action, event); @@ -335,17 +345,17 @@ describe('AxnParams', function() { and the incoming event has not 'type' neither, options should not include a 'type' */ - var event = {id: 'ID', x: 'X'}, + var event = { id: 'ID', x: 'X' }, action = { parameters: { attributes: [ { name: 'NAME', value: 'VALUE', - type: '${x}' - } - ] - } + type: '${x}', + }, + ], + }, }, options = updateAction.buildUpdateOptions(action, event); @@ -358,5 +368,3 @@ describe('AxnParams', function() { }); }); }); - - diff --git a/test/unit/metrics_servicetime_avg.js b/test/unit/metrics_servicetime_avg.js index 73cdcf99..c0bd0d6c 100644 --- a/test/unit/metrics_servicetime_avg.js +++ b/test/unit/metrics_servicetime_avg.js @@ -42,7 +42,7 @@ describe('Metrics', function() { // exhaustive assert of existence only in this test, for quick detecting this kind of problems should.exist(decorated); should.exist(decorated.sum); - should.exist(decorated.services); // exhaustive assert of existence only here, for quick detecting + should.exist(decorated.services); // exhaustive assert of existence only here, for quick detecting should.exist(decorated.services[service]); should.exist(decorated.services[service].sum); @@ -52,16 +52,18 @@ describe('Metrics', function() { }); describe('service time (average)', function() { it('should be the average when more than one transaction, the same service/subservice', function() { - var times = [9.538113116286695, - 83.72875661589205, - 6.256202259100974, - 85.36320026032627, - 88.29136565327644, - 88.75782943796366, - 98.26397101860493, - 42.91834740433842, - 94.48413769714534, - 7.29342435952276], + var times = [ + 9.538113116286695, + 83.72875661589205, + 6.256202259100974, + 85.36320026032627, + 88.29136565327644, + 88.75782943796366, + 98.26397101860493, + 42.91834740433842, + 94.48413769714534, + 7.29342435952276, + ], average = 0, decorated; @@ -83,4 +85,3 @@ describe('Metrics', function() { }); }); }); - diff --git a/test/unit/notice_location.js b/test/unit/notice_location.js index 1b98c2bc..e13b6d29 100644 --- a/test/unit/notice_location.js +++ b/test/unit/notice_location.js @@ -27,11 +27,16 @@ var should = require('should'), notices = require('../../lib/models/notices'); describe('Notices', function() { - describe('#parseLocation()', function() { it('should return latitude, longitude with a valid location', function() { - var cases = [[0, 0], [41.8919300, 12.5113300], [40.4165000, -3.7025600], - [-33.4569400, -70.6482700], [-75.1019400, 123.3952800], [53.386944, -2.919444]]; + var cases = [ + [0, 0], + [41.89193, 12.51133], + [40.4165, -3.70256], + [-33.45694, -70.64827], + [-75.10194, 123.39528], + [53.386944, -2.919444], + ]; // Be careful with precision errors cases.forEach(function(c) { @@ -79,4 +84,3 @@ describe('Notices', function() { }); }); }); - diff --git a/test/unit/notice_timestamp.js b/test/unit/notice_timestamp.js index 7e33eac9..bc5ae0d9 100644 --- a/test/unit/notice_timestamp.js +++ b/test/unit/notice_timestamp.js @@ -26,38 +26,37 @@ var should = require('should'), notices = require('../../lib/models/notices'); - function basicNotice() { return { - 'subscriptionId': '57f73930e0e2c975a712b8fd', - 'originator': 'localhost', - 'contextResponses': [ + subscriptionId: '57f73930e0e2c975a712b8fd', + originator: 'localhost', + contextResponses: [ { - 'contextElement': { - 'type': 'Trunk', - 'isPattern': 'false', - 'id': 'T1', - 'attributes': [ + contextElement: { + type: 'Trunk', + isPattern: 'false', + id: 'T1', + attributes: [ { - 'name': 'position', - 'type': 'geo:point', - 'value': '40.418889, -3.691944' - } - ] + name: 'position', + type: 'geo:point', + value: '40.418889, -3.691944', + }, + ], + }, + statusCode: { + code: '200', + reasonPhrase: 'OK', }, - 'statusCode': { - 'code': '200', - 'reasonPhrase': 'OK' - } - } - ] + }, + ], }; } describe('Notices', function() { describe('#ProcessCBNotice()', function() { it('should add a noticeTS pseudo-attribute for every notice', function() { var bn = basicNotice(), - before = Date.now(), + before = Date.now(), after, processed; @@ -78,7 +77,7 @@ describe('Notices', function() { bn.contextResponses[0].contextElement.attributes.push({ name: 'birthDate', type: 'DateTime', - value: iso8601 + value: iso8601, }); processed = notices.ProcessCBNotice('s', 'sp', bn, 0); should.exist(processed); @@ -97,7 +96,7 @@ describe('Notices', function() { bn.contextResponses[0].contextElement.attributes.push({ name: 'birthDate', type: 'urn:x-ogc:def:trs:IDAS:1.0:ISO8601', - value: iso8601 + value: iso8601, }); processed = notices.ProcessCBNotice('s', 'sp', bn, 0); should.exist(processed); @@ -115,7 +114,7 @@ describe('Notices', function() { processed; bn.contextResponses[0].contextElement.attributes.push({ name: 'TimeInstant', - value: iso8601 + value: iso8601, }); processed = notices.ProcessCBNotice('s', 'sp', bn, 0); should.exist(processed); @@ -140,10 +139,10 @@ describe('Notices', function() { metadatas: [ { name: 'when', - 'type' : 'DateTime', - 'value' : iso8601 - } - ] + type: 'DateTime', + value: iso8601, + }, + ], }); processed = notices.ProcessCBNotice('s', 'sp', bn, 0); should.exist(processed); @@ -166,10 +165,10 @@ describe('Notices', function() { metadatas: [ { name: 'when', - 'type' : 'urn:x-ogc:def:trs:IDAS:1.0:ISO8601', - 'value' : iso8601 - } - ] + type: 'urn:x-ogc:def:trs:IDAS:1.0:ISO8601', + value: iso8601, + }, + ], }); processed = notices.ProcessCBNotice('s', 'sp', bn, 0); should.exist(processed); @@ -191,9 +190,9 @@ describe('Notices', function() { metadatas: [ { name: 'TimeInstant', - 'value': iso8601 - } - ] + value: iso8601, + }, + ], }); processed = notices.ProcessCBNotice('s', 'sp', bn, 0); should.exist(processed); @@ -205,4 +204,3 @@ describe('Notices', function() { }); }); }); - diff --git a/test/unit/nsr_utest.js b/test/unit/nsr_utest.js index f5195263..d0ea2498 100644 --- a/test/unit/nsr_utest.js +++ b/test/unit/nsr_utest.js @@ -28,24 +28,24 @@ var should = require('should'), describe('noSignal', function() { var rule = { - 'name': 'NSR1', - 'action': { - 'type': 'sms', - 'template': '${device.asset.UserProps.threshold.major} message', - 'parameters': { - 'to': '12345678' - } + name: 'NSR1', + action: { + type: 'sms', + template: '${device.asset.UserProps.threshold.major} message', + parameters: { + to: '12345678', + }, + }, + subservice: '/', + service: 'unknownt', + nosignal: { + checkInterval: '<< TO BE REPLACED >>', + attribute: 'at', + reportInterval: 900, + id: null, + idRegexp: '^.*', + type: null, }, - 'subservice': '/', - 'service': 'unknownt', - 'nosignal': { - 'checkInterval': '<< TO BE REPLACED >>', - 'attribute': 'at', - 'reportInterval': 900, - 'id': null, - 'idRegexp': '^.*', - 'type': null - } }; describe('#addNSRule()', function() { it('should reject to add a rule with invalid check interval', function() { @@ -54,13 +54,17 @@ describe('noSignal', function() { }); it('should use minimum interval when adding a rule with a too small interval', function() { rule.nosignal.checkInterval = 0; - should.strictEqual(noSignal.AddNSRule(rule.service, rule.subservice, rule.name, rule.nosignal), - noSignal.getMinIntervalMs()); + should.strictEqual( + noSignal.AddNSRule(rule.service, rule.subservice, rule.name, rule.nosignal), + noSignal.getMinIntervalMs() + ); }); it('should add a rule with valid interval', function() { rule.nosignal.checkInterval = Math.ceil(noSignal.getMinIntervalMs() / noSignal.getIntervalUnit()) * 2; - should.strictEqual(noSignal.AddNSRule(rule.service, rule.subservice, rule.name, rule.nosignal), - rule.nosignal.checkInterval * noSignal.getIntervalUnit()); + should.strictEqual( + noSignal.AddNSRule(rule.service, rule.subservice, rule.name, rule.nosignal), + rule.nosignal.checkInterval * noSignal.getIntervalUnit() + ); }); }); describe('#GetNSArrRule()', function() { @@ -70,10 +74,8 @@ describe('noSignal', function() { rule.nosignal.checkInterval = '2'; should.notEqual(noSignal.AddNSRule(rule.service, rule.subservice, rule.name, rule.nosignal), 0); gotNSRule = noSignal.GetNSArrRule(rule.service, rule.subservice, rule.name); - should.deepEqual(noSignal.Nsr2Arr(rule.service, rule.subservice, rule.name, rule.nosignal), - gotNSRule); + should.deepEqual(noSignal.Nsr2Arr(rule.service, rule.subservice, rule.name, rule.nosignal), gotNSRule); }); - }); describe('#refreshAll()', function() { @@ -83,8 +85,7 @@ describe('noSignal', function() { rule.name = 'rule to add'; noSignal.RefreshAllRules([rule]); insertedRule = noSignal.GetNSArrRule(rule.service, rule.subservice, rule.name); - should.deepEqual(noSignal.Nsr2Arr(rule.service, rule.subservice, rule.name, rule.nosignal), - insertedRule); + should.deepEqual(noSignal.Nsr2Arr(rule.service, rule.subservice, rule.name, rule.nosignal), insertedRule); }); it('should delete a missing rule', function() { var deletedRule; @@ -95,7 +96,7 @@ describe('noSignal', function() { // remove it by refreshing noSignal.RefreshAllRules([]); deletedRule = noSignal.GetNSArrRule(rule.service, rule.subservice, rule.name); - should.not.exist(deletedRule); + should.not.exist(deletedRule); }); it('should update a changed rule', function() { var updatedRule; @@ -106,10 +107,7 @@ describe('noSignal', function() { rule.nosignal.checkInterval = '24'; noSignal.RefreshAllRules([rule]); updatedRule = noSignal.GetNSArrRule(rule.service, rule.subservice, rule.name); - should.deepEqual(noSignal.Nsr2Arr(rule.service, rule.subservice, rule.name, rule.nosignal), - updatedRule); + should.deepEqual(noSignal.Nsr2Arr(rule.service, rule.subservice, rule.name, rule.nosignal), updatedRule); }); }); }); - - diff --git a/test/unit/paths_utest.js b/test/unit/paths_utest.js index 5e66d37c..5d9785c1 100644 --- a/test/unit/paths_utest.js +++ b/test/unit/paths_utest.js @@ -27,7 +27,6 @@ var should = require('should'), paths = require('../../lib/models/paths'); describe('Paths', function() { - describe('#validService()', function() { it('should return null with a valid service', function() { var cases = ['a', 'aa', new Array(50).join('x')]; @@ -120,4 +119,3 @@ describe('Paths', function() { }); }); }); - diff --git a/test/unit/service_middlewr_utest.js b/test/unit/service_middlewr_utest.js index 0286bb4f..f6ea01ac 100644 --- a/test/unit/service_middlewr_utest.js +++ b/test/unit/service_middlewr_utest.js @@ -31,26 +31,24 @@ describe('service middleware', function() { camelWord = 'camelCaseWord'; describe('#service()', function() { it('should transform to lower case', function() { - var req = { headers: {}}, + var req = { headers: {} }, err; req.headers[serviceHeader] = camelWord; err = service.checkServiceHeaders(req); should.not.exist(err); should.equal(req.service, camelWord.toLowerCase()); }); - }); describe('#subservice()', function() { var subserviceHeader = 'fiware-servicepath', camelWord = '/camelCaseWord'; it('should not transform to lower case', function() { - var req = { headers: {}}, + var req = { headers: {} }, err; req.headers[subserviceHeader] = camelWord; err = service.checkServiceHeaders(req); should.not.exist(err); should.equal(req.subservice, camelWord); }); - }); }); diff --git a/test/unit/visualrules_utest.js b/test/unit/visualrules_utest.js index 7cecf36b..d6465d6c 100644 --- a/test/unit/visualrules_utest.js +++ b/test/unit/visualrules_utest.js @@ -28,7 +28,6 @@ var should = require('should'), visualRules = require('../../lib/models/visualRules'); describe('VisualRules', function() { - describe('#vr2rule()', function() { it('should generate the right EPL', function() { var cases = utilsT.loadDirExamples('./test/data/unit/vr_epl'); @@ -50,23 +49,15 @@ describe('VisualRules', function() { 'DIFFERENT_TO', 'GREATER_OR_EQUAL_THAN', 'MINOR_OR_EQUAL_THAN', - 'MATCH']; + 'MATCH', + ]; cases.forEach(function(c) { var errOp = visualRules.errorOperator(c); should(errOp).be.null; }); }); it('should return an error with invalid operators', function() { - var cases = [ - 'GREATER_THA', - 'equal_to', - '<', - '', - null, - undefined, - 42, - {} - ]; + var cases = ['GREATER_THA', 'equal_to', '<', '', null, undefined, 42, {}]; cases.forEach(function(c) { var errOp = visualRules.errorOperator(c); errOp.should.be.an.instanceOf(visualRules.errors.UnknownOperator); @@ -74,4 +65,3 @@ describe('VisualRules', function() { }); }); }); - diff --git a/test/utils/clients.js b/test/utils/clients.js index 05bdc82c..5e324ba7 100644 --- a/test/utils/clients.js +++ b/test/utils/clients.js @@ -44,7 +44,7 @@ function commonRequest(method, url, object, callback) { if (response.headers['content-type'] === 'application/json; charset=utf-8' && typeof body === 'string') { body = JSON.parse(body); } - return callback(error, {statusCode: response.statusCode, body: body, headers: response.headers}); + return callback(error, { statusCode: response.statusCode, body: body, headers: response.headers }); }); } @@ -57,18 +57,27 @@ function PostRule(rule, callback) { commonRequest('post', url, rule, callback); } function DeleteRule(ruleName, callback) { - var url = util.format('http://%s:%s%s/%s', config.endpoint.host, - config.endpoint.port, config.endpoint.rulesPath, ruleName); + var url = util.format( + 'http://%s:%s%s/%s', + config.endpoint.host, + config.endpoint.port, + config.endpoint.rulesPath, + ruleName + ); commonRequest('del', url, null, callback); } function GetRule(ruleName, callback) { - var url = util.format('http://%s:%s%s/%s', config.endpoint.host, - config.endpoint.port, config.endpoint.rulesPath, ruleName); + var url = util.format( + 'http://%s:%s%s/%s', + config.endpoint.host, + config.endpoint.port, + config.endpoint.rulesPath, + ruleName + ); commonRequest('get', url, null, callback); } function GetAllRules(callback) { - var url = util.format('http://%s:%s%s', config.endpoint.host, - config.endpoint.port, config.endpoint.rulesPath); + var url = util.format('http://%s:%s%s', config.endpoint.host, config.endpoint.port, config.endpoint.rulesPath); commonRequest('get', url, null, callback); } @@ -77,26 +86,37 @@ function PostVR(rule, callback) { commonRequest('post', url, rule, callback); } function PutVR(ruleName, rule, callback) { - var url = util.format('http://%s:%s%s/%s', + var url = util.format( + 'http://%s:%s%s/%s', config.endpoint.host, config.endpoint.port, config.endpoint.vrPath, - ruleName); + ruleName + ); commonRequest('put', url, rule, callback); } function DeleteVR(ruleName, callback) { - var url = util.format('http://%s:%s%s/%s', config.endpoint.host, - config.endpoint.port, config.endpoint.vrPath, ruleName); + var url = util.format( + 'http://%s:%s%s/%s', + config.endpoint.host, + config.endpoint.port, + config.endpoint.vrPath, + ruleName + ); commonRequest('del', url, null, callback); } function GetVR(ruleName, callback) { - var url = util.format('http://%s:%s%s/%s', config.endpoint.host, - config.endpoint.port, config.endpoint.vrPath, ruleName); + var url = util.format( + 'http://%s:%s%s/%s', + config.endpoint.host, + config.endpoint.port, + config.endpoint.vrPath, + ruleName + ); commonRequest('get', url, null, callback); } function GetAllVR(callback) { - var url = util.format('http://%s:%s%s', config.endpoint.host, - config.endpoint.port, config.endpoint.vrPath); + var url = util.format('http://%s:%s%s', config.endpoint.host, config.endpoint.port, config.endpoint.vrPath); commonRequest('get', url, null, callback); } function PostAction(action, callback) { @@ -104,18 +124,21 @@ function PostAction(action, callback) { commonRequest('post', url, action, callback); } function GetVersion(callback) { - var url = util.format('http://%s:%s%s', config.endpoint.host, - config.endpoint.port, config.endpoint.versionPath); + var url = util.format('http://%s:%s%s', config.endpoint.host, config.endpoint.port, config.endpoint.versionPath); commonRequest('get', url, null, callback); } function PutLogLevel(level, callback) { - var url = util.format('http://%s:%s%s?level=%s', config.endpoint.host, - config.endpoint.port, config.endpoint.logPath, level); + var url = util.format( + 'http://%s:%s%s?level=%s', + config.endpoint.host, + config.endpoint.port, + config.endpoint.logPath, + level + ); commonRequest('put', url, null, callback); } function GetLogLevel(callback) { - var url = util.format('http://%s:%s%s', config.endpoint.host, - config.endpoint.port, config.endpoint.logPath); + var url = util.format('http://%s:%s%s', config.endpoint.host, config.endpoint.port, config.endpoint.logPath); commonRequest('get', url, null, callback); } diff --git a/test/utils/testEnvironment.js b/test/utils/testEnvironment.js index 2b0acf72..f484a927 100644 --- a/test/utils/testEnvironment.js +++ b/test/utils/testEnvironment.js @@ -75,8 +75,9 @@ function commonBeforeEach(done) { } callback(err); }); - } - ], done + }, + ], + done ); } function commonAfterEach(done) { @@ -121,7 +122,7 @@ function commonAfterEach(done) { } callback(err); }); - } + }, ], done ); diff --git a/test/utils/utilsT.js b/test/utils/utilsT.js index 12262f61..79c9534e 100644 --- a/test/utils/utilsT.js +++ b/test/utils/utilsT.js @@ -44,29 +44,32 @@ function loadDirExamples(filepath) { files.forEach(function(element) { elementPath = path.join(filepath, element); - objects.push({filename: elementPath, object: loadExample(elementPath)}); + objects.push({ filename: elementPath, object: loadExample(elementPath) }); }); return objects; } function remove(collection, callback) { - MongoClient.connect(config.mongo.url, function(err, db) { - if (err) { - return callback(err); - } - db.collection(collection, {}, function(err, coll) { + MongoClient.connect( + config.mongo.url, + function(err, db) { if (err) { return callback(err); } - coll.remove({}, function(err, result) { + db.collection(collection, {}, function(err, coll) { if (err) { return callback(err); } - db.close(); - return callback(null, result); + coll.remove({}, function(err, result) { + if (err) { + return callback(err); + } + db.close(); + return callback(null, result); + }); }); - }); - }); + } + ); } function dropRules(callback) { @@ -76,43 +79,49 @@ function dropExecutions(callback) { remove(config.collections.executions, callback); } function dropEntities(callback) { - MongoClient.connect(config.orion.url, function(err, db) { - if (err) { - return callback(err); - } - db.collection(config.orionDb.collection, {}, function(err, coll) { + MongoClient.connect( + config.orion.url, + function(err, db) { if (err) { return callback(err); } - coll.remove({}, function(err, result) { + db.collection(config.orionDb.collection, {}, function(err, coll) { if (err) { return callback(err); } - db.close(); - return callback(null, result); + coll.remove({}, function(err, result) { + if (err) { + return callback(err); + } + db.close(); + return callback(null, result); + }); }); - }); - }); + } + ); } function dropCollection(collection, callback) { - MongoClient.connect(config.mongo.url, function(err, db) { - if (err) { - return callback(err); - } - db.collection(collection, {}, function(err, col) { + MongoClient.connect( + config.mongo.url, + function(err, db) { if (err) { return callback(err); } - col.drop(function(err, result) { + db.collection(collection, {}, function(err, col) { if (err) { return callback(err); } - db.close(); - return callback(null, result); + col.drop(function(err, result) { + if (err) { + return callback(err); + } + db.close(); + return callback(null, result); + }); }); - }); - }); + } + ); } function dropRulesCollection(callback) { dropCollection(config.collections.rules, callback); @@ -122,100 +131,115 @@ function dropExecutionsCollection(callback) { } function createRulesCollection(callback) { - MongoClient.connect(config.mongo.url, function(err, db) { - if (err) { - return callback(err); - } - db.collection(config.collections.rules, {}, function(err, rules) { + MongoClient.connect( + config.mongo.url, + function(err, db) { if (err) { return callback(err); } - rules.ensureIndex({name: 1}, {unique: true, w: 'majority'}, function(err, indexName) { - db.close(); - return callback(err, indexName); + db.collection(config.collections.rules, {}, function(err, rules) { + if (err) { + return callback(err); + } + rules.ensureIndex({ name: 1 }, { unique: true, w: 'majority' }, function(err, indexName) { + db.close(); + return callback(err, indexName); + }); }); - }); - }); + } + ); } function addRule(rule, callback) { - MongoClient.connect(config.mongo.url, function(err, db) { - if (err) { - return callback(err); - } - db.collection(config.collections.rules, {}, function(err, rules) { + MongoClient.connect( + config.mongo.url, + function(err, db) { if (err) { return callback(err); } - rules.save(rule, function(err, result) { + db.collection(config.collections.rules, {}, function(err, rules) { if (err) { return callback(err); } - db.close(); - return callback(null, result); + rules.save(rule, function(err, result) { + if (err) { + return callback(err); + } + db.close(); + return callback(null, result); + }); }); - }); - }); + } + ); } function createEntitiesCollection(tenant, callback) { - MongoClient.connect(config.orionDb.url, function(err, db) { - var db2 = db.db(config.orionDb.prefix + '-' + tenant); - if (err) { - return callback(err); - } - db2.collection(config.orionDb.collection, {}, function(err, rules) { + MongoClient.connect( + config.orionDb.url, + function(err, db) { + var db2 = db.db(config.orionDb.prefix + '-' + tenant); if (err) { return callback(err); } - // We don't mind what fields have index in that collection - rules.ensureIndex({modDate: 1}, {unique: true, w: 'majority'}, function(err, indexName) { - db2.close(); - return callback(err, indexName); + db2.collection(config.orionDb.collection, {}, function(err, rules) { + if (err) { + return callback(err); + } + // We don't mind what fields have index in that collection + rules.ensureIndex({ modDate: 1 }, { unique: true, w: 'majority' }, function(err, indexName) { + db2.close(); + return callback(err, indexName); + }); }); - }); - }); + } + ); } function dropEntities(callback) { - MongoClient.connect(config.orionDb.url, function(err, db) { - var db2 = db.db(config.orionDb.prefix + '-' + config.DEFAULT_TENANT); - if (err) { - return callback(err); - } - db2.collection(config.orionDb.collection, {}, function(err, coll) { + MongoClient.connect( + config.orionDb.url, + function(err, db) { + var db2 = db.db(config.orionDb.prefix + '-' + config.DEFAULT_TENANT); if (err) { return callback(err); } - coll.remove({}, function(err, result) { + db2.collection(config.orionDb.collection, {}, function(err, coll) { if (err) { return callback(err); } - db2.close(); - return callback(null, result); + coll.remove({}, function(err, result) { + if (err) { + return callback(err); + } + db2.close(); + return callback(null, result); + }); }); - }); - }); + } + ); } function addEntity(tenant, entity, callback) { - MongoClient.connect(config.orionDb.url, function(err, db) { - var db2; - if (err) { - return callback(err); - } - db2 = db.db(config.orionDb.prefix + '-' + tenant); - db2.collection(config.orionDb.collection, {}, function(err, entities) { + MongoClient.connect( + config.orionDb.url, + function(err, db) { + var db2; if (err) { return callback(err); } - entities.save(entity, function(err, result) { + db2 = db.db(config.orionDb.prefix + '-' + tenant); + db2.collection(config.orionDb.collection, {}, function(err, entities) { if (err) { return callback(err); } - db2.close(); - return callback(null, result); + entities.save(entity, function(err, result) { + if (err) { + return callback(err); + } + db2.close(); + return callback(null, result); + }); }); - }); - }); + } + ); } function configTest() { config.mongo.url = 'mongodb://localhost:27017/perseo_testing'; @@ -239,22 +263,24 @@ function getConfig() { } function fakeHttpServer(cb) { - var server = require('http').createServer(function(req, res) { - var body; - req.on('data', function(data) { - body += data; - }); - req.on('end', function() { - if (fakeServerCallback) { - fakeServerCallback(req, res, body); - } else { - res.writeHead(fakeServerCode, {'Content-Type': 'text/plain'}); - res.end(fakeServerMessage); - } + var server = require('http') + .createServer(function(req, res) { + var body; + req.on('data', function(data) { + body += data; + }); + req.on('end', function() { + if (fakeServerCallback) { + fakeServerCallback(req, res, body); + } else { + res.writeHead(fakeServerCode, { 'Content-Type': 'text/plain' }); + res.end(fakeServerMessage); + } + }); + }) + .listen(fakeServerPort, function() { + cb(null, server); }); - }).listen(fakeServerPort, function() { - cb(null, server); - }); } module.exports.loadExample = loadExample; @@ -281,4 +307,3 @@ module.exports.setServerCallback = function(fxn) { fakeServerCallback = fxn; }; module.exports.getConfig = getConfig; - From aa9c92c0863a0e328135e313b43075938522e398 Mon Sep 17 00:00:00 2001 From: Jason Fox Date: Thu, 31 Jan 2019 11:32:32 +0100 Subject: [PATCH 09/11] Fix additional linting errors --- lib/models/paths.js | 2 ++ lib/routes/checkController.js | 2 ++ test/unit/axn_param_utest.js | 14 ++++++++++++-- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/lib/models/paths.js b/lib/models/paths.js index dafe9d16..c418646e 100644 --- a/lib/models/paths.js +++ b/lib/models/paths.js @@ -86,7 +86,9 @@ module.exports.errors = errors; errors.InvalidCharacter = function InvalidCharacter(msg) { this.name = 'INVALID_CHAR'; + /*jshint quotmark: double */ this.message = "service/subservice: invalid character '" + msg + "'"; + /*jshint quotmark: single */ this.httpCode = 400; }; errors.AbsolutePath = function AbsolutePath(msg) { diff --git a/lib/routes/checkController.js b/lib/routes/checkController.js index ad132b99..fcf992ba 100644 --- a/lib/routes/checkController.js +++ b/lib/routes/checkController.js @@ -26,7 +26,9 @@ var config = require('../../config'), myutils = require('../myutils'), errorNotAMaster; +/*jshint quotmark: double */ errorNotAMaster = new Error("I'm not a master"); +/*jshint quotmark: single */ errorNotAMaster.httpCode = 400; function Check(req, resp) { diff --git a/test/unit/axn_param_utest.js b/test/unit/axn_param_utest.js index 74b9f9aa..4ca2eeda 100644 --- a/test/unit/axn_param_utest.js +++ b/test/unit/axn_param_utest.js @@ -146,32 +146,42 @@ describe('AxnParams', function() { parameters: { to: 'http://localhost:8080/path/entity', }, + /*jshint quotmark: double */ template: "this is '$'", + /*jshint quotmark: single */ }, options = smsAction.buildSMSOptions(action, event); should.equal(options.to, 'http://localhost:8080/path/entity'); + /*jshint quotmark: double */ should.equal(options.text, "this is '$'"); + /*jshint quotmark: single */ }); }); describe('#buildTwitterOptions()', function() { it('should substitute params', function() { var event = { t: 'some text' }, action = { + /*jshint quotmark: double */ template: "this is '${t}'", + /*jshint quotmark: single */ }, options = twitterAction.buildTwitterOptions(action, event); - + /*jshint quotmark: double */ should.equal(options.text, "this is 'some text'"); + /*jshint quotmark: single */ }); it('should keep params without placeholders', function() { var event = { x: 1, y: 'abc', z: '***', t: 'some text' }, action = { + /*jshint quotmark: double */ template: "this is '$'", + /*jshint quotmark: single */ }, options = twitterAction.buildTwitterOptions(action, event); - + /*jshint quotmark: double */ should.equal(options.text, "this is '$'"); + /*jshint quotmark: single */ }); }); describe('#buildUpdateOptions()', function() { From a583d49751e4aea4f15893b47e7de80dad50fa7e Mon Sep 17 00:00:00 2001 From: Jason Fox Date: Fri, 1 Feb 2019 15:15:01 +0100 Subject: [PATCH 10/11] Update script to use config. --- .prettierrc.json | 2 +- package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.prettierrc.json b/.prettierrc.json index 6bc2f8e4..8238852e 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -4,6 +4,6 @@ "singleQuote": true, "parser": "flow", "printWidth": 120, - "trailingComma": "es5", + "trailingComma": "none", "tabWidth": 4 } \ No newline at end of file diff --git a/package.json b/package.json index 2b056b56..94893223 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,7 @@ "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 --tab-width 4 --print-width 120 --single-quote --trailing-comma es5 --write ./**/**/*.js **/*.js *.js", + "prettier": "prettier --config .prettierrc.json --write ./**/**/*.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" From c048e0fa919680d665f8b0924bd5bacd974ddade Mon Sep 17 00:00:00 2001 From: Jason Fox Date: Fri, 1 Feb 2019 15:32:46 +0100 Subject: [PATCH 11/11] Re-running prettier with no trailing comma. --- config.js | 24 ++--- lib/constants.js | 2 +- lib/db.js | 10 +- lib/middleware/logRequest.js | 2 +- lib/models/actions.js | 4 +- lib/models/actionsStore.js | 2 +- lib/models/emailAction.js | 2 +- lib/models/entitiesStore.js | 6 +- lib/models/executionsStore.js | 10 +- lib/models/keystone.js | 18 ++-- lib/models/noSignal.js | 4 +- lib/models/notices.js | 8 +- lib/models/postAction.js | 4 +- lib/models/rules.js | 28 +++--- lib/models/rulesStore.js | 14 +-- lib/models/smppAction.js | 8 +- lib/models/smsAction.js | 6 +- lib/models/twitterAction.js | 2 +- lib/models/updateAction.js | 20 ++-- lib/models/visualRules.js | 14 +-- lib/perseo.js | 8 +- lib/refreshCore.js | 2 +- lib/routes/rulesController.js | 4 +- lib/routes/versionController.js | 4 +- lib/routes/visualRulesController.js | 4 +- test/component/actions_elapsed_test.js | 2 +- test/component/actions_test.js | 26 +++--- test/component/auth_test.js | 4 +- test/component/config.js | 2 +- test/component/error_in_axn.js | 2 +- test/component/nsr_test.js | 20 ++-- test/component/rules_test.js | 22 ++--- test/component/visualrules_test.js | 24 ++--- test/unit/axn_param_utest.js | 78 ++++++++-------- test/unit/metrics_servicetime_avg.js | 2 +- test/unit/notice_location.js | 2 +- test/unit/notice_timestamp.js | 38 ++++---- test/unit/notices_Do.js | 38 ++++---- test/unit/notices_processCBNotice.js | 48 +++++----- test/unit/notices_processCBv2Notice.js | 118 +++++++++++------------ test/unit/nsr_utest.js | 8 +- test/unit/updateAction.js | 124 ++++++++++++------------- test/unit/visualrules_utest.js | 2 +- test/utils/testEnvironment.js | 4 +- 44 files changed, 387 insertions(+), 387 deletions(-) diff --git a/config.js b/config.js index 569d2cb2..60615e01 100644 --- a/config.js +++ b/config.js @@ -44,7 +44,7 @@ config.endpoint = { checkPath: '/check', versionPath: '/version', logPath: '/admin/log', - metricsPath: '/admin/metrics', + metricsPath: '/admin/metrics' }; /** @@ -64,7 +64,7 @@ config.mongo = { // The URI to use for the database connection. It supports replica set URIs. // mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]] // I.e.: 'mongodb://user:pass@host1:27017,host2:27018,host3:27019/cep?replicaSet=myrep' - url: 'mongodb://localhost:27017/cep', + url: 'mongodb://localhost:27017/cep' }; /** @@ -74,7 +74,7 @@ config.orionDb = { url: 'mongodb://localhost:27017/orion', collection: 'entities', prefix: 'orion', - batchSize: 500, + batchSize: 500 }; /** @@ -86,7 +86,7 @@ config.orionDb = { config.perseoCore = { rulesURL: 'http://localhost:8080/perseo-core/rules', noticesURL: 'http://localhost:8080/perseo-core/events', - interval: 60e3 * 5, + interval: 60e3 * 5 }; /** * NEXT EPL core options (with HA) @@ -117,8 +117,8 @@ config.smtp = { */ tls: { // keep rejectUnauthorized to false when secure is also false - rejectUnauthorized: false, - }, + rejectUnauthorized: false + } }; /** @@ -128,7 +128,7 @@ config.sms = { URL: 'http://sms-endpoint/smsoutbound', API_KEY: '', API_SECRET: '', - from: 'tel:22012;phone-context=+34', + from: 'tel:22012;phone-context=+34' }; /** @@ -140,14 +140,14 @@ config.smpp = { systemid: '', password: '', from: '346666666', - enabled: false, + enabled: false }; /** * Orion (Context Broker) endpoint options */ config.orion = { - URL: 'http://orion-endpoint:1026/NGSI10/updateContext', + URL: 'http://orion-endpoint:1026/NGSI10/updateContext' }; /** @@ -157,7 +157,7 @@ config.authentication = { host: 'keystone', port: '5001', user: 'user', - password: 'password', + password: 'password' }; /** @@ -166,7 +166,7 @@ config.authentication = { */ config.collections = { rules: 'rules', - executions: 'executions', + executions: 'executions' }; /** @@ -200,7 +200,7 @@ config.checkDB = { delay: 5e3, reconnectTries: 1e3, reconnectInterval: 5e3, - bufferMaxEntries: 5, + bufferMaxEntries: 5 }; /** diff --git a/lib/constants.js b/lib/constants.js index cbae47ba..8116c013 100644 --- a/lib/constants.js +++ b/lib/constants.js @@ -32,5 +32,5 @@ module.exports = { CORRELATOR_HEADER: 'fiware-correlator', AUTH_HEADER: 'X-Auth-Token', REALIP_HEADER: 'X-Real-IP', - COMPONENT_NAME: 'perseo-fe', + COMPONENT_NAME: 'perseo-fe' }; diff --git a/lib/db.js b/lib/db.js index 2ea2725f..6cf64d13 100644 --- a/lib/db.js +++ b/lib/db.js @@ -53,13 +53,13 @@ function getDbAux(url, component, callback) { { db: { bufferMaxEntries: config.checkDB.bufferMaxEntries, - domainsEnabled: true, + domainsEnabled: true }, server: { reconnectTries: config.checkDB.reconnectTries, reconnectInterval: config.checkDB.reconnectInterval, - domainsEnabled: true, - }, + domainsEnabled: true + } }, function(err, db) { if (err) { @@ -124,9 +124,9 @@ function setUp(cbSU) { ensureIndex.bind(null, rulesCollection, { name: 1, subservice: 1, - service: 1, + service: 1 }), - ensureIndexTTL.bind(null, executionsCollection, { lastTime: 1 }, config.executionsTTL), + ensureIndexTTL.bind(null, executionsCollection, { lastTime: 1 }, config.executionsTTL) ], cbSU ); diff --git a/lib/middleware/logRequest.js b/lib/middleware/logRequest.js index a02cd671..632d5e25 100644 --- a/lib/middleware/logRequest.js +++ b/lib/middleware/logRequest.js @@ -39,7 +39,7 @@ exports.middleware = function() { headers: req.headers, body: req.body, subservice: req.subservice, - service: req.service, + service: req.service }); next(); }; diff --git a/lib/models/actions.js b/lib/models/actions.js index d68bfc9c..0c92762f 100644 --- a/lib/models/actions.js +++ b/lib/models/actions.js @@ -127,7 +127,7 @@ function conditionalExec(task, lastTime, callbackW) { return callbackS(localError, null); } }, - executionsStore.Update.bind(null, task), + executionsStore.Update.bind(null, task) ], callbackW ); @@ -255,7 +255,7 @@ function DoAction(event, callback) { queue.push({ action: actions[i], event: event, - context: event.fiwarePerseoContext, + context: event.fiwarePerseoContext }); } }); diff --git a/lib/models/actionsStore.js b/lib/models/actionsStore.js index 5f372acf..6ae7ddfd 100644 --- a/lib/models/actionsStore.js +++ b/lib/models/actionsStore.js @@ -43,7 +43,7 @@ module.exports = { } return callback(null, data.action); }); - }, + } }; /** * Constructors for possible errors from this module diff --git a/lib/models/emailAction.js b/lib/models/emailAction.js index 73102597..061459b9 100644 --- a/lib/models/emailAction.js +++ b/lib/models/emailAction.js @@ -38,7 +38,7 @@ function buildMailOptions(action, event) { from: myutils.expandVar(action.parameters.from, event), to: myutils.expandVar(action.parameters.to, event), subject: myutils.expandVar(action.parameters.subject || '', event), - text: myutils.expandVar(action.template, event), + text: myutils.expandVar(action.template, event) }; } diff --git a/lib/models/entitiesStore.js b/lib/models/entitiesStore.js index 975594fb..2ad5c96c 100644 --- a/lib/models/entitiesStore.js +++ b/lib/models/entitiesStore.js @@ -41,7 +41,7 @@ function findSilentEntities(service, subservice, ruleData, func, callback) { db = orionServiceDb(service); criterion['attrs.' + ruleData.attribute + '.modDate'] = { - $lt: Date.now() / 1000 - ruleData.reportInterval, + $lt: Date.now() / 1000 - ruleData.reportInterval }; criterion['_id.servicePath'] = subservice; if (ruleData.id) { @@ -76,7 +76,7 @@ function findSilentEntities(service, subservice, ruleData, func, callback) { func(one); count++; }); - }, + } ], function(err, result) { logger.debug(context, 'findSilentEntities %s', myutils.firstChars(result)); @@ -86,5 +86,5 @@ function findSilentEntities(service, subservice, ruleData, func, callback) { } module.exports = { - FindSilentEntities: findSilentEntities, + FindSilentEntities: findSilentEntities }; diff --git a/lib/models/executionsStore.js b/lib/models/executionsStore.js index 9395307b..8dd9fdd2 100644 --- a/lib/models/executionsStore.js +++ b/lib/models/executionsStore.js @@ -45,7 +45,7 @@ module.exports = { col.findOne( { $query: { name: ruleName, subservice: subservice, service: service, id: id, index: index }, - $orderby: { lastTime: -1 }, + $orderby: { lastTime: -1 } }, function(err, data) { myutils.logErrorIf(err); @@ -77,7 +77,7 @@ module.exports = { service: service, id: id, notice: noticeId, - index: index, + index: index }, function(err, data) { myutils.logErrorIf(err); @@ -108,13 +108,13 @@ module.exports = { service: service, id: id, notice: noticeId, - index: index, + index: index }, { $currentDate: { lastTime: true } }, { upsert: true }, cb ); - }, + } ], function(err, result) { myutils.logErrorIf(err); @@ -122,5 +122,5 @@ module.exports = { return callback(err, result); } ); - }, + } }; diff --git a/lib/models/keystone.js b/lib/models/keystone.js index 8659d779..85f37fc3 100644 --- a/lib/models/keystone.js +++ b/lib/models/keystone.js @@ -40,20 +40,20 @@ function getToken(trust, callback) { password: { user: { domain: { - name: 'admin_domain', + name: 'admin_domain' }, name: config.authentication.user, - password: config.authentication.password, - }, - }, + password: config.authentication.password + } + } }, scope: { 'OS-TRUST:trust': { - id: trust, - }, - }, - }, - }, + id: trust + } + } + } + } }; logger.debug('retrieving token from Keystone using trust [%s]', trust); diff --git a/lib/models/noSignal.js b/lib/models/noSignal.js index 2cf87abf..b03e217b 100644 --- a/lib/models/noSignal.js +++ b/lib/models/noSignal.js @@ -68,7 +68,7 @@ function alertFunc(nsLineRule, entity) { ruleName: nsLineRule[NAME], reportInterval: nsLineRule[REPORT_INTERVAL], id: entity._id.id, - type: entity._id.type, + type: entity._id.type }; // Search for modDate of the entity's attribute @@ -110,7 +110,7 @@ function checkNoSignal(period) { id: nsrule[ID], idRegexp: nsrule[ID_REGEXP], type: nsrule[TYPE], - reportInterval: nsrule[REPORT_INTERVAL], + reportInterval: nsrule[REPORT_INTERVAL] }, alertFunc.bind({}, nsrule), function(err, data) { diff --git a/lib/models/notices.js b/lib/models/notices.js index 732bda91..e589b98e 100644 --- a/lib/models/notices.js +++ b/lib/models/notices.js @@ -71,7 +71,7 @@ function parseLocation(locStr) { lat: lat, lon: lon, x: utmResult.coord.x, - y: utmResult.coord.y, + y: utmResult.coord.y }; } @@ -101,7 +101,7 @@ function parseDate(isoStr) { hourUTC: date.getUTCHours(), minuteUTC: date.getUTCMinutes(), secondUTC: date.getUTCSeconds(), - millisecondUTC: date.getUTCMilliseconds(), + millisecondUTC: date.getUTCMilliseconds() }; } } @@ -385,7 +385,7 @@ function DoNotice(orionN, callback) { { url: config.perseoCore.noticesURL, json: notice, - headers: h, + headers: h }, function(err, data) { if (err) { @@ -402,7 +402,7 @@ function DoNotice(orionN, callback) { { url: config.nextCore.noticesURL, json: notice, - headers: h, + headers: h }, myutils.logErrorIf ); diff --git a/lib/models/postAction.js b/lib/models/postAction.js index 86a71408..1ed71058 100644 --- a/lib/models/postAction.js +++ b/lib/models/postAction.js @@ -31,7 +31,7 @@ function buildPostOptions(action, event) { method: action.parameters.method || 'post', url: myutils.expandVar(action.parameters.url, event), qs: myutils.expandObject(action.parameters.qs, event), - headers: myutils.expandObject(action.parameters.headers, event), + headers: myutils.expandObject(action.parameters.headers, event) }; if (action.parameters.json) { @@ -50,7 +50,7 @@ function doIt(action, event, callback) { requestOptions = { url: options.url, qs: options.qs, - headers: options.headers, + headers: options.headers }; if (options.json) { requestOptions.json = true; diff --git a/lib/models/rules.js b/lib/models/rules.js index 2f6edef3..0a6f4ee7 100644 --- a/lib/models/rules.js +++ b/lib/models/rules.js @@ -73,11 +73,11 @@ function postR2core(rule, callback) { if (rule.text) { var eplRule = { name: myutils.ruleUniqueName(rule), - text: myutils.ruleWithContext(rule), + text: myutils.ruleWithContext(rule) }, context = { name: myutils.contextName(rule), - text: myutils.contextEPL(rule), + text: myutils.contextEPL(rule) }; async.series( @@ -90,12 +90,12 @@ function postR2core(rule, callback) { [ myutils.requestHelperWOMetrics.bind(null, 'post', { url: config.nextCore.rulesURL, - json: context, + json: context }), myutils.requestHelperWOMetrics.bind(null, 'post', { url: config.nextCore.rulesURL, - json: eplRule, - }), + json: eplRule + }) ], function(/*error*/) { cb(null); // Do not propagate error @@ -104,7 +104,7 @@ function postR2core(rule, callback) { } else { cb(null); } - }, + } ], callback ); @@ -131,7 +131,7 @@ function delR2core(rule, callback) { } else { cb(null); } - }, + } ], callback ); @@ -143,11 +143,11 @@ function putR2core(rules, callback) { if (rule.text) { rulesAndContexts.push({ name: myutils.contextName(rule), - text: myutils.contextEPL(rule), + text: myutils.contextEPL(rule) }); rulesAndContexts.push({ name: myutils.ruleUniqueName(rule), - text: myutils.ruleWithContext(rule), + text: myutils.ruleWithContext(rule) }); } }); @@ -213,7 +213,7 @@ module.exports = { noSignal.AddNSRule(rule.service, rule.subservice, rule.name, rule.nosignal); } cb(null); - }, + } ], callback ); @@ -226,7 +226,7 @@ module.exports = { function(cb) { noSignal.DeleteNSRule(rule.service, rule.subservice, rule.name); cb(null); - }, + } ], callback ); @@ -239,7 +239,7 @@ module.exports = { noSignal.RefreshAllRules(rules); cb(null, rules); }, - putR2core, + putR2core ], callback ); @@ -271,11 +271,11 @@ module.exports = { } cb(null); }, - rulesStore.Update.bind(null, id, rule), + rulesStore.Update.bind(null, id, rule) ], callback ); - }, + } }; /** * Constructors for possible errors from this module diff --git a/lib/models/rulesStore.js b/lib/models/rulesStore.js index 8b9b8cf0..b73fdf54 100644 --- a/lib/models/rulesStore.js +++ b/lib/models/rulesStore.js @@ -89,7 +89,7 @@ function search(rule, callback) { db.collection.bind(db, rulesCollectionName, { strict: true }), function(col, cb) { col.findOne({ name: rule.name, subservice: rule.subservice, service: rule.service }, cb); - }, + } ], callback ); @@ -117,7 +117,7 @@ function findAll(service, subservice, callback) { } cb(err, rules); }); - }, + } ], function(err, result) { myutils.logErrorIf(err); @@ -156,7 +156,7 @@ module.exports = { db.collection.bind(db, rulesCollectionName, { strict: true }), function(col, cb) { col.remove({ name: rule.name, subservice: rule.subservice, service: rule.service }, cb); - }, + } ], function(err, result) { myutils.logErrorIf(err); @@ -173,7 +173,7 @@ module.exports = { db.collection.bind(db, rulesCollectionName, { strict: true }), function(col, cb) { col.save(r, cb); - }, + } ], function(err, result) { myutils.logErrorIf(err); @@ -194,7 +194,7 @@ module.exports = { r, { upsert: false, - returnOriginal: false, + returnOriginal: false }, function(err, result) { if (result && result.lastErrorObject && result.lastErrorObject.updatedExisting === false) { @@ -204,7 +204,7 @@ module.exports = { return cb(err, r); } ); - }, + } ], function(err, result) { myutils.logErrorIf(err); @@ -212,7 +212,7 @@ module.exports = { return callback(err, result); } ); - }, + } }; /** * Constructors for possible errors from this module diff --git a/lib/models/smppAction.js b/lib/models/smppAction.js index d203b7ab..54330914 100644 --- a/lib/models/smppAction.js +++ b/lib/models/smppAction.js @@ -32,7 +32,7 @@ var logger = require('logops'), function buildSMSOptions(action, event) { return { text: myutils.expandVar(action.template, event), - to: myutils.expandVar(action.parameters.to, event), + to: myutils.expandVar(action.parameters.to, event) }; } @@ -70,7 +70,7 @@ function doIt(action, event, callback) { { source_addr: from, destination_addr: to, - short_message: text, + short_message: text }, function(pdu) { if (pdu.command_status === 0) { @@ -91,7 +91,7 @@ function doIt(action, event, callback) { logger.debug('smpp session host: %s, port: %s', config.smpp.host, config.smpp.port); session = new smpp.Session({ host: config.smpp.host, - port: config.smpp.port, + port: config.smpp.port }); // We will track connection state for re-connecting @@ -108,7 +108,7 @@ function doIt(action, event, callback) { session.bind_transceiver( { system_id: config.smpp.systemid, - password: config.smpp.password, + password: config.smpp.password }, function(pdu) { if (pdu.command_status === 0) { diff --git a/lib/models/smsAction.js b/lib/models/smsAction.js index 815f77bb..caeabf3b 100644 --- a/lib/models/smsAction.js +++ b/lib/models/smsAction.js @@ -32,7 +32,7 @@ var util = require('util'), function buildSMSOptions(action, event) { return { text: myutils.expandVar(action.template, event), - to: myutils.expandVar(action.parameters.to, event), + to: myutils.expandVar(action.parameters.to, event) }; } function doIt(action, event, callback) { @@ -52,8 +52,8 @@ function doIt(action, event, callback) { headers: { 'User-Agent': 'request', API_KEY: config.sms.API_KEY, - API_SECRET: config.sms.API_SECRET, - }, + API_SECRET: config.sms.API_SECRET + } }, function(err, data) { myutils.logErrorIf(err, util.format('%s -> %s', config.sms.URL, msg.to)); diff --git a/lib/models/twitterAction.js b/lib/models/twitterAction.js index dbebbd36..3ab4306d 100644 --- a/lib/models/twitterAction.js +++ b/lib/models/twitterAction.js @@ -40,7 +40,7 @@ function doIt(action, event, callback) { consumer_key: action.parameters.consumer_key, consumer_secret: action.parameters.consumer_secret, access_token_key: action.parameters.access_token_key, - access_token_secret: action.parameters.access_token_secret, + access_token_secret: action.parameters.access_token_secret /*jshint +W106 */ }, client; diff --git a/lib/models/updateAction.js b/lib/models/updateAction.js index fbf5a514..b6880ae9 100644 --- a/lib/models/updateAction.js +++ b/lib/models/updateAction.js @@ -89,12 +89,12 @@ function buildUpdateOptions(action, event) { action.parameters.attributes.push({ name: action.parameters.name, value: action.parameters.value, - type: action.parameters.attrType, + type: action.parameters.attrType }); } options = { id: myutils.expandVar(action.parameters.id, event), - isPattern: myutils.expandVar(action.parameters.isPattern, event), + isPattern: myutils.expandVar(action.parameters.isPattern, event) }; if (action.parameters.actionType) { options.actionType = myutils.expandVar(action.parameters.actionType, event); @@ -103,7 +103,7 @@ function buildUpdateOptions(action, event) { for (var i = 0; i < action.parameters.attributes.length; i++) { attr = { name: myutils.expandVar(action.parameters.attributes[i].name, event), - value: myutils.expandVar(action.parameters.attributes[i].value, event), + value: myutils.expandVar(action.parameters.attributes[i].value, event) }; //The portal does not provide 'type' for attribute, "plain" rules could @@ -132,10 +132,10 @@ function doRequest(action, event, token, callback) { { isPattern: options.isPattern, id: options.id, - attributes: options.attributes, - }, + attributes: options.attributes + } ], - updateAction: 'APPEND', + updateAction: 'APPEND' }; if (options.actionType !== undefined) { updateOrion.updateAction = options.actionType; @@ -146,7 +146,7 @@ function doRequest(action, event, token, callback) { } headers = { - Accept: 'application/json', + Accept: 'application/json' }; if (token !== null) { headers[constants.AUTH_HEADER] = token; @@ -162,7 +162,7 @@ function doRequest(action, event, token, callback) { url: new URL('v1/updateContext', config.orion.URL), body: updateOrion, json: true, - headers: headers, + headers: headers }, function(err, data) { if (err) { @@ -284,7 +284,7 @@ function processOptionParams(action, event) { var key = myutils.expandVar(attr.name, event); changes[key] = { value: theValue, - type: theType, + type: theType }; if (attr.metadata !== undefined) { changes[key].metadata = theMeta; @@ -308,7 +308,7 @@ function processOptionParams(action, event) { function doRequestV2(action, event, callback) { var options = { service: event.service, - servicepath: event.subservice, + servicepath: event.subservice }; // TODO NGSIv2 update action with trust token (similar to doItWithToken for NGSIv1) diff --git a/lib/models/visualRules.js b/lib/models/visualRules.js index 2900acfb..2c38d205 100644 --- a/lib/models/visualRules.js +++ b/lib/models/visualRules.js @@ -33,7 +33,7 @@ var util = require('util'), DIFFERENT_TO: ' != ', GREATER_OR_EQUAL_THAN: ' >= ', MINOR_OR_EQUAL_THAN: ' <= ', - MATCH: ' regexp ', + MATCH: ' regexp ' }, errors = {}; @@ -172,7 +172,7 @@ function vr2rule(cardRule) { noSignal = { checkInterval: card.timeData.interval, attribute: card.sensorData.measureName, - reportInterval: card.conditionList[0].parameterValue, + reportInterval: card.conditionList[0].parameterValue }; break; default: @@ -188,7 +188,7 @@ function vr2rule(cardRule) { action.parameters = { to: plain['mail.to'], from: plain['mail.from'], - subject: plain['mail.subject'], + subject: plain['mail.subject'] }; break; case 'SendSmsMibAction': @@ -196,14 +196,14 @@ function vr2rule(cardRule) { action.type = 'sms'; action.template = plain['sms.message']; action.parameters = { - to: plain['sms.to'], + to: plain['sms.to'] }; break; case 'updateAttribute': action.type = 'update'; action.parameters = { name: card.actionData.userParams.name, - value: card.actionData.userParams.value, + value: card.actionData.userParams.value }; if (card.actionData.userParams.actionType) { action.parameters.actionType = card.actionData.userParams.actionType; @@ -245,7 +245,7 @@ function vr2rule(cardRule) { name: r.name, conditions: conditions.join(' AND '), service: r.service, - subservice: r.subservice, + subservice: r.subservice }); } } catch (ex) { @@ -310,7 +310,7 @@ module.exports = { } callback(err, data[0].VR); }); - }, + } }; /** * Constructors for possible errors from this module diff --git a/lib/perseo.js b/lib/perseo.js index 26b96b91..f9173715 100644 --- a/lib/perseo.js +++ b/lib/perseo.js @@ -84,7 +84,7 @@ function start(callbackStart) { buf.length ); } - }, + } }) ); app.use(logRequestMiddleware.middleware()); @@ -107,7 +107,7 @@ function start(callbackStart) { function(db0, cbwf) { appContext.SetDB(db0); cbwf(null); - }, + } ], callback ); @@ -121,7 +121,7 @@ function start(callbackStart) { function(dbO, cbwf) { appContext.SetOrionDB(dbO); cbwf(null); - }, + } ], callback ); @@ -145,7 +145,7 @@ function start(callbackStart) { logger.info(context, 'listening on port %d', server.address().port); return callback(null, server); }); - }, + } ], function(err) { myutils.logErrorIf(err, context); diff --git a/lib/refreshCore.js b/lib/refreshCore.js index 167bc5e8..714978f2 100644 --- a/lib/refreshCore.js +++ b/lib/refreshCore.js @@ -36,7 +36,7 @@ var config = require('../config'), trans: 'n/a', corr: 'n/a', srv: 'n/a', - subsrv: 'n/a', + subsrv: 'n/a' }; function refreshCore() { diff --git a/lib/routes/rulesController.js b/lib/routes/rulesController.js index 04e2bd19..82a5d0ef 100644 --- a/lib/routes/rulesController.js +++ b/lib/routes/rulesController.js @@ -36,7 +36,7 @@ function GetRules(req, resp) { var rule = { name: req.params.id, subservice: req.subservice, - service: req.service, + service: req.service }; rules.Find(rule, function(err, data) { myutils.respond(resp, err, data); @@ -60,7 +60,7 @@ function DelRules(req, resp) { var rule = { name: req.params.id, subservice: req.subservice, - service: req.service, + service: req.service }; metrics.IncMetrics(req.service, req.subservice, metrics.ruleDelete); rules.Remove(rule, function(err, data) { diff --git a/lib/routes/versionController.js b/lib/routes/versionController.js index f97256f9..2e794e0a 100644 --- a/lib/routes/versionController.js +++ b/lib/routes/versionController.js @@ -30,14 +30,14 @@ var config = require('../../config'), versionObj = { name: packageObj.name, description: packageObj.description, - version: packageObj.version, + version: packageObj.version }, logLevels = { DEBUG: 'DEBUG', INFO: 'INFO', WARN: 'WARN', ERROR: 'ERROR', - FATAL: 'FATAL', + FATAL: 'FATAL' }, errors = {}, currentLevel = config.logLevel; diff --git a/lib/routes/visualRulesController.js b/lib/routes/visualRulesController.js index 89d823a7..538be6af 100644 --- a/lib/routes/visualRulesController.js +++ b/lib/routes/visualRulesController.js @@ -44,7 +44,7 @@ function GetVR(req, resp) { var rule = { name: req.params.id, subservice: req.subservice, - service: req.service, + service: req.service }; visualRules.Find(rule, function(err, data) { if (!err && data) { @@ -82,7 +82,7 @@ function DelVR(req, resp) { var rule = { name: req.params.id, subservice: req.subservice, - service: req.service, + service: req.service }; metrics.IncMetrics(req.service, req.subservice, metrics.ruleDelete); diff --git a/test/component/actions_elapsed_test.js b/test/component/actions_elapsed_test.js index 0f485681..91047b8d 100644 --- a/test/component/actions_elapsed_test.js +++ b/test/component/actions_elapsed_test.js @@ -87,7 +87,7 @@ describe('Actions elapsed', function() { function(callback) { executedActions.should.be.equal(1); return callback(null); - }, + } ], done ); diff --git a/test/component/actions_test.js b/test/component/actions_test.js index 4a389e72..31a5fd19 100644 --- a/test/component/actions_test.js +++ b/test/component/actions_test.js @@ -79,7 +79,7 @@ describe('Actions', function() { data.should.have.property('statusCode', 200); return callback(); }); - }, + } ], done ); @@ -104,7 +104,7 @@ describe('Actions', function() { data.should.have.property('statusCode', 200); return callback(); }); - }, + } ], done ); @@ -135,7 +135,7 @@ describe('Actions', function() { data.should.have.property('statusCode', 200); return callback(); }); - }, + } ], done ); @@ -165,7 +165,7 @@ describe('Actions', function() { data.should.have.property('statusCode', 200); return callback(); }); - }, + } ], done ); @@ -237,9 +237,9 @@ describe('Actions', function() { service: action.ev.service, subservice: action.ev.subservice, ruleName: rule.name, - id: action.ev.id, + id: action.ev.id }, - action: { index: 0 }, + action: { index: 0 } }, function(error, time) { @@ -250,7 +250,7 @@ describe('Actions', function() { return callback(); } ); - }, + } ], done ); @@ -286,9 +286,9 @@ describe('Actions', function() { service: action.ev.service, subservice: action.ev.subservice, ruleName: rule.name, - id: action.ev.id, + id: action.ev.id }, - action: { index: 0 }, + action: { index: 0 } }, function(error, time) { should.not.exist(error); @@ -314,9 +314,9 @@ describe('Actions', function() { service: action.ev.service, subservice: action.ev.subservice, ruleName: rule.name, - id: action.ev.id, + id: action.ev.id }, - action: { index: 0 }, + action: { index: 0 } }, function(error, time) { should.not.exist(error); @@ -324,7 +324,7 @@ describe('Actions', function() { return callback(); } ); - }, + } ], done ); @@ -385,7 +385,7 @@ describe('Actions', function() { data.should.have.property('statusCode', 500); callback(); }); - }, + } ], done ); diff --git a/test/component/auth_test.js b/test/component/auth_test.js index 112f3d6c..1ee97993 100644 --- a/test/component/auth_test.js +++ b/test/component/auth_test.js @@ -71,7 +71,7 @@ describe('Auth', function() { data.should.have.property('statusCode', 200); return callback(); }); - }, + } ], function(error) { if (error) { @@ -107,7 +107,7 @@ describe('Auth', function() { data.should.have.property('statusCode', 200); return callback(); }); - }, + } ], function(error) { if (error) { diff --git a/test/component/config.js b/test/component/config.js index 5bcf3404..a9c63482 100644 --- a/test/component/config.js +++ b/test/component/config.js @@ -93,7 +93,7 @@ describe('Config', function() { describe('#With next core for notices and rules', function() { utilsT.getConfig().nextCore = { noticesURL: 'http://averyfarwayhost:1234', - rulesURL: 'http://averyfarwayhost:1234', + rulesURL: 'http://averyfarwayhost:1234' }; it('should return OK when posting a rule', postRuleOK); it('should return OK when posting a notice', postNoticeOK); diff --git a/test/component/error_in_axn.js b/test/component/error_in_axn.js index 7cdd0842..75816516 100644 --- a/test/component/error_in_axn.js +++ b/test/component/error_in_axn.js @@ -91,7 +91,7 @@ describe('Actions', function() { should.equal(array.length(), 0); return callback(); }, 100); - }, + } ], callbackES ); diff --git a/test/component/nsr_test.js b/test/component/nsr_test.js index 8470fac5..e1bdc551 100644 --- a/test/component/nsr_test.js +++ b/test/component/nsr_test.js @@ -42,21 +42,21 @@ describe('Entity', function() { _id: { id: 'eA', servicePath: DEFAULT_SUBSERVICE, type: 'type e1' }, attrs: { at: { value: 1, modDate: 0 }, - other: { value: 'this is a value', modDate: 0 }, - }, + other: { value: 'this is a value', modDate: 0 } + } }, { _id: { id: 'eB', servicePath: DEFAULT_SUBSERVICE, type: '' }, attrs: { - at: { value: 2, modDate: Date.now() / 1000 - 30 * 60 }, - }, + at: { value: 2, modDate: Date.now() / 1000 - 30 * 60 } + } }, { _id: { id: 'eC', servicePath: DEFAULT_SUBSERVICE }, attrs: { - at: { value: 3, modDate: -1 }, - }, - }, + at: { value: 3, modDate: -1 } + } + } ], checkInterval = 1, rule = utilsT.loadExample('./test/data/no_signal/generic_nonsignal.json'); @@ -94,9 +94,9 @@ describe('Entity', function() { service: DEFAULT_SERVICE, subservice: DEFAULT_SUBSERVICE, ruleName: rule.name, - id: entity._id.id, + id: entity._id.id }, - action: { index: 0 }, + action: { index: 0 } }, function(error, time) { should.not.exist(error); @@ -108,7 +108,7 @@ describe('Entity', function() { }, cb ); - }, + } ], function(err, results) { // asserts diff --git a/test/component/rules_test.js b/test/component/rules_test.js index bdcde9cb..41272cfb 100644 --- a/test/component/rules_test.js +++ b/test/component/rules_test.js @@ -94,7 +94,7 @@ describe('Rules', function() { data.body.data.should.have.property('text', rule.text); return callback(); }); - }, + } ], done ); @@ -125,7 +125,7 @@ describe('Rules', function() { return callback(); }); - }, + } ], done ); @@ -157,7 +157,7 @@ describe('Rules', function() { return callback(); }); - }, + } ], done ); @@ -188,7 +188,7 @@ describe('Rules', function() { return callback(); }); - }, + } ], done ); @@ -316,7 +316,7 @@ describe('Rules', function() { data.should.have.property('statusCode', 400); return callback(null); }); - }, + } ], done ); @@ -341,7 +341,7 @@ describe('Rules', function() { callback0(); } ); - }, + } ], function(error) { should.not.exist(error); @@ -375,7 +375,7 @@ describe('Rules', function() { data.should.have.property('statusCode', 200); return callback(); }); - }, + } ], done ); @@ -409,7 +409,7 @@ describe('Rules', function() { callback0(); } ); - }, + } ], function(error) { should.not.exist(error); @@ -443,7 +443,7 @@ describe('Rules', function() { data.should.have.property('statusCode', 200); return callback(); }); - }, + } ], done ); @@ -468,7 +468,7 @@ describe('Rules', function() { callback0(); } ); - }, + } ], function(error) { should.not.exist(error); @@ -495,7 +495,7 @@ describe('Rules', function() { data.should.have.property('statusCode', 500); return callback(null); }); - }, + } ], function(error) { should.not.exist(error); diff --git a/test/component/visualrules_test.js b/test/component/visualrules_test.js index e2fca59b..544be510 100644 --- a/test/component/visualrules_test.js +++ b/test/component/visualrules_test.js @@ -111,7 +111,7 @@ describe('VisualRules', function() { callback0(); } ); - }, + } ], function(error) { should.not.exist(error); @@ -145,7 +145,7 @@ describe('VisualRules', function() { data.should.have.property('statusCode', 204); return callback(); }); - }, + } ], done ); @@ -179,7 +179,7 @@ describe('VisualRules', function() { callback0(); } ); - }, + } ], function(error) { should.not.exist(error); @@ -217,7 +217,7 @@ describe('VisualRules', function() { should.deepEqual(data.body.data, rule); return callback(); }); - }, + } ], done ); @@ -242,7 +242,7 @@ describe('VisualRules', function() { callback0(); } ); - }, + } ], function(error) { should.not.exist(error); @@ -280,7 +280,7 @@ describe('VisualRules', function() { should.deepEqual(data.body.data[0], rule); return callback(); }); - }, + } ], done ); @@ -295,7 +295,7 @@ describe('VisualRules', function() { data.should.have.property('statusCode', 500); return callback(null); }); - }, + } ], function(error) { should.not.exist(error); @@ -331,7 +331,7 @@ describe('VisualRules', function() { data.should.have.property('statusCode', 200); return callback(); }); - }, + } ], done ); @@ -354,7 +354,7 @@ describe('VisualRules', function() { data.should.have.property('statusCode', 400); return callback(); }); - }, + } ], done ); @@ -377,7 +377,7 @@ describe('VisualRules', function() { data.should.have.property('statusCode', 400); return callback(); }); - }, + } ], done ); @@ -412,7 +412,7 @@ describe('VisualRules', function() { callback0(); } ); - }, + } ], function(error) { should.not.exist(error); @@ -454,7 +454,7 @@ describe('VisualRules', function() { data.body.data.cards[0].id.should.be.equal(originalID); return callback(); }); - }, + } ], done ); diff --git a/test/unit/axn_param_utest.js b/test/unit/axn_param_utest.js index 4ca2eeda..cb2b9d50 100644 --- a/test/unit/axn_param_utest.js +++ b/test/unit/axn_param_utest.js @@ -38,9 +38,9 @@ describe('AxnParams', function() { parameters: { from: ' x = ${x}', to: 'y is ${y} ', - subject: '${z} ${z} ${z}', + subject: '${z} ${z} ${z}' }, - template: 'this is "${t}"', + template: 'this is "${t}"' }, options = emailAction.buildMailOptions(action, event); @@ -55,9 +55,9 @@ describe('AxnParams', function() { parameters: { from: ' x = 1', to: 'y is y ', - subject: '{z} $z $ { z }', + subject: '{z} $z $ { z }' }, - template: 'this is "$"', + template: 'this is "$"' }, options = emailAction.buildMailOptions(action, event); @@ -74,9 +74,9 @@ describe('AxnParams', function() { parameters: { url: 'http://${x}/${y}/${z}', qs: { '${x}': 'Y${y}Y' }, - headers: { 'X-${x}': '-${z}-', 'X-${y}': '+${z}+' }, + headers: { 'X-${x}': '-${z}-', 'X-${y}': '+${z}+' } }, - template: 'this is "${t}"', + template: 'this is "${t}"' }, options = postAction.buildPostOptions(action, event); @@ -94,8 +94,8 @@ describe('AxnParams', function() { parameters: { url: 'http://${x}/${y}/${z}', qs: { '${x}': 'Y${y}Y' }, - headers: { 'X-${x}': '-${z}-', 'X-${y}': '+${z}+' }, - }, + headers: { 'X-${x}': '-${z}-', 'X-${y}': '+${z}+' } + } }, options = postAction.buildPostOptions(action, event); @@ -110,9 +110,9 @@ describe('AxnParams', function() { parameters: { url: 'http://localhost:8080/path/entity', headers: { 'Content-type': 'application/json', 'X-Something': 'in the way she moves' }, - qs: { George: 'Harrison', Paul: 'McCartney', John: 'Lennon', Ringo: '*' }, + qs: { George: 'Harrison', Paul: 'McCartney', John: 'Lennon', Ringo: '*' } }, - template: 'this is "$"', + template: 'this is "$"' }, options = postAction.buildPostOptions(action, event); @@ -131,9 +131,9 @@ describe('AxnParams', function() { var event = { x: 1, y: 'abc', z: '***', t: 'some text' }, action = { parameters: { - to: 'http://${x}/${y}/${z}', + to: 'http://${x}/${y}/${z}' }, - template: 'this is "${t}"', + template: 'this is "${t}"' }, options = smsAction.buildSMSOptions(action, event); @@ -144,10 +144,10 @@ describe('AxnParams', function() { var event = { x: 1, y: 'abc', z: '***', t: 'some text' }, action = { parameters: { - to: 'http://localhost:8080/path/entity', + to: 'http://localhost:8080/path/entity' }, /*jshint quotmark: double */ - template: "this is '$'", + template: "this is '$'" /*jshint quotmark: single */ }, options = smsAction.buildSMSOptions(action, event); @@ -163,7 +163,7 @@ describe('AxnParams', function() { var event = { t: 'some text' }, action = { /*jshint quotmark: double */ - template: "this is '${t}'", + template: "this is '${t}'" /*jshint quotmark: single */ }, options = twitterAction.buildTwitterOptions(action, event); @@ -175,7 +175,7 @@ describe('AxnParams', function() { var event = { x: 1, y: 'abc', z: '***', t: 'some text' }, action = { /*jshint quotmark: double */ - template: "this is '$'", + template: "this is '$'" /*jshint quotmark: single */ }, options = twitterAction.buildTwitterOptions(action, event); @@ -194,8 +194,8 @@ describe('AxnParams', function() { name: '${c}', value: '${d}', isPattern: '${e}', - attrType: '${f}', - }, + attrType: '${f}' + } }, options = updateAction.buildUpdateOptions(action, event); @@ -212,8 +212,8 @@ describe('AxnParams', function() { parameters: { name: 'NAME', value: 'VALUE', - attrType: 'ATTRTYPE', - }, + attrType: 'ATTRTYPE' + } }, options = updateAction.buildUpdateOptions(action, event); @@ -237,8 +237,8 @@ describe('AxnParams', function() { parameters: { name: 'NAME', value: 'VALUE', - attrType: '${x}', - }, + attrType: '${x}' + } }, options = updateAction.buildUpdateOptions(action, event); @@ -262,7 +262,7 @@ describe('AxnParams', function() { f1: 'ATTRTYPE1', c2: 'NAME2', d2: 'VALUE2', - f2: 'ATTRTYPE2', + f2: 'ATTRTYPE2' }, action = { parameters: { @@ -273,20 +273,20 @@ describe('AxnParams', function() { { name: '${c}', value: '${d}', - type: '${f}', + type: '${f}' }, { name: '${c1}', value: '${d1}', - type: '${f1}', + type: '${f1}' }, { name: '${c2}', value: '${d2}', - type: '${f2}', - }, - ], - }, + type: '${f2}' + } + ] + } }, options = updateAction.buildUpdateOptions(action, event); @@ -314,20 +314,20 @@ describe('AxnParams', function() { { name: 'NAME', value: 'VALUE', - type: 'ATTRTYPE', + type: 'ATTRTYPE' }, { name: 'NAME1', value: 'VALUE1', - type: 'ATTRTYPE1', + type: 'ATTRTYPE1' }, { name: 'NAME2', value: 'VALUE2', - type: 'ATTRTYPE2', - }, - ], - }, + type: 'ATTRTYPE2' + } + ] + } }, options = updateAction.buildUpdateOptions(action, event); @@ -362,10 +362,10 @@ describe('AxnParams', function() { { name: 'NAME', value: 'VALUE', - type: '${x}', - }, - ], - }, + type: '${x}' + } + ] + } }, options = updateAction.buildUpdateOptions(action, event); diff --git a/test/unit/metrics_servicetime_avg.js b/test/unit/metrics_servicetime_avg.js index c0bd0d6c..cb176e21 100644 --- a/test/unit/metrics_servicetime_avg.js +++ b/test/unit/metrics_servicetime_avg.js @@ -62,7 +62,7 @@ describe('Metrics', function() { 98.26397101860493, 42.91834740433842, 94.48413769714534, - 7.29342435952276, + 7.29342435952276 ], average = 0, decorated; diff --git a/test/unit/notice_location.js b/test/unit/notice_location.js index e13b6d29..6190601a 100644 --- a/test/unit/notice_location.js +++ b/test/unit/notice_location.js @@ -35,7 +35,7 @@ describe('Notices', function() { [40.4165, -3.70256], [-33.45694, -70.64827], [-75.10194, 123.39528], - [53.386944, -2.919444], + [53.386944, -2.919444] ]; // Be careful with precision errors diff --git a/test/unit/notice_timestamp.js b/test/unit/notice_timestamp.js index bc5ae0d9..bb7c978e 100644 --- a/test/unit/notice_timestamp.js +++ b/test/unit/notice_timestamp.js @@ -40,16 +40,16 @@ function basicNotice() { { name: 'position', type: 'geo:point', - value: '40.418889, -3.691944', - }, - ], + value: '40.418889, -3.691944' + } + ] }, statusCode: { code: '200', - reasonPhrase: 'OK', - }, - }, - ], + reasonPhrase: 'OK' + } + } + ] }; } describe('Notices', function() { @@ -77,7 +77,7 @@ describe('Notices', function() { bn.contextResponses[0].contextElement.attributes.push({ name: 'birthDate', type: 'DateTime', - value: iso8601, + value: iso8601 }); processed = notices.ProcessCBNotice('s', 'sp', bn, 0); should.exist(processed); @@ -96,7 +96,7 @@ describe('Notices', function() { bn.contextResponses[0].contextElement.attributes.push({ name: 'birthDate', type: 'urn:x-ogc:def:trs:IDAS:1.0:ISO8601', - value: iso8601, + value: iso8601 }); processed = notices.ProcessCBNotice('s', 'sp', bn, 0); should.exist(processed); @@ -114,7 +114,7 @@ describe('Notices', function() { processed; bn.contextResponses[0].contextElement.attributes.push({ name: 'TimeInstant', - value: iso8601, + value: iso8601 }); processed = notices.ProcessCBNotice('s', 'sp', bn, 0); should.exist(processed); @@ -140,9 +140,9 @@ describe('Notices', function() { { name: 'when', type: 'DateTime', - value: iso8601, - }, - ], + value: iso8601 + } + ] }); processed = notices.ProcessCBNotice('s', 'sp', bn, 0); should.exist(processed); @@ -166,9 +166,9 @@ describe('Notices', function() { { name: 'when', type: 'urn:x-ogc:def:trs:IDAS:1.0:ISO8601', - value: iso8601, - }, - ], + value: iso8601 + } + ] }); processed = notices.ProcessCBNotice('s', 'sp', bn, 0); should.exist(processed); @@ -190,9 +190,9 @@ describe('Notices', function() { metadatas: [ { name: 'TimeInstant', - value: iso8601, - }, - ], + value: iso8601 + } + ] }); processed = notices.ProcessCBNotice('s', 'sp', bn, 0); should.exist(processed); diff --git a/test/unit/notices_Do.js b/test/unit/notices_Do.js index 1455dd5c..90c48695 100644 --- a/test/unit/notices_Do.js +++ b/test/unit/notices_Do.js @@ -47,14 +47,14 @@ var noticeExampleV1 = JSON.stringify({ { name: 'Attr1', type: 'Number', - value: '123', - }, - ], - }, - }, + value: '123' + } + ] + } + } ], subservice: '/test/notices/unit', - service: 'utest', + service: 'utest' }); var noticeExampleV2 = JSON.stringify({ @@ -66,12 +66,12 @@ var noticeExampleV2 = JSON.stringify({ Attr1: { type: 'Number', value: 122, - metadata: {}, - }, - }, + metadata: {} + } + } ], subservice: '/test/notices/unitv2', - service: 'utestv2', + service: 'utestv2' }); // Core mocks @@ -79,7 +79,7 @@ var coreNotice1 = { id: 'ent1', type: 'Room', service: 'utest', - subservice: '/test/notices/unit', + subservice: '/test/notices/unit' }; describe('Notices Do', function() { @@ -105,7 +105,7 @@ describe('Notices Do', function() { 'myutils.requestHelperWOMetrics': requestWOMetricsMock, 'config.perseoCore.noticesURL': 'http://mokedurl.org', 'alarm.release': alarmReleaseMock, - 'alarm.POST_EVENT': postEvent, + 'alarm.POST_EVENT': postEvent })(function() { var callback = function(e, request) { should.exist(request); @@ -120,7 +120,7 @@ describe('Notices Do', function() { requestWOMetricsMock.should.have.been.calledWith('post', { url: 'http://mokedurl.org', json: coreNotice1, - headers: h, + headers: h }); requestWOMetricsMock.should.be.calledOnce; alarmReleaseMock.should.have.been.calledWith(postEvent); @@ -171,7 +171,7 @@ describe('Notices Do', function() { 'config.perseoCore.noticesURL': 'http://mokedurl.org', 'alarm.release': alarmReleaseMock, 'alarm.POST_EVENT': postEvent, - processCBv2Notice: processCBv2NoticeMock, + processCBv2Notice: processCBv2NoticeMock })(function() { var callback = function(e, request) { should.exist(request); @@ -186,7 +186,7 @@ describe('Notices Do', function() { requestWOMetricsMock.should.have.been.calledWith('post', { url: 'http://mokedurl.org', json: coreNotice1, - headers: h, + headers: h }); requestWOMetricsMock.should.be.calledOnce; alarmReleaseMock.should.have.been.calledWith(postEvent); @@ -211,7 +211,7 @@ describe('Notices Do', function() { 'myutils.logErrorIf': logErrorMock, 'alarm.POST_EVENT': postEvent, 'config.perseoCore.noticesURL': 'http://mokedurl.org', - 'alarm.release': alarmReleaseMock, + 'alarm.release': alarmReleaseMock })(function() { var callback = function(e, request) { should.not.exists(request); @@ -248,7 +248,7 @@ describe('Notices Do', function() { 'alarm.POST_EVENT': postEvent, processCBv2Notice: processCBv2NoticeMock, 'config.nextCore': { noticesURL: 'http://nextCoreMockURL' }, - 'myutils.logErrorIf': logErrorMock, + 'myutils.logErrorIf': logErrorMock })(function() { var callback = function(e, request) { should.exist(e); @@ -263,12 +263,12 @@ describe('Notices Do', function() { expect(requestWOMetricsMock).to.have.been.calledWith('post', { url: 'http://mokedurl.org', json: coreNotice1, - headers: h, + headers: h }); expect(requestWOMetricsMock).to.have.been.calledWith('post', { url: 'http://nextCoreMockURL', json: coreNotice1, - headers: h, + headers: h }); alarmRaiseMock.should.have.been.calledWith(postEvent); alarmRaiseMock.should.be.calledOnce; diff --git a/test/unit/notices_processCBNotice.js b/test/unit/notices_processCBNotice.js index 48e0ac5a..7db89f88 100644 --- a/test/unit/notices_processCBNotice.js +++ b/test/unit/notices_processCBNotice.js @@ -56,14 +56,14 @@ var noticeExampleV1 = JSON.stringify({ { name: attrKey, type: attrType, - value: attrValue, - }, - ], - }, - }, + value: attrValue + } + ] + } + } ], subservice: subservice, - service: service, + service: service }); var processCBNotice = notices.__get__('processCBNotice'); @@ -100,7 +100,7 @@ describe('Notices NGSIv1', function() { it('should accept simple notice using Number type', function(done) { notices.__with__({ 'uuid.v1': uuidMock, - 'Date.now': dateNowMock, + 'Date.now': dateNowMock })(function() { var noticeResult = processCBNotice(service, subservice, noticeExample, 0); expect(noticeResult.noticeId).to.equal(mockedUid); @@ -122,13 +122,13 @@ describe('Notices NGSIv1', function() { lat: lat, lon: long, x: x, - y: y, + y: y }; }); notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - parseLocation: parseLocationMock, + parseLocation: parseLocationMock })(function() { noticeExample.contextResponses[0].contextElement.attributes[0].type = locType; noticeExample.contextResponses[0].contextElement.attributes[0].value = locValue; @@ -161,13 +161,13 @@ describe('Notices NGSIv1', function() { year: 2018, hour: 11, minute: 31, - second: 26, + second: 26 }; }); notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - parseDate: parseDateMock, + parseDate: parseDateMock })(function() { noticeExample.contextResponses[0].contextElement.attributes[0].type = dateType; noticeExample.contextResponses[0].contextElement.attributes[0].value = dateValue; @@ -199,13 +199,13 @@ describe('Notices NGSIv1', function() { var metaAtVal = 'mockedValue1234'; notices.__with__({ 'uuid.v1': uuidMock, - 'Date.now': dateNowMock, + 'Date.now': dateNowMock })(function() { noticeExample.contextResponses[0].contextElement.attributes[0].metadatas = [ { name: at, - value: metaAtVal, - }, + value: metaAtVal + } ]; var noticeResult = processCBNotice(service, subservice, noticeExample, 0); expect(noticeResult.noticeId).to.equal(mockedUid); @@ -233,20 +233,20 @@ describe('Notices NGSIv1', function() { year: 2018, hour: 11, minute: 31, - second: 26, + second: 26 }; }); notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - parseDate: parseDateMock, + parseDate: parseDateMock })(function() { noticeExample.contextResponses[0].contextElement.attributes[0].metadatas = [ { name: at, value: dateValue, - type: dateType, - }, + type: dateType + } ]; var noticeResult = processCBNotice(service, subservice, noticeExample, 0); expect(noticeResult.noticeId).to.equal(mockedUid); @@ -303,20 +303,20 @@ describe('Notices NGSIv1', function() { lat: lat, lon: long, x: x, - y: y, + y: y }; }); notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - parseLocation: parseLocationMock, + parseLocation: parseLocationMock })(function() { noticeExample.contextResponses[0].contextElement.attributes[0].metadatas = [ { name: at, value: locValue, - type: locType, - }, + type: locType + } ]; var noticeResult = processCBNotice(service, subservice, noticeExample, 0); expect(noticeResult.noticeId).to.equal(mockedUid); @@ -350,7 +350,7 @@ describe('Notices NGSIv1', function() { 'uuid.v1': uuidMock, 'Date.now': dateNowMock, parseLocation: parseLocationMock, - 'myutils.logErrorIf': logErrorMock, + 'myutils.logErrorIf': logErrorMock })(function() { noticeExample.contextResponses[0].contextElement.attributes[0].type = locType; noticeExample.contextResponses[0].contextElement.attributes[0].value = locValue; @@ -376,7 +376,7 @@ describe('Notices NGSIv1', function() { notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - parseLocation: parseLocationMock, + parseLocation: parseLocationMock })(function() { noticeExample.contextResponses[0].contextElement.attributes[0].type = locType; noticeExample.contextResponses[0].contextElement.attributes[0].value = locValue; diff --git a/test/unit/notices_processCBv2Notice.js b/test/unit/notices_processCBv2Notice.js index 2efaf900..4839a2f6 100644 --- a/test/unit/notices_processCBv2Notice.js +++ b/test/unit/notices_processCBv2Notice.js @@ -47,16 +47,16 @@ var noticeExampleV2 = { data: [ { id: id, - type: type, - }, + type: type + } ], subservice: subservice, - service: service, + service: service }; var attrKey = 'Attr1'; noticeExampleV2.data[0][attrKey] = { type: attrType, - value: attrValue, + value: attrValue }; noticeExampleV2 = JSON.stringify(noticeExampleV2); @@ -94,7 +94,7 @@ describe('Notices NGSIv2', function() { it('should accept simple notice using Number type', function(done) { notices.__with__({ 'uuid.v1': uuidMock, - 'Date.now': dateNowMock, + 'Date.now': dateNowMock })(function() { var noticeResult = processCBv2Notice(service, subservice, noticeExample, 0); expect(noticeResult.noticeId).to.equal(mockedUid); @@ -114,14 +114,14 @@ describe('Notices NGSIv2', function() { var parseDateMock = sinon.spy(function() { return { a: 123, - b: 456, + b: 456 }; }); notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - parseDate: parseDateMock, + parseDate: parseDateMock })(function() { noticeExample.data[0][attrKey].type = dateType; noticeExample.data[0][attrKey].value = dateValue; @@ -148,14 +148,14 @@ describe('Notices NGSIv2', function() { lat: lat, lon: long, x: x, - y: y, + y: y }; }); notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - parseLocation: parseLocationMock, + parseLocation: parseLocationMock })(function() { noticeExample.data[0][attrKey].type = locType; noticeExample.data[0][attrKey].value = locValue; @@ -183,11 +183,11 @@ describe('Notices NGSIv2', function() { var metavalue = 'attMetaEXtraValue'; notices.__with__({ 'uuid.v1': uuidMock, - 'Date.now': dateNowMock, + 'Date.now': dateNowMock })(function() { var meta = (noticeExample.data[0].Attr1.metadata = {}); meta[at] = { - value: metavalue, + value: metavalue }; var noticeResult = processCBv2Notice(service, subservice, noticeExample, 0); expect(noticeResult.noticeId).to.equal(mockedUid); @@ -212,18 +212,18 @@ describe('Notices NGSIv2', function() { lat: lat, lon: long, x: x, - y: y, + y: y }; }); notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - parseLocation: parseLocationMock, + parseLocation: parseLocationMock })(function() { var meta = (noticeExample.data[0].Attr1.metadata = {}); meta[at] = { value: locValue, - type: locType, + type: locType }; var noticeResult = processCBv2Notice(service, subservice, noticeExample, 0); expect(noticeResult.noticeId).to.equal(mockedUid); @@ -254,19 +254,19 @@ describe('Notices NGSIv2', function() { day: 3, month: 6, year: 2018, - hour: 11, + hour: 11 // ... }; }); notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - parseDate: parseDateMock, + parseDate: parseDateMock })(function() { var meta = (noticeExample.data[0].Attr1.metadata = {}); meta[at] = { value: dateValue, - type: dateType, + type: dateType }; var noticeResult = processCBv2Notice(service, subservice, noticeExample, 0); expect(noticeResult.noticeId).to.equal(mockedUid); @@ -300,13 +300,13 @@ describe('Notices NGSIv2', function() { notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - parseDate: parseDateMock, + parseDate: parseDateMock })(function() { // Set Invalid DateType metadata attribute var meta = (noticeExample.data[0].Attr1.metadata = {}); meta[at] = { value: invalidMetaDate, - type: dateType, + type: dateType }; var noticeResult = processCBv2Notice(service, subservice, noticeExample, 0); noticeResult.should.be.instanceof(notices.errors.InvalidDateTime); @@ -330,12 +330,12 @@ describe('Notices NGSIv2', function() { notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - parseDate: parseDateMock, + parseDate: parseDateMock })(function() { // Set Invalid DateType attribute noticeExample.data[0].Attr1 = { value: invalidAttDate, - type: dateType, + type: dateType }; var noticeResult = processCBv2Notice(service, subservice, noticeExample, 0); noticeResult.should.be.instanceof(notices.errors.InvalidDateTime); @@ -359,12 +359,12 @@ describe('Notices NGSIv2', function() { notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - parseLocation: parseLocationMock, + parseLocation: parseLocationMock })(function() { // Set Invalid location attribute noticeExample.data[0].Attr1 = { value: invalidLoc, - type: locType, + type: locType }; var noticeResult = processCBv2Notice(service, subservice, noticeExample, 0); noticeResult.should.be.instanceof(notices.errors.InvalidLocation); @@ -389,13 +389,13 @@ describe('Notices NGSIv2', function() { notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - parseLocation: parseLocationMock, + parseLocation: parseLocationMock })(function() { // Set Invalid location metadata attribute var meta = (noticeExample.data[0].Attr1.metadata = {}); meta[at] = { value: invalidLoc, - type: locType, + type: locType }; var noticeResult = processCBv2Notice(service, subservice, noticeExample, 0); noticeResult.should.be.instanceof(notices.errors.InvalidLocation); @@ -420,13 +420,13 @@ describe('Notices NGSIv2', function() { 'uuid.v1': uuidMock, 'Date.now': dateNowMock, parseLocation: parseLocationMock, - 'myutils.logErrorIf': logErrorMock, + 'myutils.logErrorIf': logErrorMock })(function() { // Set location metadata attribute var meta = (noticeExample.data[0].Attr1.metadata = {}); meta[at] = { value: locValue, - type: locType, + type: locType }; var noticeResult = processCBv2Notice(service, subservice, noticeExample, 0); noticeResult.should.be.instanceof(notices.errors.InvalidV2Notice); @@ -479,10 +479,10 @@ describe('Notices NGSIv2', function() { metadata: { metaAttr1: { type: 'geo:point', - value: '47.55555, -ll3.333x-333', - }, - }, - }, + value: '47.55555, -ll3.333x-333' + } + } + } }, { id: 'sensor-2', @@ -493,10 +493,10 @@ describe('Notices NGSIv2', function() { metadata: { metaAttr1: { type: 'geo:point', - value: '47.55555, -ll3.333x-333', - }, - }, - }, + value: '47.55555, -ll3.333x-333' + } + } + } }, { id: 'sensor-3', @@ -507,10 +507,10 @@ describe('Notices NGSIv2', function() { metadata: { metaAttr1: { type: 'geo:point', - value: '47.55555, -333.333333', - }, - }, - }, + value: '47.55555, -333.333333' + } + } + } }, { id: 'sensor-4', @@ -518,8 +518,8 @@ describe('Notices NGSIv2', function() { Attr1: { type: 'geo:point', value: '470.418889, -3.691944', - metadata: {}, - }, + metadata: {} + } }, { id: 'sensor-5', @@ -530,10 +530,10 @@ describe('Notices NGSIv2', function() { metadata: { metaAttr1: { type: 'geo:point', - value: 'x4x7x.5555x5-, -3.33333', - }, - }, - }, + value: 'x4x7x.5555x5-, -3.33333' + } + } + } }, { id: 'sensor-6', @@ -544,11 +544,11 @@ describe('Notices NGSIv2', function() { metadata: { metaAttr1: { type: 'geo:point', - value: '47.55555, 3.33333', - }, - }, - }, - }, + value: '47.55555, 3.33333' + } + } + } + } ]; noticeExample.subservice = '/test/notices/unit,/test/notices/unit,/test/notices/unit,' + @@ -577,10 +577,10 @@ describe('Notices NGSIv2', function() { metadata: { metaAttr1: { value: '2018-96-03T09:31:26.296Z', - type: 'DateTime', - }, - }, - }, + type: 'DateTime' + } + } + } }, { id: 'sensor-2', @@ -591,11 +591,11 @@ describe('Notices NGSIv2', function() { metadata: { metaAttr1: { value: '2018-06-03T09:31:26.296Z', - type: 'DateTime', - }, - }, - }, - }, + type: 'DateTime' + } + } + } + } ]; noticeExample.subservice = '/test/notices/unit,/test/notices/unit'; notices.Do(noticeExample, callback); diff --git a/test/unit/nsr_utest.js b/test/unit/nsr_utest.js index d0ea2498..a7a86a7a 100644 --- a/test/unit/nsr_utest.js +++ b/test/unit/nsr_utest.js @@ -33,8 +33,8 @@ describe('noSignal', function() { type: 'sms', template: '${device.asset.UserProps.threshold.major} message', parameters: { - to: '12345678', - }, + to: '12345678' + } }, subservice: '/', service: 'unknownt', @@ -44,8 +44,8 @@ describe('noSignal', function() { reportInterval: 900, id: null, idRegexp: '^.*', - type: null, - }, + type: null + } }; describe('#addNSRule()', function() { it('should reject to add a rule with invalid check interval', function() { diff --git a/test/unit/updateAction.js b/test/unit/updateAction.js index e64fde43..06f901fd 100644 --- a/test/unit/updateAction.js +++ b/test/unit/updateAction.js @@ -35,7 +35,7 @@ chai.Should(); chai.use(sinonChai); var metaExample = { - timestamp: '2018-12-05T12:34:32.00Z', + timestamp: '2018-12-05T12:34:32.00Z' }; var action1 = { type: 'update', @@ -45,131 +45,131 @@ var action1 = { { name: 'streetLightID', type: 'Text', - value: '${id}', + value: '${id}' }, { name: 'textNumberLit', type: 'Text', - value: 666, + value: 666 }, { name: 'textBoolLit', type: 'Text', - value: false, + value: false }, { name: 'textObjLit', type: 'Text', - value: { a: 1, b: 2 }, + value: { a: 1, b: 2 } }, { name: 'streetLightID', type: 'Text', - value: '${id}', + value: '${id}' }, { name: 'illuminanceLevel', type: 'Number', - value: '${lastLightIllumNumber}', + value: '${lastLightIllumNumber}' }, { name: 'illuminanceLevel2', type: 'Number', - value: '${lastLightIllumStringNumber}', + value: '${lastLightIllumStringNumber}' }, { name: 'illuminanceLevel3', type: 'Number', - value: 12.5, + value: 12.5 }, { name: 'lastchange', type: 'DateTime', - value: '${stringDate}', + value: '${stringDate}' }, { name: 'lastchange2', type: 'DateTime', - value: '${stringDateMs}', + value: '${stringDateMs}' }, { name: 'lastchange3', type: 'DateTime', - value: '${numberDateMs}', + value: '${numberDateMs}' }, { name: 'isBool1', type: 'Boolean', value: '${isconnected}', - metadata: metaExample, + metadata: metaExample }, { name: 'isBool2', type: 'Boolean', - value: 'TRUE', + value: 'TRUE' }, { name: 'isBool3', type: 'Boolean', - value: 'true', + value: 'true' }, { name: 'isBool4', type: 'Boolean', - value: 'False', + value: 'False' }, { name: 'isBool5', type: 'Boolean', - value: 'other', + value: 'other' }, { name: 'isBool6', type: 'Boolean', - value: true, + value: true }, { name: 'isBool7', type: 'Boolean', - value: false, + value: false }, { name: 'district', type: 'Text', - value: '${areaServed}', + value: '${areaServed}' }, { name: 'status', type: 'Text', - value: '${laststatus}', + value: '${laststatus}' }, { name: 'address', type: 'Address', - value: '${streetAddress}, ${addressLocality}', + value: '${streetAddress}, ${addressLocality}' }, { name: 'powerState', type: 'Text', - value: '${powerState}', + value: '${powerState}' }, { name: 'refNone', type: '${refNoneType}', - value: 'futureNull', + value: 'futureNull' }, { name: 'refNone2', type: '${refNoneType}', - value: '123', + value: '123' }, { name: 'refNone3', type: '${refNoneType}', - value: null, - }, - ], - }, + value: null + } + ] + } }; var event1 = { ruleName: 'switch_on', @@ -196,108 +196,108 @@ var event1 = { trans: 'f8636710-5fc6-4070-9b1e-8d414fc6522a', corr: 'd5f0a9cc-0258-11e9-b678-0242ac160003; perseocep=15', srv: 'dev_test', - subsrv: '/', - }, + subsrv: '/' + } }; var expectedChanges = { address: { value: 'Vasagatan 1, Stockholm', - type: 'Address', + type: 'Address' }, status: { value: 'allright', - type: 'Text', + type: 'Text' }, textBoolLit: { value: 'false', - type: 'Text', + type: 'Text' }, textNumberLit: { value: '666', - type: 'Text', + type: 'Text' }, textObjLit: { value: '[object Object]', - type: 'Text', + type: 'Text' }, refNone: { value: null, - type: 'None', + type: 'None' }, refNone2: { value: null, - type: 'None', + type: 'None' }, refNone3: { value: null, - type: 'None', + type: 'None' }, isBool1: { value: true, type: 'Boolean', - metadata: metaExample, + metadata: metaExample }, isBool2: { value: true, - type: 'Boolean', + type: 'Boolean' }, isBool3: { value: true, - type: 'Boolean', + type: 'Boolean' }, isBool4: { value: false, - type: 'Boolean', + type: 'Boolean' }, isBool5: { value: false, - type: 'Boolean', + type: 'Boolean' }, isBool6: { value: true, - type: 'Boolean', + type: 'Boolean' }, isBool7: { value: false, - type: 'Boolean', + type: 'Boolean' }, powerState: { value: 'on', - type: 'Text', + type: 'Text' }, illuminanceLevel: { value: 80, - type: 'Number', + type: 'Number' }, illuminanceLevel2: { value: 69, - type: 'Number', + type: 'Number' }, illuminanceLevel3: { value: 12.5, - type: 'Number', + type: 'Number' }, streetLightID: { value: 'AmbientLightSensor:1', - type: 'Text', + type: 'Text' }, district: { value: 'Stockholm center', - type: 'Text', + type: 'Text' }, lastchange: { value: '2018-12-05T11:31:39.000Z', - type: 'DateTime', + type: 'DateTime' }, lastchange2: { value: '2019-01-30T10:11:00.657Z', - type: 'DateTime', + type: 'DateTime' }, lastchange3: { value: '2019-01-30T10:13:49.832Z', - type: 'DateTime', - }, + type: 'DateTime' + } }; describe('doIt', function() { @@ -321,12 +321,12 @@ describe('doIt', function() { var NGSIConnectionMock = sinon.spy(function() { return { v2: { createEntity: createEntityMock }, - close: NGSICloseMock, + close: NGSICloseMock }; }); updateAction.__with__({ - 'NGSI.Connection': NGSIConnectionMock, + 'NGSI.Connection': NGSIConnectionMock })(function() { var callback = function(e, request) { should.exist(request); @@ -360,12 +360,12 @@ describe('doIt', function() { var NGSIConnectionMock = sinon.spy(function() { return { v2: { createEntity: createEntityMock }, - close: NGSICloseMock, + close: NGSICloseMock }; }); updateAction.__with__({ - 'NGSI.Connection': NGSIConnectionMock, + 'NGSI.Connection': NGSIConnectionMock })(function() { var callback = function(e, request) { should.exist(request); @@ -400,12 +400,12 @@ describe('doIt', function() { var NGSIConnectionMock = sinon.spy(function() { return { v2: { createEntity: createEntityMock }, - close: NGSICloseMock, + close: NGSICloseMock }; }); updateAction.__with__({ - 'NGSI.Connection': NGSIConnectionMock, + 'NGSI.Connection': NGSIConnectionMock })(function() { var callback = function(e, request) { should.not.exist(request); diff --git a/test/unit/visualrules_utest.js b/test/unit/visualrules_utest.js index 3632ed0f..f1d1ba48 100644 --- a/test/unit/visualrules_utest.js +++ b/test/unit/visualrules_utest.js @@ -49,7 +49,7 @@ describe('VisualRules', function() { 'DIFFERENT_TO', 'GREATER_OR_EQUAL_THAN', 'MINOR_OR_EQUAL_THAN', - 'MATCH', + 'MATCH' ]; cases.forEach(function(c) { var errOp = visualRules.errorOperator(c); diff --git a/test/utils/testEnvironment.js b/test/utils/testEnvironment.js index f484a927..ab43fdf2 100644 --- a/test/utils/testEnvironment.js +++ b/test/utils/testEnvironment.js @@ -75,7 +75,7 @@ function commonBeforeEach(done) { } callback(err); }); - }, + } ], done ); @@ -122,7 +122,7 @@ function commonAfterEach(done) { } callback(err); }); - }, + } ], done );