diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 00000000..8238852e --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,9 @@ +{ + "arrowParens": "always", + "bracketSpacing": true, + "singleQuote": true, + "parser": "flow", + "printWidth": 120, + "trailingComma": "none", + "tabWidth": 4 +} \ No newline at end of file diff --git a/config.js b/config.js index 291b524d..60615e01 100644 --- a/config.js +++ b/config.js @@ -31,19 +31,18 @@ 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', + rulesPath: '/rules', + actionsPath: '/actions/do', + noticesPath: '/notices', + vrPath: '/m2m/vrules', + checkPath: '/check', + versionPath: '/version', logPath: '/admin/log', metricsPath: '/admin/metrics' }; @@ -58,7 +57,6 @@ config.isMaster = true; */ config.slaveDelay = 500; - /** * DB Configuration. */ @@ -66,20 +64,19 @@ 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' }; /** * OrionDB Configuration. */ config.orionDb = { - url : 'mongodb://localhost:27017/orion', - collection : 'entities', - prefix : 'orion', + url: 'mongodb://localhost:27017/orion', + collection: 'entities', + prefix: 'orion', batchSize: 500 }; - /** * EPL core options * @@ -87,9 +84,9 @@ 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) @@ -104,14 +101,13 @@ config.nextCore = { */ }; - /** * SMTP endpoint options */ config.smtp = { port: 25, host: 'smtpserver', - secure: false + secure: false, /* , auth: { @@ -119,20 +115,18 @@ config.smtp = { pass: 'xyz' } */ - , tls: { - // keep rejectUnauthorized to false when secure is also false - rejectUnauthorized: false + // keep rejectUnauthorized to false when secure is also false + rejectUnauthorized: false } - }; /** * SMS endpoint options */ config.sms = { - URL : 'http://sms-endpoint/smsoutbound', - API_KEY : '', + URL: 'http://sms-endpoint/smsoutbound', + API_KEY: '', API_SECRET: '', from: 'tel:22012;phone-context=+34' }; @@ -153,7 +147,7 @@ config.smpp = { * Orion (Context Broker) endpoint options */ config.orion = { - URL : 'http://orion-endpoint:1026/NGSI10/updateContext' + URL: 'http://orion-endpoint:1026/NGSI10/updateContext' }; /** @@ -171,7 +165,7 @@ config.authentication = { * @type {{}} */ config.collections = { - rules : 'rules', + 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 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 2e3f7c7f..e589b98e 100644 --- a/lib/models/notices.js +++ b/lib/models/notices.js @@ -44,9 +44,7 @@ var util = require('util'), * InvalidLocation, InvalidLatitude, or InvalidLongitude error otherwise */ function parseLocation(locStr) { - var position, - lat, - lon; + var position, lat, lon; if (typeof locStr !== 'string') { return new errors.InvalidLocation(locStr); } @@ -64,7 +62,7 @@ function parseLocation(locStr) { } var utmResult; try { - utmResult = converter.toUtm({coord: [lon, lat]}); // CAUTION: Longitude first element + utmResult = converter.toUtm({ coord: [lon, lat] }); // CAUTION: Longitude first element } catch (e) { return new errors.InvalidLocation(e); } @@ -79,9 +77,7 @@ function parseLocation(locStr) { // 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)) { @@ -145,8 +141,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; @@ -156,9 +151,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); } @@ -168,9 +165,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); } @@ -185,13 +184,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; - } } } @@ -209,8 +206,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; @@ -229,7 +226,6 @@ function processCBNotice(service, subservice, ncr, ix) { * @return The processed notice if notice was correct; InvalidV2Notice error otherwise */ function processCBv2Notice(service, subservice, ncr, ix) { - var n = {}, pp, temp, @@ -272,7 +268,6 @@ function processCBv2Notice(service, subservice, ncr, ix) { } for (var metaKey in attrInfo.metadata) { - n[attr + '__metadata__' + metaKey + '__type'] = attrInfo.metadata[metaKey].type; if (attrInfo.metadata[metaKey].type === 'DateTime') { metaDate = parseDate(attrInfo.metadata[metaKey].value); @@ -283,7 +278,6 @@ function processCBv2Notice(service, subservice, ncr, ix) { } else { n[attr + '__metadata__' + metaKey] = attrInfo.metadata[metaKey].value; } - } } // Add descriptive information in errors @@ -312,7 +306,6 @@ function processCBv2Notice(service, subservice, ncr, ix) { }); n = myutils.flattenMap('', n); - } catch (ex) { // Should never reach this catch var localError = new errors.InvalidV2Notice(ex + ' (' + JSON.stringify(ncr) + ')'); @@ -360,23 +353,16 @@ function DoNotice(orionN, callback) { if (!util.isArray(orionResponse)) { if (orionN.version === 2) { - return callback( - new errors.InvalidV2Notice('data must be an array, not a ' + typeof(orionResponse)) - ); + return callback(new errors.InvalidV2Notice('data must be an array, not a ' + typeof orionResponse)); } - return callback( - new errors.ContextResponsesNotArray('(' + typeof(orionResponse) + ')') - ); + return callback(new errors.ContextResponsesNotArray('(' + typeof orionResponse + ')')); } if (orionResponse.length !== sps.length) { - return callback( - new errors.ServipathCountMismatch('(' + sps.length + ',' + orionResponse.length + ')') - ); + return callback(new errors.ServipathCountMismatch('(' + sps.length + ',' + orionResponse.length + ')')); } // Iterates the collection. process 1 notice for each entity for (var j = 0; j < sps.length; j++) { - if (orionN.version === 2) { notice = processCBv2Notice(orionN.service, sps[j].trim(), orionN, j); } else { @@ -385,41 +371,51 @@ function DoNotice(orionN, callback) { if (notice instanceof Error) { myutils.logErrorIf(notice); noticesErr.push(notice); - } - else { + } else { notices.push(notice); } } - 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 - }, - function(err, data) { - if (err) { - alarm.raise(alarm.POST_EVENT); - noticesErr.push(err); - } else { - alarm.release(alarm.POST_EVENT); - dataArr.push(data); - } - // 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); + 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 + }, + function(err, data) { + if (err) { + alarm.raise(alarm.POST_EVENT); + noticesErr.push(err); + } else { + alarm.release(alarm.POST_EVENT); + dataArr.push(data); + } + // 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 + ); + } + cbEach(); } - 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) { @@ -428,7 +424,7 @@ function DoNotice(orionN, callback) { statusCode = 500; } }); - return callback({httpCode: statusCode, message: msgArr}); + return callback({ httpCode: statusCode, message: msgArr }); } ); } @@ -437,7 +433,6 @@ module.exports.Do = DoNotice; module.exports.ParseLocation = parseLocation; module.exports.ProcessCBNotice = processCBNotice; - /** * Constructors for possible errors from this module * diff --git a/lib/models/paths.js b/lib/models/paths.js index df8bc325..c418646e 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,9 @@ module.exports.errors = errors; errors.InvalidCharacter = function InvalidCharacter(msg) { this.name = 'INVALID_CHAR'; - this.message = 'service/subservice: invalid character \'' + msg + '\''; + /*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/models/postAction.js b/lib/models/postAction.js index 243dc6d2..1ed71058 100644 --- a/lib/models/postAction.js +++ b/lib/models/postAction.js @@ -26,8 +26,6 @@ var myutils = require('../myutils'), logger = require('logops'), metrics = require('./metrics'); - - function buildPostOptions(action, event) { var options = { method: action.parameters.method || 'post', @@ -38,8 +36,7 @@ function buildPostOptions(action, 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); } @@ -58,8 +55,7 @@ function doIt(action, event, callback) { 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 091f4d11..0a6f4ee7 100644 --- a/lib/models/rules.js +++ b/lib/models/rules.js @@ -46,9 +46,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)); @@ -57,7 +59,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; @@ -74,26 +77,37 @@ function postR2core(rule, callback) { }, 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); + 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); + ], + callback + ); } else { callback(null, rule); } @@ -102,19 +116,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); + 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); + ], + callback + ); } function putR2core(rules, callback) { @@ -131,7 +151,7 @@ function putR2core(rules, callback) { }); } }); - myutils.requestHelperWOMetrics('put', {url: config.perseoCore.rulesURL, json: rulesAndContexts}, callback); + myutils.requestHelperWOMetrics('put', { url: config.perseoCore.rulesURL, json: rulesAndContexts }, callback); } /** @@ -140,7 +160,6 @@ function putR2core(rules, callback) { * @param rule The rule object */ function normalizeRuleName(rule) { - var newAs = '"' + rule.name + '" as ruleName'; // Add "name as ruleName" if not exist if (rule.text && rule.text.indexOf(' as ruleName') === -1) { @@ -306,5 +325,3 @@ module.exports.errors = errors; util.inherits(errors[element], Error); }); })(); - - diff --git a/lib/models/rulesStore.js b/lib/models/rulesStore.js index 64c23857..b73fdf54 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,54 +151,67 @@ 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); - }); + ); } }; /** @@ -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..54330914 100644 --- a/lib/models/smppAction.js +++ b/lib/models/smppAction.js @@ -29,7 +29,6 @@ var logger = require('logops'), alarm = require('../alarm'), metrics = require('./metrics'); - function buildSMSOptions(action, event) { return { text: myutils.expandVar(action.template, event), @@ -37,13 +36,12 @@ function buildSMSOptions(action, 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..caeabf3b 100644 --- a/lib/models/smsAction.js +++ b/lib/models/smsAction.js @@ -29,7 +29,6 @@ var util = require('util'), alarm = require('../alarm'), metrics = require('./metrics'); - function buildSMSOptions(action, event) { return { text: myutils.expandVar(action.template, event), @@ -40,33 +39,37 @@ 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..3ab4306d 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) { @@ -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 aa99b644..b6880ae9 100644 --- a/lib/models/updateAction.js +++ b/lib/models/updateAction.js @@ -52,7 +52,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]; } @@ -76,7 +76,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}'; @@ -120,11 +120,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; @@ -150,7 +146,7 @@ function doRequest(action, event, token, callback) { } headers = { - 'Accept': 'application/json' + Accept: 'application/json' }; if (token !== null) { headers[constants.AUTH_HEADER] = token; @@ -158,16 +154,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: new URL('v1/updateContext', config.orion.URL), body: updateOrion, json: true, headers: headers - }, function(err, data) { + }, + function(err, data) { if (err) { metrics.IncMetrics(event.service, event.subservice, metrics.failedActionEntityUpdate); @@ -181,7 +178,8 @@ function doRequest(action, event, token, callback) { err = new errors.OrionError(JSON.stringify(data.body.orionError)); } callback(err, data); - }); + } + ); } function makeTokenListenerFunc(action, event, callback) { @@ -199,11 +197,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; @@ -211,13 +205,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 { @@ -229,8 +225,7 @@ function doItWithToken(action, event, callback) { if (cached.generating === false) { generateToken(action.parameters.trust, cached); } - } - else { + } else { return callback(error, data); } }); @@ -246,7 +241,6 @@ function doItWithToken(action, event, callback) { * @return changes object */ function processOptionParams(action, event) { - // Default id -> last event ID action.parameters.id = action.parameters.id || '${id}'; // Default type -> last event Type @@ -256,15 +250,14 @@ function processOptionParams(action, event) { var changes = {}; action.parameters.attributes.forEach(function(attr) { - // Direct value for Text, DateTime, and others. Apply expandVar for strings - let theValue = myutils.expandVar(attr.value, event); - let theType = myutils.expandVar(attr.type, event); + let theValue = myutils.expandVar(attr.value, event); + let theType = myutils.expandVar(attr.type, event); // Metadata should be null or object let theMeta = attr.metadata; var date; - switch(theType) { + switch (theType) { case 'Text': theValue = theValue.toString(); break; @@ -313,10 +306,9 @@ function processOptionParams(action, event) { * @return changes object */ function doRequestV2(action, event, callback) { - var options = { - 'service': event.service, - 'servicepath': event.subservice, + service: event.service, + servicepath: event.subservice }; // TODO NGSIv2 update action with trust token (similar to doItWithToken for NGSIv1) @@ -326,12 +318,13 @@ function doRequestV2(action, event, callback) { var changes = processOptionParams(action, event); metrics.IncMetrics(event.service, event.subservice, metrics.actionEntityUpdate); - connection.v2.createEntity(changes, {upsert: true}).then( + connection.v2.createEntity(changes, { upsert: true }).then( (response) => { metrics.IncMetrics(event.service, event.subservice, metrics.okActionEntityUpdate); alarm.release(alarm.ORION); callback(null, response); - }, (error) => { + }, + (error) => { metrics.IncMetrics(event.service, event.subservice, metrics.failedActionEntityUpdate); alarm.raise(alarm.ORION, null, error); callback(error, null); @@ -373,6 +366,3 @@ module.exports.errors = errors; util.inherits(errors[element], Error); }); })(); - - - diff --git a/lib/models/visualRules.js b/lib/models/visualRules.js index ddc35d3e..2c38d205 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 '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); } 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(''); + 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); } - 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; - } - 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)); - } - } } @@ -234,7 +248,8 @@ function vr2rule(cardRule) { 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); @@ -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 7cc12c28..d5deea1e 100644 --- a/lib/myutils.js +++ b/lib/myutils.js @@ -37,26 +37,24 @@ function logErrorIf(err, message, context) { if (err) { message = message || ''; if (context) { - context.op = context.op || new Error().stack.split('\n')[2].trim().substr(3); + 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 { + } 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(new RegExp('\\$\\{' + p + '\\}', 'g'), mapping[p]); }); val = val.replace(/\$\{\w*\}/g, '[?]'); } @@ -79,7 +77,10 @@ function expandObject(templateObj, dictionary) { // Think better if this is the best way function flattenMap(key, targetMap) { - var newMap = {}, v, flattened, fv; + var newMap = {}, + v, + flattened, + fv; Object.keys(targetMap).forEach(function(k) { v = targetMap[k]; if (v && typeof v === 'object') { @@ -96,7 +97,9 @@ function flattenMap(key, targetMap) { } function requestHelperAux(method, options, withMetrics, callback) { - var localError, respObj, headers, + var localError, + respObj, + headers, domain = process.domain; logger.info('making %s to %s', method, options.url); if (withMetrics && domain.context) { @@ -118,8 +121,12 @@ function requestHelperAux(method, options, withMetrics, callback) { 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')); + metrics.IncMetrics( + domain.context.srv, + domain.context.subsrv, + metrics.outgoingTransactionsRequestSize, + Buffer.byteLength(JSON.stringify(options.body), 'utf-8') + ); } catch (exception) { logger.warn(exception); } @@ -137,8 +144,12 @@ function requestHelperAux(method, options, withMetrics, callback) { logger.warn(ex); } } - metrics.IncMetrics(domain.context.srv, domain.context.subsrv, - metrics.outgoingTransactionsResponseSize, bodySz); + metrics.IncMetrics( + domain.context.srv, + domain.context.subsrv, + metrics.outgoingTransactionsResponseSize, + bodySz + ); } } if (err) { @@ -148,11 +159,17 @@ function requestHelperAux(method, options, withMetrics, callback) { } return callback(err, null); } - respObj = {code: response.statusCode, body: body}; + 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 = 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) { @@ -176,7 +193,8 @@ function requestHelperWOMetrics(method, options, callback) { function respondAux(resp, err, data, withCount, raw, withMetrics) { var statusCode = 200, errMsg = null, - respObj, respStr, + respObj, + respStr, domain = process.domain; if (err) { errMsg = err.message; @@ -191,20 +209,22 @@ function respondAux(resp, err, data, withCount, raw, withMetrics) { } else { respObj = data; } - - } - else { // non-raw - respObj = {error: errMsg, data: 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); + 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')); + 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); } @@ -247,8 +267,12 @@ function ruleUniqueName(rule) { } 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) { diff --git a/lib/perseo.js b/lib/perseo.js index 1b865903..f9173715 100644 --- a/lib/perseo.js +++ b/lib/perseo.js @@ -51,7 +51,7 @@ var domain = require('domain'), 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); @@ -66,20 +66,27 @@ function start(callbackStart) { 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( + 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()); @@ -94,24 +101,30 @@ function start(callbackStart) { async.series( [ function(callback) { - async.waterfall([ - db.getDb, - function(db0, cbwf) { - appContext.SetDB(db0); - cbwf(null); - } - ], 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); + async.waterfall( + [ + db.getOrionDb, + function(dbO, cbwf) { + appContext.SetOrionDB(dbO); + cbwf(null); + } + ], + callback + ); }, db.orionPing, function(callback) { @@ -141,21 +154,15 @@ function start(callbackStart) { } ); }); - } function stop(callback) { - var context = {op: 'stop', comp: constants.COMPONENT_NAME}; + 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); - }); + async.series([server.close.bind(server), db.close, db.orionClose], function(err) { + myutils.logErrorIf(err); + return callback(err); + }); } /** @@ -170,5 +177,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..714978f2 100644 --- a/lib/refreshCore.js +++ b/lib/refreshCore.js @@ -26,10 +26,18 @@ var config = require('../config'), rules = require('./models/rules'), logger = require('logops'), alarm = require('./alarm'), - interval, domain, + 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'}; + 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) { @@ -42,13 +50,19 @@ function refreshCore() { }); } if (config.perseoCore.interval >= MAX_INTERVAL) { - logger.error('Invalid value for config.perseoCore.interval, too large (%d >= %d)', - config.perseoCore.interval, MAX_INTERVAL); + 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); + logger.error( + 'Invalid value for config.perseoCore.interval, too small (%d <= %d)', + config.perseoCore.interval, + MIN_INTERVAL + ); process.abort(); } @@ -58,6 +72,4 @@ domain.context = context; interval = setInterval(refreshCore, config.perseoCore.interval); domain.add(interval); - interval.unref(); - 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..fcf992ba 100644 --- a/lib/routes/checkController.js +++ b/lib/routes/checkController.js @@ -26,14 +26,15 @@ var config = require('../../config'), myutils = require('../myutils'), errorNotAMaster; -errorNotAMaster = new Error('I\'m not a master'); +/*jshint quotmark: double */ +errorNotAMaster = new Error("I'm not a master"); +/*jshint quotmark: single */ errorNotAMaster.httpCode = 400; function Check(req, resp) { if (config.isMaster) { myutils.respondWOMetrics(resp, null, 'OK'); } else { - myutils.respondWOMetrics(resp, errorNotAMaster, null); } } @@ -48,4 +49,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..82a5d0ef 100644 --- a/lib/routes/rulesController.js +++ b/lib/routes/rulesController.js @@ -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..2e794e0a 100644 --- a/lib/routes/versionController.js +++ b/lib/routes/versionController.js @@ -33,11 +33,11 @@ var config = require('../../config'), 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..538be6af 100644 --- a/lib/routes/visualRulesController.js +++ b/lib/routes/visualRulesController.js @@ -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 { diff --git a/package.json b/package.json index ca733390..94893223 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,17 +24,21 @@ "test": "mocha --recursive 'test/**/*.js' --reporter spec --timeout 3000 --ui bdd --exit", "test:watch": "npm run test -- -w ./lib", "lint": "jshint lib/ --config .jshintrc && jshint test/ --config test/.jshintrc", + "prettier": "prettier --config .prettierrc.json --write ./**/**/*.js **/*.js *.js", "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", "chai": "~4.1.2", "proxyquire": "0.5.1", + "prettier": "~1.14.2", "rewire": "~4.0.1", "should": "8.2.2", "watch": "~1.0.2", @@ -55,5 +60,16 @@ "utm-converter": "~0.1.1", "uuid": "~1.4.2", "smpp": "0.3.1" + }, + "husky": { + "hooks": { + "pre-commit": "lint-staged" + } + }, + "lint-staged": { + "*.js": [ + "prettier --config .prettierrc.json --write", + "git add" + ] } } diff --git a/test/.jshintrc b/test/.jshintrc index f06dd11e..6089a791 100644 --- a/test/.jshintrc +++ b/test/.jshintrc @@ -13,7 +13,7 @@ "maxparams": 6, "maxdepth": 4, "camelcase": true, - "maxlen": 120, + "maxlen": 180, "node": true, "expr": true, "unused": "vars", diff --git a/test/component/actions_elapsed_test.js b/test/component/actions_elapsed_test.js index 1f4c74c4..91047b8d 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 4fee69bf..31a5fd19 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'), @@ -45,146 +44,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 = new 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(); + } + ); }); }); @@ -197,108 +214,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) { @@ -312,8 +341,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; @@ -321,36 +354,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 e452cc08..1ee97993 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'), @@ -52,15 +51,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) { - var respCodes = [401, 201, 200]; + 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': '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(); @@ -72,44 +108,13 @@ describe('Auth', function() { 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..a9c63482 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..75816516 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 428ef689..679a6323 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.property('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.property('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/metrics/metrics_actions_test.js b/test/component/metrics/metrics_actions_test.js index ecd93601..6bc64dfb 100644 --- a/test/component/metrics/metrics_actions_test.js +++ b/test/component/metrics/metrics_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'), @@ -38,30 +37,35 @@ describe('Metrics', function() { afterEach(testEnv.commonAfterEach); describe('#PostAction()', function() { - it('should count fired valid actions', function(done) { + it('should count fired valid actions', function(done) { var cases = utilsT.loadDirExamples('./test/data/good_actions'); metrics.GetDecorated(true); // reset metrics - 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) { - var m = metrics.GetDecorated(true), msub; + 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) { + var m = metrics.GetDecorated(true), + msub; - should.not.exist(error); - should.exists(m); - should.exists(m.services); - should.exists(m.services.unknownt); - should.exists(m.services.unknownt.subservices); - should.exists(m.services.unknownt.subservices['/']); - msub = m.services.unknownt.subservices['/']; + should.not.exist(error); + should.exists(m); + should.exists(m.services); + should.exists(m.services.unknownt); + should.exists(m.services.unknownt.subservices); + should.exists(m.services.unknownt.subservices['/']); + msub = m.services.unknownt.subservices['/']; - should.equal(m.services.unknownt.sum.firedRules, cases.length); + should.equal(m.services.unknownt.sum.firedRules, cases.length); - return done(); - }); + return done(); + } + ); }); it('should increment successful sms', function(done) { @@ -69,39 +73,43 @@ describe('Metrics', function() { action = utilsT.loadExample('./test/data/good_actions/action_sms.json'); utilsT.getConfig().sms.URL = util.format('http://localhost:%s', utilsT.fakeHttpServerPort); metrics.GetDecorated(true); // reset metrics - 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); + 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); - setTimeout(function() { - var m = metrics.GetDecorated(true), msub; + setTimeout(function() { + var m = metrics.GetDecorated(true), + msub; - should.exists(m); - should.exists(m.services); - should.exists(m.services.unknownt); - should.exists(m.services.unknownt.subservices); - should.exists(m.services.unknownt.subservices['/']); - msub = m.services.unknownt.subservices['/']; + should.exists(m); + should.exists(m.services); + should.exists(m.services.unknownt); + should.exists(m.services.unknownt.subservices); + should.exists(m.services.unknownt.subservices['/']); + msub = m.services.unknownt.subservices['/']; - should.equal(m.services.unknownt.sum.actionSMS, 1); - should.equal(m.services.unknownt.sum.okActionSMS, 1); - should.equal(m.services.unknownt.sum.failedActionSMS, 0); - should.equal(m.services.unknownt.sum.outgoingTransactions, 1); - should.equal(m.services.unknownt.sum.outgoingTransactionsErrors, 0); - return callback(); - }, 50); - }); - } - ], done); + should.equal(m.services.unknownt.sum.actionSMS, 1); + should.equal(m.services.unknownt.sum.okActionSMS, 1); + should.equal(m.services.unknownt.sum.failedActionSMS, 0); + should.equal(m.services.unknownt.sum.outgoingTransactions, 1); + should.equal(m.services.unknownt.sum.outgoingTransactionsErrors, 0); + return callback(); + }, 50); + }); + }, + ], + done + ); }); it('should increment error for failed sms', function(done) { @@ -109,38 +117,42 @@ describe('Metrics', function() { action = utilsT.loadExample('./test/data/good_actions/action_sms.json'); utilsT.getConfig().sms.URL = ''; metrics.GetDecorated(true); // reset metrics - 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); + 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); - setTimeout(function() { - var m = metrics.GetDecorated(true), msub; - should.exists(m); - should.exists(m.services); - should.exists(m.services.unknownt); - should.exists(m.services.unknownt.subservices); - should.exists(m.services.unknownt.subservices['/']); - msub = m.services.unknownt.subservices['/']; + setTimeout(function() { + var m = metrics.GetDecorated(true), + msub; + should.exists(m); + should.exists(m.services); + should.exists(m.services.unknownt); + should.exists(m.services.unknownt.subservices); + should.exists(m.services.unknownt.subservices['/']); + msub = m.services.unknownt.subservices['/']; - should.equal(m.services.unknownt.sum.actionSMS, 1); - should.equal(m.services.unknownt.sum.okActionSMS, 0); - should.equal(m.services.unknownt.sum.failedActionSMS, 1); - should.equal(m.services.unknownt.sum.outgoingTransactions, 1); - should.equal(m.services.unknownt.sum.outgoingTransactionsErrors, 1); - return callback(); - }, 50); - }); - } - ], done); + should.equal(m.services.unknownt.sum.actionSMS, 1); + should.equal(m.services.unknownt.sum.okActionSMS, 0); + should.equal(m.services.unknownt.sum.failedActionSMS, 1); + should.equal(m.services.unknownt.sum.outgoingTransactions, 1); + should.equal(m.services.unknownt.sum.outgoingTransactionsErrors, 1); + return callback(); + }, 50); + }); + }, + ], + done + ); }); it('should increment a successful action for update', function(done) { @@ -148,74 +160,82 @@ describe('Metrics', function() { action = utilsT.loadExample('./test/data/good_actions/action_update.json'); utilsT.getConfig().orion.URL = new URL(util.format('http://localhost:%s', utilsT.fakeHttpServerPort)); metrics.GetDecorated(true); // reset metrics - 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); - setTimeout(function() { - var m = metrics.GetDecorated(true), msub; - should.exists(m); - should.exists(m.services); - should.exists(m.services.unknownt); - should.exists(m.services.unknownt.subservices); - should.exists(m.services.unknownt.subservices['/']); - msub = m.services.unknownt.subservices['/']; + 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); + setTimeout(function() { + var m = metrics.GetDecorated(true), + msub; + should.exists(m); + should.exists(m.services); + should.exists(m.services.unknownt); + should.exists(m.services.unknownt.subservices); + should.exists(m.services.unknownt.subservices['/']); + msub = m.services.unknownt.subservices['/']; - should.equal(m.services.unknownt.sum.actionEntityUpdate, 1); - should.equal(m.services.unknownt.sum.okActionEntityUpdate, 1); - should.equal(m.services.unknownt.sum.failedActionEntityUpdate, 0); - should.equal(m.services.unknownt.sum.outgoingTransactions, 1); - should.equal(m.services.unknownt.sum.outgoingTransactionsErrors, 0); - return callback(); - }, 50); - }); - } - ], done); + should.equal(m.services.unknownt.sum.actionEntityUpdate, 1); + should.equal(m.services.unknownt.sum.okActionEntityUpdate, 1); + should.equal(m.services.unknownt.sum.failedActionEntityUpdate, 0); + should.equal(m.services.unknownt.sum.outgoingTransactions, 1); + should.equal(m.services.unknownt.sum.outgoingTransactionsErrors, 0); + return callback(); + }, 50); + }); + }, + ], + done + ); }); it('should increment a failed 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 = new URL('http://inventedurl.notexists.com'); metrics.GetDecorated(true); // reset metrics - 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); - setTimeout(function() { - var m = metrics.GetDecorated(true), msub; - should.exists(m); - should.exists(m.services); - should.exists(m.services.unknownt); - should.exists(m.services.unknownt.subservices); - should.exists(m.services.unknownt.subservices['/']); - msub = m.services.unknownt.subservices['/']; + 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); + setTimeout(function() { + var m = metrics.GetDecorated(true), + msub; + should.exists(m); + should.exists(m.services); + should.exists(m.services.unknownt); + should.exists(m.services.unknownt.subservices); + should.exists(m.services.unknownt.subservices['/']); + msub = m.services.unknownt.subservices['/']; - should.equal(m.services.unknownt.sum.actionEntityUpdate, 1); - should.equal(m.services.unknownt.sum.okActionEntityUpdate, 0); - should.equal(m.services.unknownt.sum.failedActionEntityUpdate, 1); - should.equal(m.services.unknownt.sum.outgoingTransactions, 1); - should.equal(m.services.unknownt.sum.outgoingTransactionsErrors, 1); - return callback(); - }, 150); - }); - } - ], done); + should.equal(m.services.unknownt.sum.actionEntityUpdate, 1); + should.equal(m.services.unknownt.sum.okActionEntityUpdate, 0); + should.equal(m.services.unknownt.sum.failedActionEntityUpdate, 1); + should.equal(m.services.unknownt.sum.outgoingTransactions, 1); + should.equal(m.services.unknownt.sum.outgoingTransactionsErrors, 1); + return callback(); + }, 150); + }); + }, + ], + done + ); }); it('should increment successful post', function(done) { @@ -223,37 +243,41 @@ describe('Metrics', function() { action = utilsT.loadExample('./test/data/good_actions/action_post.json'); metrics.GetDecorated(true); // reset metrics rule.action.parameters.url = util.format('http://localhost:%s', utilsT.fakeHttpServerPort); - 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); - setTimeout(function() { - var m = metrics.GetDecorated(true), msub; - should.exists(m); - should.exists(m.services); - should.exists(m.services.unknownt); - should.exists(m.services.unknownt.subservices); - should.exists(m.services.unknownt.subservices['/']); - msub = m.services.unknownt.subservices['/']; + 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); + setTimeout(function() { + var m = metrics.GetDecorated(true), + msub; + should.exists(m); + should.exists(m.services); + should.exists(m.services.unknownt); + should.exists(m.services.unknownt.subservices); + should.exists(m.services.unknownt.subservices['/']); + msub = m.services.unknownt.subservices['/']; - should.equal(m.services.unknownt.sum.actionHttpPost, 1); - should.equal(m.services.unknownt.sum.okActionHttpPost, 1); - should.equal(m.services.unknownt.sum.failedActionHttpPost, 0); - should.equal(m.services.unknownt.sum.outgoingTransactions, 1); - should.equal(m.services.unknownt.sum.outgoingTransactionsErrors, 0); - return callback(); - }, 50); - }); - } - ], done); + should.equal(m.services.unknownt.sum.actionHttpPost, 1); + should.equal(m.services.unknownt.sum.okActionHttpPost, 1); + should.equal(m.services.unknownt.sum.failedActionHttpPost, 0); + should.equal(m.services.unknownt.sum.outgoingTransactions, 1); + should.equal(m.services.unknownt.sum.outgoingTransactionsErrors, 0); + return callback(); + }, 50); + }); + }, + ], + done + ); }); it('should increment error for failed post', function(done) { @@ -261,37 +285,41 @@ describe('Metrics', function() { action = utilsT.loadExample('./test/data/good_actions/action_post.json'); metrics.GetDecorated(true); // reset metrics rule.action.parameters.url = ''; - 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); - setTimeout(function() { - var m = metrics.GetDecorated(true), msub; - should.exists(m); - should.exists(m.services); - should.exists(m.services.unknownt); - should.exists(m.services.unknownt.subservices); - should.exists(m.services.unknownt.subservices['/']); - msub = m.services.unknownt.subservices['/']; + 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); + setTimeout(function() { + var m = metrics.GetDecorated(true), + msub; + should.exists(m); + should.exists(m.services); + should.exists(m.services.unknownt); + should.exists(m.services.unknownt.subservices); + should.exists(m.services.unknownt.subservices['/']); + msub = m.services.unknownt.subservices['/']; - should.equal(m.services.unknownt.sum.actionHttpPost, 1); - should.equal(m.services.unknownt.sum.okActionHttpPost, 0); - should.equal(m.services.unknownt.sum.failedActionHttpPost, 1); - should.equal(m.services.unknownt.sum.outgoingTransactions, 1); - should.equal(m.services.unknownt.sum.outgoingTransactionsErrors, 1); - return callback(); - }, 50); - }); - } - ], done); + should.equal(m.services.unknownt.sum.actionHttpPost, 1); + should.equal(m.services.unknownt.sum.okActionHttpPost, 0); + should.equal(m.services.unknownt.sum.failedActionHttpPost, 1); + should.equal(m.services.unknownt.sum.outgoingTransactions, 1); + should.equal(m.services.unknownt.sum.outgoingTransactionsErrors, 1); + return callback(); + }, 50); + }); + }, + ], + done + ); }); // @@ -304,39 +332,42 @@ describe('Metrics', function() { action = utilsT.loadExample('./test/data/good_actions/action_email.json'); utilsT.getConfig().smtp.host = 'averyfarwayhosthatnotexist'; metrics.GetDecorated(true); // reset metrics - 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); + 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); - setTimeout(function() { - var m = metrics.GetDecorated(true), msub; - should.exists(m); - should.exists(m.services); - should.exists(m.services.unknownt); - should.exists(m.services.unknownt.subservices); - should.exists(m.services.unknownt.subservices['/']); - msub = m.services.unknownt.subservices['/']; + setTimeout(function() { + var m = metrics.GetDecorated(true), + msub; + should.exists(m); + should.exists(m.services); + should.exists(m.services.unknownt); + should.exists(m.services.unknownt.subservices); + should.exists(m.services.unknownt.subservices['/']); + msub = m.services.unknownt.subservices['/']; - should.equal(m.services.unknownt.sum.actionEmail, 1); - should.equal(m.services.unknownt.sum.okActionEmail, 0); - should.equal(m.services.unknownt.sum.failedActionEmail, 1); - should.equal(m.services.unknownt.sum.outgoingTransactions, 1); - should.equal(m.services.unknownt.sum.outgoingTransactionsErrors, 1); - return callback(); - }, 50); - }); - } - ], done); + should.equal(m.services.unknownt.sum.actionEmail, 1); + should.equal(m.services.unknownt.sum.okActionEmail, 0); + should.equal(m.services.unknownt.sum.failedActionEmail, 1); + should.equal(m.services.unknownt.sum.outgoingTransactions, 1); + should.equal(m.services.unknownt.sum.outgoingTransactionsErrors, 1); + return callback(); + }, 50); + }); + }, + ], + done + ); }); - }); }); diff --git a/test/component/myutils_test.js b/test/component/myutils_test.js index ac4942e5..3032bff7 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); @@ -44,7 +44,7 @@ describe('Myutils', function() { it('should return error', function(done) { var host = 'incredibleifthishostexistsicantbelievemyeyes.io'; var url = 'http://' + host; - myutils.requestHelper('get', {url: url}, function(error) { + myutils.requestHelper('get', { url: url }, function(error) { should.exist(error); error.host.should.be.equal(host); error.code.should.be.equal('ENOTFOUND'); @@ -54,4 +54,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..e1bdc551 100644 --- a/test/component/nsr_test.js +++ b/test/component/nsr_test.js @@ -39,22 +39,22 @@ 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 } } } ], @@ -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 9f54ef70..41272cfb 100644 --- a/test/component/rules_test.js +++ b/test/component/rules_test.js @@ -33,155 +33,184 @@ 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 add ruleName automatically when the rule text does not include "rule as ruleName"', function(done) { var rule = utilsT.loadExample('./test/data/good_rules/no_ruleName_in_text_rule_post.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.should.have.property('data'); - data.body.data.should.have.property('text', - 'select "x_post_auto" as ruleName, *, ev.xPressure? as Pression, ev.id? as Meter from ' + - 'pattern [every ev=iotEvent(cast(cast(xPressure?,String),float)>1.5 and type="xMeter")]'); - data.body.data.should.have.property('name', rule.name); + 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.should.have.property('data'); + data.body.data.should.have.property( + 'text', + 'select "x_post_auto" as ruleName, *, ev.xPressure? as Pression, ev.id? as Meter from ' + + 'pattern [every ev=iotEvent(cast(cast(xPressure?,String),float)>1.5 and type="xMeter")]' + ); + data.body.data.should.have.property('name', rule.name); - return callback(); - }); - } - ], done); + return callback(); + }); + } + ], + done + ); }); it('should preserve user ruleName', function(done) { var rule = utilsT.loadExample('./test/data/good_rules/blood_rule_post.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.should.have.property('data'); - data.body.data.should.have.property('text', - 'select *,\"blood_post\" as ruleName,ev.BloodPressure? as Pression, ev.id? as Meter from' + - ' pattern [every ev=iotEvent(cast(cast(BloodPressure?,String),float)>1.5 and ' + - 'type=\"BloodMeter\")]'); - data.body.data.should.have.property('name', rule.name); + 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.should.have.property('data'); + data.body.data.should.have.property( + 'text', + 'select *,"blood_post" as ruleName,ev.BloodPressure? as Pression, ev.id? as Meter from' + + ' pattern [every ev=iotEvent(cast(cast(BloodPressure?,String),float)>1.5 and ' + + 'type="BloodMeter")]' + ); + data.body.data.should.have.property('name', rule.name); - return callback(); - }); - } - ], done); + return callback(); + }); + } + ], + done + ); }); it('should preserve user incorrect ruleName', function(done) { var rule = utilsT.loadExample('./test/data/bad_rules/rule_bad_ruleName_text_rule_post.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.should.have.property('data'); - data.body.data.should.have.property('text', - 'select *, "badRuleleName" as ruleName, ev.xPressure? as Pression, ev.id? as Meter from' + - ' pattern [every ev=iotEvent(cast(cast(xPressure?,String),float)>1.5 and type="xMeter")]'); - data.body.data.should.have.property('name', rule.name); + 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.should.have.property('data'); + data.body.data.should.have.property( + 'text', + 'select *, "badRuleleName" as ruleName, ev.xPressure? as Pression, ev.id? as Meter from' + + ' pattern [every ev=iotEvent(cast(cast(xPressure?,String),float)>1.5 and type="xMeter")]' + ); + data.body.data.should.have.property('name', rule.name); - return callback(); - }); - } - ], done); + 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'); @@ -255,7 +284,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); @@ -272,43 +301,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() { @@ -321,22 +360,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); @@ -349,24 +391,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() { @@ -379,46 +428,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) { @@ -429,19 +486,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..544be510 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..cb2b9d50 100644 --- a/test/unit/axn_param_utest.js +++ b/test/unit/axn_param_utest.js @@ -31,10 +31,9 @@ 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}', @@ -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 }' }, - 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,12 +89,12 @@ 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}' }, - template: 'this is \"${t}\"' + template: 'this is "${t}"' }, options = smsAction.buildSMSOptions(action, event); @@ -142,42 +141,52 @@ 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' }, - template: 'this is \'$\'' + /*jshint quotmark: double */ + template: "this is '$'" + /*jshint quotmark: single */ }, options = smsAction.buildSMSOptions(action, event); should.equal(options.to, 'http://localhost:8080/path/entity'); - should.equal(options.text, 'this is \'$\''); + /*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'}, + var event = { t: 'some text' }, action = { - template: 'this is \'${t}\'' + /*jshint quotmark: double */ + template: "this is '${t}'" + /*jshint quotmark: single */ }, options = twitterAction.buildTwitterOptions(action, event); - - should.equal(options.text, 'this is \'some text\''); + /*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'}, + var event = { x: 1, y: 'abc', z: '***', t: 'some text' }, action = { - template: 'this is \'$\'' + /*jshint quotmark: double */ + template: "this is '$'" + /*jshint quotmark: single */ }, options = twitterAction.buildTwitterOptions(action, event); - - should.equal(options.text, 'this is \'$\''); + /*jshint quotmark: double */ + should.equal(options.text, "this is '$'"); + /*jshint quotmark: single */ }); }); 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}', @@ -198,7 +207,7 @@ 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', @@ -223,7 +232,7 @@ 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', @@ -241,9 +250,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}', @@ -287,7 +307,7 @@ 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: [ @@ -335,7 +355,7 @@ 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: [ @@ -358,5 +378,3 @@ describe('AxnParams', function() { }); }); }); - - diff --git a/test/unit/metrics_servicetime_avg.js b/test/unit/metrics_servicetime_avg.js index 73cdcf99..cb176e21 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..6190601a 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..bb7c978e 100644 --- a/test/unit/notice_timestamp.js +++ b/test/unit/notice_timestamp.js @@ -26,28 +26,27 @@ 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' } } ] @@ -57,7 +56,7 @@ 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; @@ -140,8 +139,8 @@ describe('Notices', function() { metadatas: [ { name: 'when', - 'type' : 'DateTime', - 'value' : iso8601 + type: 'DateTime', + value: iso8601 } ] }); @@ -166,8 +165,8 @@ 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 } ] }); @@ -191,7 +190,7 @@ describe('Notices', function() { metadatas: [ { name: 'TimeInstant', - 'value': iso8601 + value: iso8601 } ] }); @@ -205,4 +204,3 @@ describe('Notices', function() { }); }); }); - diff --git a/test/unit/notices_Do.js b/test/unit/notices_Do.js index 89884d04..90c48695 100644 --- a/test/unit/notices_Do.js +++ b/test/unit/notices_Do.js @@ -35,83 +35,79 @@ chai.Should(); chai.use(sinonChai); var noticeExampleV1 = JSON.stringify({ - 'subscriptionId': '5b34e37052a01bc4c7e67c34', - 'originator': 'localhost', - 'contextResponses': [ + subscriptionId: '5b34e37052a01bc4c7e67c34', + originator: 'localhost', + contextResponses: [ { - 'contextElement': { - 'type': 'tipeExample1', - 'isPattern': 'false', - 'id': 'sensor-1', - 'attributes': [ + contextElement: { + type: 'tipeExample1', + isPattern: 'false', + id: 'sensor-1', + attributes: [ { - 'name': 'Attr1', - 'type': 'Number', - 'value': '123' + name: 'Attr1', + type: 'Number', + value: '123' } ] } } ], - 'subservice': '/test/notices/unit', - 'service': 'utest' + subservice: '/test/notices/unit', + service: 'utest' }); -var noticeExampleV2 = JSON.stringify({ - 'subscriptionId': '5b311ccb29adb333f843b5f3', - 'data': [ +var noticeExampleV2 = JSON.stringify({ + subscriptionId: '5b311ccb29adb333f843b5f3', + data: [ { - 'id': 'sensorv2-1', - 'type': 'tipeExamplev21', - 'Attr1': { - 'type': 'Number', - 'value': 122, - 'metadata': {} + id: 'sensorv2-1', + type: 'tipeExamplev21', + Attr1: { + type: 'Number', + value: 122, + metadata: {} } } ], - 'subservice': '/test/notices/unitv2', - 'service': 'utestv2' + subservice: '/test/notices/unitv2', + service: 'utestv2' }); // Core mocks var coreNotice1 = { - 'id': 'ent1', - 'type': 'Room', - 'service': 'utest', - 'subservice': '/test/notices/unit' + id: 'ent1', + type: 'Room', + service: 'utest', + subservice: '/test/notices/unit' }; describe('Notices Do', function() { - describe('#DoNotice', function() { var v1notice, v2notice; - beforeEach(function () { + beforeEach(function() { v1notice = JSON.parse(noticeExampleV1); v2notice = JSON.parse(noticeExampleV2); }); - it('should accept NGSIv1 entities', function (done) { - + it('should accept NGSIv1 entities', function(done) { var postEvent = 'POST_EVENT'; - var alarmReleaseMock = sinon.spy(function () {}); - var processCBNoticeMock = sinon.spy(function () { + var alarmReleaseMock = sinon.spy(function() {}); + var processCBNoticeMock = sinon.spy(function() { return coreNotice1; }); - var requestWOMetricsMock = sinon.spy( - function (method, option, callback) { - callback(null, {'httpCode': '200', 'message': 'all right'}); - } - ); + var requestWOMetricsMock = sinon.spy(function(method, option, callback) { + callback(null, { httpCode: '200', message: 'all right' }); + }); notices.__with__({ - 'processCBNotice': processCBNoticeMock, + processCBNotice: processCBNoticeMock, 'myutils.requestHelperWOMetrics': requestWOMetricsMock, 'config.perseoCore.noticesURL': 'http://mokedurl.org', 'alarm.release': alarmReleaseMock, 'alarm.POST_EVENT': postEvent - })(function () { - var callback = function (e, request) { + })(function() { + var callback = function(e, request) { should.exist(request); request.should.not.be.instanceof(Error); should.equal(request.length, 1); @@ -120,7 +116,7 @@ describe('Notices Do', function() { processCBNoticeMock.should.have.been.calledWith('utest', '/test/notices/unit', v1notice, 0); processCBNoticeMock.should.be.calledOnce; // Checking call to requestWOMetrics - var h = {'fiware-servicepath': '/test/notices/unit'}; + var h = { 'fiware-servicepath': '/test/notices/unit' }; requestWOMetricsMock.should.have.been.calledWith('post', { url: 'http://mokedurl.org', json: coreNotice1, @@ -136,8 +132,7 @@ describe('Notices Do', function() { }); it('should fail whith empty notice', function(done) { - - var callback = function (e, request) { + var callback = function(e, request) { should.exist(e); should.not.exist(request); should.equal(e.httpCode, 400); @@ -149,38 +144,36 @@ describe('Notices Do', function() { }); it('should fail whith invalid subservice', function(done) { - - var callback = function (e, request) { + var callback = function(e, request) { should.exist(e); should.not.exist(request); should.equal(e.httpCode, 400); - should.equal(e.message, 'invalid notice format Subservice must be' + - ' a comma-separated list of servicePath'); + should.equal( + e.message, + 'invalid notice format Subservice must be' + ' a comma-separated list of servicePath' + ); done(); }; - notices.Do({data:[], subservice:123}, callback); + notices.Do({ data: [], subservice: 123 }, callback); }); it('should accept NGSIv2 entities', function(done) { - var postEvent = 'POST_EVENT'; - var alarmReleaseMock = sinon.spy(function () {}); - var processCBv2NoticeMock = sinon.spy(function () { + var alarmReleaseMock = sinon.spy(function() {}); + var processCBv2NoticeMock = sinon.spy(function() { return coreNotice1; }); - var requestWOMetricsMock = sinon.spy( - function (method, option, callback) { - callback(null, {'httpCode': '200', 'message': 'all right'}); - } - ); + var requestWOMetricsMock = sinon.spy(function(method, option, callback) { + callback(null, { httpCode: '200', message: 'all right' }); + }); notices.__with__({ 'myutils.requestHelperWOMetrics': requestWOMetricsMock, 'config.perseoCore.noticesURL': 'http://mokedurl.org', 'alarm.release': alarmReleaseMock, 'alarm.POST_EVENT': postEvent, - 'processCBv2Notice': processCBv2NoticeMock - })(function () { - var callback = function (e, request) { + processCBv2Notice: processCBv2NoticeMock + })(function() { + var callback = function(e, request) { should.exist(request); request.should.not.be.instanceof(Error); should.equal(request.length, 1); @@ -189,7 +182,7 @@ describe('Notices Do', function() { processCBv2NoticeMock.should.have.been.calledWith('utestv2', '/test/notices/unitv2', v2notice, 0); processCBv2NoticeMock.should.be.calledOnce; // Checking call to requestWOMetrics - var h = {'fiware-servicepath': '/test/notices/unit'}; + var h = { 'fiware-servicepath': '/test/notices/unit' }; requestWOMetricsMock.should.have.been.calledWith('post', { url: 'http://mokedurl.org', json: coreNotice1, @@ -205,23 +198,22 @@ describe('Notices Do', function() { }); it('should process Errors correctly', function(done) { - var postEvent = 'POST_EVENT'; - var alarmReleaseMock = sinon.spy(function () {}); + var alarmReleaseMock = sinon.spy(function() {}); var errorLocNotice = new notices.errors.InvalidLocation('Location_Mock'); errorLocNotice.httpCode = 500; - var processCBv2NoticeMock = sinon.spy(function () { + var processCBv2NoticeMock = sinon.spy(function() { return errorLocNotice; }); var logErrorMock = sinon.spy(); notices.__with__({ - 'processCBv2Notice': processCBv2NoticeMock, + processCBv2Notice: processCBv2NoticeMock, 'myutils.logErrorIf': logErrorMock, 'alarm.POST_EVENT': postEvent, 'config.perseoCore.noticesURL': 'http://mokedurl.org', - 'alarm.release': alarmReleaseMock, - })(function () { - var callback = function (e, request) { + 'alarm.release': alarmReleaseMock + })(function() { + var callback = function(e, request) { should.not.exists(request); should.exist(e); // Check invalid Location error @@ -240,30 +232,25 @@ describe('Notices Do', function() { }); it('should process Error from core', function(done) { - var postEvent = 'POST_EVENT'; - var alarmRaiseMock = sinon.spy(function () {}); - var processCBv2NoticeMock = sinon.spy(function () { + var alarmRaiseMock = sinon.spy(function() {}); + var processCBv2NoticeMock = sinon.spy(function() { return coreNotice1; }); - var requestWOMetricsMock = sinon.spy( - function (method, option, callback) { - callback('errorMock!'); - } - ); - var logErrorMock = sinon.spy( - function(notice) {} - ); + var requestWOMetricsMock = sinon.spy(function(method, option, callback) { + callback('errorMock!'); + }); + var logErrorMock = sinon.spy(function(notice) {}); notices.__with__({ 'myutils.requestHelperWOMetrics': requestWOMetricsMock, 'config.perseoCore.noticesURL': 'http://mokedurl.org', 'alarm.raise': alarmRaiseMock, 'alarm.POST_EVENT': postEvent, - 'processCBv2Notice': processCBv2NoticeMock, - 'config.nextCore': {noticesURL: 'http://nextCoreMockURL'}, - 'myutils.logErrorIf': logErrorMock, - })(function () { - var callback = function (e, request) { + processCBv2Notice: processCBv2NoticeMock, + 'config.nextCore': { noticesURL: 'http://nextCoreMockURL' }, + 'myutils.logErrorIf': logErrorMock + })(function() { + var callback = function(e, request) { should.exist(e); should.not.exists(request); should.equal(e.httpCode, 400); @@ -271,7 +258,7 @@ describe('Notices Do', function() { processCBv2NoticeMock.should.have.been.calledWith('utestv2', '/test/notices/unitv2', v2notice, 0); processCBv2NoticeMock.should.be.calledOnce; // Checking call to requestWOMetrics - var h = {'fiware-servicepath': '/test/notices/unit'}; + var h = { 'fiware-servicepath': '/test/notices/unit' }; should.equal(requestWOMetricsMock.calledTwice, true); expect(requestWOMetricsMock).to.have.been.calledWith('post', { url: 'http://mokedurl.org', @@ -295,8 +282,7 @@ describe('Notices Do', function() { }); it('should fail with invalid NGSIv2 data', function(done) { - - var callback = function (e, request) { + var callback = function(e, request) { should.not.exists(request); should.exist(e); // Check invalid notice error @@ -304,11 +290,11 @@ describe('Notices Do', function() { should.equal(e.message, 'invalid NGSIv2 notice format data must be an array, not a number'); done(); }; - v2notice.data =123; + v2notice.data = 123; notices.Do(v2notice, callback); }); it('should fail with invalid NGSIv1 contextResponses', function(done) { - var callback = function (e, request) { + var callback = function(e, request) { should.not.exists(request); should.exist(e); // Check invalid Location error @@ -316,13 +302,12 @@ describe('Notices Do', function() { should.equal(e.message, 'ContextResponses is not an array (number)'); done(); }; - v1notice.contextResponses =123; + v1notice.contextResponses = 123; notices.Do(v1notice, callback); }); it('should fail whith invalid Servipaths', function(done) { - - var callback = function (e, request) { + var callback = function(e, request) { should.exist(e); should.not.exist(request); should.equal(e.httpCode, 400); @@ -333,4 +318,4 @@ describe('Notices Do', function() { notices.Do(v1notice, callback); }); }); -}); \ No newline at end of file +}); diff --git a/test/unit/notices_processCBNotice.js b/test/unit/notices_processCBNotice.js index f4352374..7db89f88 100644 --- a/test/unit/notices_processCBNotice.js +++ b/test/unit/notices_processCBNotice.js @@ -44,26 +44,26 @@ var subservice = '/test/notices/unit'; var service = 'utest'; var noticeExampleV1 = JSON.stringify({ - 'subscriptionId': '5b311ccb29adb333f843b5f3', - 'originator': 'localhost', - 'contextResponses': [ + subscriptionId: '5b311ccb29adb333f843b5f3', + originator: 'localhost', + contextResponses: [ { - 'contextElement': { - 'id': id, - 'type': type, - 'isPattern': 'false', - 'attributes': [ + contextElement: { + id: id, + type: type, + isPattern: 'false', + attributes: [ { - 'name': attrKey, - 'type': attrType, - 'value': attrValue + name: attrKey, + type: attrType, + value: attrValue } ] } } ], - 'subservice': subservice, - 'service': service + subservice: subservice, + service: service }); var processCBNotice = notices.__get__('processCBNotice'); @@ -71,7 +71,7 @@ var processCBNotice = notices.__get__('processCBNotice'); // Mocks var mockedUid = 'MockedUID_'; var mockedDateMilis = 442796400000; -var uuidMock = sinon.spy(function () { +var uuidMock = sinon.spy(function() { return mockedUid; }); var dateNowMock = sinon.spy(function() { @@ -90,7 +90,6 @@ var x = 441298.13043762115; var y = 4474481.316254241; var locValue = lat + ', ' + long; - describe('Notices NGSIv1', function() { var noticeExample; beforeEach(function() { @@ -98,13 +97,11 @@ describe('Notices NGSIv1', function() { noticeExample = JSON.parse(noticeExampleV1); }); describe('#processCBNotice', function() { - it('should accept simple notice using Number type', function(done) { - notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock - })(function () { + })(function() { var noticeResult = processCBNotice(service, subservice, noticeExample, 0); expect(noticeResult.noticeId).to.equal(mockedUid); expect(noticeResult.noticeTS).to.equal(mockedDateMilis); @@ -120,7 +117,6 @@ describe('Notices NGSIv1', function() { }); it('should accept simple notice using geo:point type', function(done) { - var parseLocationMock = sinon.spy(function() { return { lat: lat, @@ -132,8 +128,8 @@ describe('Notices NGSIv1', function() { notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - 'parseLocation': parseLocationMock - })(function () { + parseLocation: parseLocationMock + })(function() { noticeExample.contextResponses[0].contextElement.attributes[0].type = locType; noticeExample.contextResponses[0].contextElement.attributes[0].value = locValue; var noticeResult = processCBNotice(service, subservice, noticeExample, 0); @@ -157,23 +153,22 @@ describe('Notices NGSIv1', function() { }); it('should accept simple notice using DateTime type', function(done) { - var parseDateMock = sinon.spy(function() { return { - 'ts': 1528018286296, - 'day': 3, - 'month': 6, - 'year': 2018, - 'hour': 11, - 'minute': 31, - 'second': 26 + ts: 1528018286296, + day: 3, + month: 6, + year: 2018, + hour: 11, + minute: 31, + second: 26 }; }); notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - 'parseDate': parseDateMock - })(function () { + parseDate: parseDateMock + })(function() { noticeExample.contextResponses[0].contextElement.attributes[0].type = dateType; noticeExample.contextResponses[0].contextElement.attributes[0].value = dateValue; var noticeResult = processCBNotice(service, subservice, noticeExample, 0); @@ -200,17 +195,18 @@ describe('Notices NGSIv1', function() { }); it('should accept notices including metadata without type', function(done) { - var at = 'theMetaAttribute'; var metaAtVal = 'mockedValue1234'; notices.__with__({ 'uuid.v1': uuidMock, - 'Date.now': dateNowMock, - })(function () { - noticeExample.contextResponses[0].contextElement.attributes[0].metadatas = [{ - 'name': at, - 'value': metaAtVal - }]; + 'Date.now': dateNowMock + })(function() { + noticeExample.contextResponses[0].contextElement.attributes[0].metadatas = [ + { + name: at, + value: metaAtVal + } + ]; var noticeResult = processCBNotice(service, subservice, noticeExample, 0); expect(noticeResult.noticeId).to.equal(mockedUid); expect(noticeResult.noticeTS).to.equal(mockedDateMilis); @@ -228,29 +224,30 @@ describe('Notices NGSIv1', function() { }); it('should accept notice using DateTime metadata', function(done) { - var at = 'theMetaAttribute'; - var parseDateMock = sinon.spy(function () { + var parseDateMock = sinon.spy(function() { return { - 'ts': 1528018286296, - 'day': 3, - 'month': 6, - 'year': 2018, - 'hour': 11, - 'minute': 31, - 'second': 26 + ts: 1528018286296, + day: 3, + month: 6, + year: 2018, + hour: 11, + minute: 31, + second: 26 }; }); notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - 'parseDate': parseDateMock - })(function () { - noticeExample.contextResponses[0].contextElement.attributes[0].metadatas = [{ - 'name': at, - 'value': dateValue, - 'type': dateType - }]; + parseDate: parseDateMock + })(function() { + noticeExample.contextResponses[0].contextElement.attributes[0].metadatas = [ + { + name: at, + value: dateValue, + type: dateType + } + ]; var noticeResult = processCBNotice(service, subservice, noticeExample, 0); expect(noticeResult.noticeId).to.equal(mockedUid); expect(noticeResult.noticeTS).to.equal(mockedDateMilis); @@ -280,8 +277,9 @@ describe('Notices NGSIv1', function() { var noticeResult = processCBNotice(service, subservice, noticeExample, 0); noticeResult.should.be.instanceof(notices.errors.IdAsAttribute); expect(noticeResult.name).to.equal('ID_ATTRIBUTE'); - expect(noticeResult.message).to.equal('id as attribute ' + JSON.stringify(noticeExample.contextResponses[0] - .contextElement.attributes[0])); + expect(noticeResult.message).to.equal( + 'id as attribute ' + JSON.stringify(noticeExample.contextResponses[0].contextElement.attributes[0]) + ); expect(noticeResult.httpCode).to.equal(400); }); @@ -290,93 +288,87 @@ describe('Notices NGSIv1', function() { var noticeResult = processCBNotice(service, subservice, noticeExample, 0); noticeResult.should.be.instanceof(notices.errors.TypeAsAttribute); expect(noticeResult.name).to.equal('TYPE_ATTRIBUTE'); - expect(noticeResult.message).to.equal('type as attribute ' + - JSON.stringify(noticeExample.contextResponses[0].contextElement.attributes[0])); + expect(noticeResult.message).to.equal( + 'type as attribute ' + JSON.stringify(noticeExample.contextResponses[0].contextElement.attributes[0]) + ); expect(noticeResult.httpCode).to.equal(400); }); // Weird functionality - it('should accept notices and parse value as location when exist an attribute named location in metadata', - function(done) { - - // this feature does not seem to make sense - var at = 'location'; - var parseLocationMock = sinon.spy(function() { - return { - lat: lat, - lon: long, - x: x, - y: y - }; - }); - notices.__with__({ - 'uuid.v1': uuidMock, - 'Date.now': dateNowMock, - 'parseLocation': parseLocationMock - })(function () { - noticeExample.contextResponses[0].contextElement.attributes[0].metadatas = [{ - 'name': at, - 'value': locValue, - 'type': locType - }]; - var noticeResult = processCBNotice(service, subservice, noticeExample, 0); - expect(noticeResult.noticeId).to.equal(mockedUid); - expect(noticeResult.noticeTS).to.equal(mockedDateMilis); - expect(noticeResult.id).to.equal(id); - expect(noticeResult.type).to.equal(type); - expect(noticeResult.subservice).to.equal(subservice); - expect(noticeResult.service).to.equal(service); - expect(noticeResult.isPattern).to.equal('false'); - expect(noticeResult[attrKey + '__type']).to.equal(attrType); - expect(noticeResult[attrKey]).to.equal(attrValue); - expect(noticeResult[attrKey + '__metadata__' + at]).to.equal(locValue); - expect(noticeResult[attrKey + '__metadata__' + at + '__type']).to.equal(locType); - expect(noticeResult[attrKey + '__lat']).to.equal(lat); - expect(noticeResult[attrKey + '__lon']).to.equal(long); - expect(noticeResult[attrKey + '__x']).to.equal(x); - expect(noticeResult[attrKey + '__y']).to.equal(y); - - // Why call parselocation with the attribute value and not with location metadata attribute? - parseLocationMock.should.have.been.calledWith(attrValue); - parseLocationMock.should.be.calledOnce; - done(); - }); - } - ); + it('should accept notices and parse value as location when exist an attribute named location in metadata', function(done) { + // this feature does not seem to make sense + var at = 'location'; + var parseLocationMock = sinon.spy(function() { + return { + lat: lat, + lon: long, + x: x, + y: y + }; + }); + notices.__with__({ + 'uuid.v1': uuidMock, + 'Date.now': dateNowMock, + parseLocation: parseLocationMock + })(function() { + noticeExample.contextResponses[0].contextElement.attributes[0].metadatas = [ + { + name: at, + value: locValue, + type: locType + } + ]; + var noticeResult = processCBNotice(service, subservice, noticeExample, 0); + expect(noticeResult.noticeId).to.equal(mockedUid); + expect(noticeResult.noticeTS).to.equal(mockedDateMilis); + expect(noticeResult.id).to.equal(id); + expect(noticeResult.type).to.equal(type); + expect(noticeResult.subservice).to.equal(subservice); + expect(noticeResult.service).to.equal(service); + expect(noticeResult.isPattern).to.equal('false'); + expect(noticeResult[attrKey + '__type']).to.equal(attrType); + expect(noticeResult[attrKey]).to.equal(attrValue); + expect(noticeResult[attrKey + '__metadata__' + at]).to.equal(locValue); + expect(noticeResult[attrKey + '__metadata__' + at + '__type']).to.equal(locType); + expect(noticeResult[attrKey + '__lat']).to.equal(lat); + expect(noticeResult[attrKey + '__lon']).to.equal(long); + expect(noticeResult[attrKey + '__x']).to.equal(x); + expect(noticeResult[attrKey + '__y']).to.equal(y); - it('should catch correctly errors', - function(done) { + // Why call parselocation with the attribute value and not with location metadata attribute? + parseLocationMock.should.have.been.calledWith(attrValue); + parseLocationMock.should.be.calledOnce; + done(); + }); + }); - var error = new Error('fake error'); - var parseLocationMock = sinon.stub().throws(error); - var logErrorMock = sinon.spy( - function(notice) {} - ); - notices.__with__({ - 'uuid.v1': uuidMock, - 'Date.now': dateNowMock, - 'parseLocation': parseLocationMock, - 'myutils.logErrorIf': logErrorMock - })(function () { - noticeExample.contextResponses[0].contextElement.attributes[0].type = locType; - noticeExample.contextResponses[0].contextElement.attributes[0].value = locValue; - var noticeResult = processCBNotice(service, subservice, noticeExample, 0); - noticeResult.should.be.instanceof(notices.errors.InvalidNotice); - expect(noticeResult.name).to.equal('INVALID_NOTICE'); - expect(noticeResult.message).to.equal('invalid notice format ' + JSON.stringify(noticeExample)); - expect(noticeResult.httpCode).to.equal(400); - expect(parseLocationMock).to.throw(Error); - expect(parseLocationMock).to.have.been.calledWith(locValue); - // Checking logError - logErrorMock.should.have.been.calledWith(noticeResult); - logErrorMock.should.be.calledOnce; - done(); - }); - } - ); + it('should catch correctly errors', function(done) { + var error = new Error('fake error'); + var parseLocationMock = sinon.stub().throws(error); + var logErrorMock = sinon.spy(function(notice) {}); + notices.__with__({ + 'uuid.v1': uuidMock, + 'Date.now': dateNowMock, + parseLocation: parseLocationMock, + 'myutils.logErrorIf': logErrorMock + })(function() { + noticeExample.contextResponses[0].contextElement.attributes[0].type = locType; + noticeExample.contextResponses[0].contextElement.attributes[0].value = locValue; + var noticeResult = processCBNotice(service, subservice, noticeExample, 0); + noticeResult.should.be.instanceof(notices.errors.InvalidNotice); + expect(noticeResult.name).to.equal('INVALID_NOTICE'); + expect(noticeResult.message).to.equal('invalid notice format ' + JSON.stringify(noticeExample)); + expect(noticeResult.httpCode).to.equal(400); + expect(parseLocationMock).to.throw(Error); + expect(parseLocationMock).to.have.been.calledWith(locValue); + // Checking logError + logErrorMock.should.have.been.calledWith(noticeResult); + logErrorMock.should.be.calledOnce; + done(); + }); + }); it('should fail parsing invalid location attribute', function(done) { - var error = new notices.errors.InvalidLocation('fake error'); var parseLocationMock = sinon.spy(function() { return error; @@ -384,8 +376,8 @@ describe('Notices NGSIv1', function() { notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - 'parseLocation': parseLocationMock - })(function () { + parseLocation: parseLocationMock + })(function() { noticeExample.contextResponses[0].contextElement.attributes[0].type = locType; noticeExample.contextResponses[0].contextElement.attributes[0].value = locValue; var noticeResult = processCBNotice(service, subservice, noticeExample, 0); @@ -398,6 +390,5 @@ describe('Notices NGSIv1', function() { done(); }); }); - }); }); diff --git a/test/unit/notices_processCBv2Notice.js b/test/unit/notices_processCBv2Notice.js index 5b67a1e2..4839a2f6 100644 --- a/test/unit/notices_processCBv2Notice.js +++ b/test/unit/notices_processCBv2Notice.js @@ -43,20 +43,20 @@ var subservice = '/test/notices/unit'; var service = 'utest'; var noticeExampleV2 = { - 'subscriptionId': '5b311ccb29adb333f843b5f3', - 'data': [ + subscriptionId: '5b311ccb29adb333f843b5f3', + data: [ { - 'id': id, - 'type': type, + id: id, + type: type } ], - 'subservice': subservice, - 'service': service + subservice: subservice, + service: service }; var attrKey = 'Attr1'; noticeExampleV2.data[0][attrKey] = { - 'type': attrType, - 'value': attrValue + type: attrType, + value: attrValue }; noticeExampleV2 = JSON.stringify(noticeExampleV2); @@ -65,7 +65,7 @@ var processCBv2Notice = notices.__get__('processCBv2Notice'); // Mocks var mockedUid = 'MockedUID_'; var mockedDateMilis = 442796400000; -var uuidMock = sinon.spy(function () { +var uuidMock = sinon.spy(function() { return mockedUid; }); var dateNowMock = sinon.spy(function() { @@ -91,13 +91,11 @@ describe('Notices NGSIv2', function() { noticeExample = JSON.parse(noticeExampleV2); }); describe('#processCBv2Notice', function() { - it('should accept simple notice using Number type', function(done) { - notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock - })(function () { + })(function() { var noticeResult = processCBv2Notice(service, subservice, noticeExample, 0); expect(noticeResult.noticeId).to.equal(mockedUid); expect(noticeResult.noticeTS).to.equal(mockedDateMilis); @@ -113,7 +111,6 @@ describe('Notices NGSIv2', function() { }); it('should accept simple notice using DateTime', function(done) { - var parseDateMock = sinon.spy(function() { return { a: 123, @@ -124,8 +121,8 @@ describe('Notices NGSIv2', function() { notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - 'parseDate': parseDateMock, - })(function () { + parseDate: parseDateMock + })(function() { noticeExample.data[0][attrKey].type = dateType; noticeExample.data[0][attrKey].value = dateValue; var noticeResult = processCBv2Notice(service, subservice, noticeExample, 0); @@ -146,7 +143,6 @@ describe('Notices NGSIv2', function() { }); it('should accept simple notice using geo:point type', function(done) { - var parseLocationMock = sinon.spy(function() { return { lat: lat, @@ -159,8 +155,8 @@ describe('Notices NGSIv2', function() { notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - 'parseLocation': parseLocationMock - })(function () { + parseLocation: parseLocationMock + })(function() { noticeExample.data[0][attrKey].type = locType; noticeExample.data[0][attrKey].value = locValue; var noticeResult = processCBv2Notice(service, subservice, noticeExample, 0); @@ -183,16 +179,15 @@ describe('Notices NGSIv2', function() { }); it('should accept notices including metadata without type', function(done) { - var at = 'theAttribute'; var metavalue = 'attMetaEXtraValue'; notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock - })(function () { - var meta = noticeExample.data[0].Attr1.metadata = {}; + })(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); @@ -211,7 +206,6 @@ describe('Notices NGSIv2', function() { }); it('should accept notices including geo:point metadata', function(done) { - var at = 'theAttribute'; var parseLocationMock = sinon.spy(function() { return { @@ -224,12 +218,12 @@ describe('Notices NGSIv2', function() { notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - 'parseLocation': parseLocationMock - })(function () { - var meta = noticeExample.data[0].Attr1.metadata = {}; + parseLocation: parseLocationMock + })(function() { + var meta = (noticeExample.data[0].Attr1.metadata = {}); meta[at] = { - 'value': locValue, - 'type': locType + value: locValue, + type: locType }; var noticeResult = processCBv2Notice(service, subservice, noticeExample, 0); expect(noticeResult.noticeId).to.equal(mockedUid); @@ -253,27 +247,26 @@ describe('Notices NGSIv2', function() { }); it('should accept notices including DateTime metadata', function(done) { - var at = 'theAttribute'; var parseDateMock = sinon.spy(function() { return { - 'ts': 1528018286296, - 'day': 3, - 'month': 6, - 'year': 2018, - 'hour': 11 + ts: 1528018286296, + day: 3, + month: 6, + year: 2018, + hour: 11 // ... }; }); notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - 'parseDate': parseDateMock, - })(function () { - var meta = noticeExample.data[0].Attr1.metadata = {}; + parseDate: parseDateMock + })(function() { + var meta = (noticeExample.data[0].Attr1.metadata = {}); meta[at] = { - 'value': dateValue, - 'type': dateType + value: dateValue, + type: dateType }; var noticeResult = processCBv2Notice(service, subservice, noticeExample, 0); expect(noticeResult.noticeId).to.equal(mockedUid); @@ -298,7 +291,6 @@ describe('Notices NGSIv2', function() { }); it('should fail parsing invalid DateTime metadata attribute', function(done) { - var at = 'theMetaAttribute'; var invalidMetaDate = '2018-96-03T09:31:26.296Z'; // invalid date for metadata var errorDateNotice = new notices.errors.InvalidDateTime(invalidMetaDate); @@ -308,19 +300,20 @@ describe('Notices NGSIv2', function() { notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - 'parseDate': parseDateMock - })(function () { + parseDate: parseDateMock + })(function() { // Set Invalid DateType metadata attribute - var meta = noticeExample.data[0].Attr1.metadata = {}; + var meta = (noticeExample.data[0].Attr1.metadata = {}); meta[at] = { - 'value': invalidMetaDate, - 'type': dateType + value: invalidMetaDate, + type: dateType }; var noticeResult = processCBv2Notice(service, subservice, noticeExample, 0); noticeResult.should.be.instanceof(notices.errors.InvalidDateTime); expect(noticeResult.name).to.equal('INVALID_DATETIME'); - expect(noticeResult.message).to.equal('Invalid ' + dateType + - ' attribute metadata: datetime is not valid ' + invalidMetaDate); + expect(noticeResult.message).to.equal( + 'Invalid ' + dateType + ' attribute metadata: datetime is not valid ' + invalidMetaDate + ); expect(noticeResult.httpCode).to.equal(400); parseDateMock.should.have.been.calledWith(invalidMetaDate); parseDateMock.should.be.calledOnce; @@ -329,8 +322,7 @@ describe('Notices NGSIv2', function() { }); it('should fail parsing invalid DateTime attribute', function(done) { - - var invalidAttDate = '2018-08-32T09:31:26.296Z'; // invalid date for attribute + var invalidAttDate = '2018-08-32T09:31:26.296Z'; // invalid date for attribute var errorDateNotice = new notices.errors.InvalidDateTime(invalidAttDate); var parseDateMock = sinon.spy(function() { return errorDateNotice; @@ -338,18 +330,19 @@ describe('Notices NGSIv2', function() { notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - 'parseDate': parseDateMock - })(function () { + parseDate: parseDateMock + })(function() { // Set Invalid DateType attribute noticeExample.data[0].Attr1 = { - 'value': invalidAttDate, - 'type': dateType + value: invalidAttDate, + type: dateType }; var noticeResult = processCBv2Notice(service, subservice, noticeExample, 0); noticeResult.should.be.instanceof(notices.errors.InvalidDateTime); expect(noticeResult.name).to.equal('INVALID_DATETIME'); - expect(noticeResult.message).to.equal('Invalid ' + dateType + - ' attribute: datetime is not valid ' + invalidAttDate); + expect(noticeResult.message).to.equal( + 'Invalid ' + dateType + ' attribute: datetime is not valid ' + invalidAttDate + ); expect(noticeResult.httpCode).to.equal(400); parseDateMock.should.have.been.calledWith(invalidAttDate); parseDateMock.should.be.calledOnce; @@ -358,8 +351,7 @@ describe('Notices NGSIv2', function() { }); it('should fail parsing invalid location attribute', function(done) { - - var invalidLoc = '47.418889, -3.691944, 12.123'; // invalid location for attribute + var invalidLoc = '47.418889, -3.691944, 12.123'; // invalid location for attribute var locError = new notices.errors.InvalidLocation(invalidLoc); var parseLocationMock = sinon.spy(function() { return locError; @@ -367,18 +359,19 @@ describe('Notices NGSIv2', function() { notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - 'parseLocation': parseLocationMock - })(function () { + parseLocation: parseLocationMock + })(function() { // Set Invalid location attribute noticeExample.data[0].Attr1 = { - 'value': invalidLoc, - 'type': locType + value: invalidLoc, + type: locType }; var noticeResult = processCBv2Notice(service, subservice, noticeExample, 0); noticeResult.should.be.instanceof(notices.errors.InvalidLocation); expect(noticeResult.name).to.equal('INVALID_LOCATION'); - expect(noticeResult.message).to.equal('Invalid ' + locType + - ' attribute: invalid location ' + invalidLoc); + expect(noticeResult.message).to.equal( + 'Invalid ' + locType + ' attribute: invalid location ' + invalidLoc + ); expect(noticeResult.httpCode).to.equal(400); parseLocationMock.should.have.been.calledWith(invalidLoc); parseLocationMock.should.be.calledOnce; @@ -387,9 +380,8 @@ describe('Notices NGSIv2', function() { }); it('should fail parsing invalid location metadata attribute', function(done) { - var at = 'theMetaAttribute'; - var invalidLoc = '47.418889, -3.691944, 12.123'; // invalid location for attribute + var invalidLoc = '47.418889, -3.691944, 12.123'; // invalid location for attribute var locError = new notices.errors.InvalidLocation(invalidLoc); var parseLocationMock = sinon.spy(function() { return locError; @@ -397,19 +389,20 @@ describe('Notices NGSIv2', function() { notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - 'parseLocation': parseLocationMock - })(function () { + parseLocation: parseLocationMock + })(function() { // Set Invalid location metadata attribute - var meta = noticeExample.data[0].Attr1.metadata = {}; + var meta = (noticeExample.data[0].Attr1.metadata = {}); meta[at] = { - 'value': invalidLoc, - 'type': locType + value: invalidLoc, + type: locType }; var noticeResult = processCBv2Notice(service, subservice, noticeExample, 0); noticeResult.should.be.instanceof(notices.errors.InvalidLocation); expect(noticeResult.name).to.equal('INVALID_LOCATION'); - expect(noticeResult.message).to.equal('Invalid ' + locType + - ' attribute metadata: invalid location ' + invalidLoc); + expect(noticeResult.message).to.equal( + 'Invalid ' + locType + ' attribute metadata: invalid location ' + invalidLoc + ); expect(noticeResult.httpCode).to.equal(400); parseLocationMock.should.have.been.calledWith(invalidLoc); parseLocationMock.should.be.calledOnce; @@ -418,31 +411,29 @@ describe('Notices NGSIv2', function() { }); it('should handle exception correctly', function(done) { - var at = 'theMetaAttribute'; var error = new Error('fake error'); var parseLocationMock = sinon.stub().throws(error); - var logErrorMock = sinon.spy( - function(notice) {} - ); + var logErrorMock = sinon.spy(function(notice) {}); notices.__with__({ 'uuid.v1': uuidMock, 'Date.now': dateNowMock, - 'parseLocation': parseLocationMock, + parseLocation: parseLocationMock, 'myutils.logErrorIf': logErrorMock - })(function () { + })(function() { // Set location metadata attribute - var meta = noticeExample.data[0].Attr1.metadata = {}; + var meta = (noticeExample.data[0].Attr1.metadata = {}); meta[at] = { - 'value': locValue, - 'type': locType + value: locValue, + type: locType }; var noticeResult = processCBv2Notice(service, subservice, noticeExample, 0); noticeResult.should.be.instanceof(notices.errors.InvalidV2Notice); expect(noticeResult.name).to.equal('INVALID_NGSIV2_NOTICE'); - expect(noticeResult.message).to.equal('invalid NGSIv2 notice format ' + error + - ' (' + JSON.stringify(noticeExample) +')'); + expect(noticeResult.message).to.equal( + 'invalid NGSIv2 notice format ' + error + ' (' + JSON.stringify(noticeExample) + ')' + ); expect(noticeResult.httpCode).to.equal(400); expect(parseLocationMock).to.throw(Error); expect(parseLocationMock).to.have.been.calledWith(locValue); @@ -454,7 +445,6 @@ describe('Notices NGSIv2', function() { }); }); - describe('#Data types location and time', function() { var noticeExample; beforeEach(function() { @@ -463,28 +453,31 @@ describe('Notices NGSIv2', function() { }); it('should fail parsing invalid location attributes', function() { - var callback = function (e, request) { + var callback = function(e, request) { expect(e).exist; expect(request).not.exist; expect(e.httpCode).to.equal(400); expect(e.message[0]).to.equal('Invalid geo:point attribute: invalid location 47.41x8889, -3.691944, x'); expect(e.message[1]).to.equal('Invalid geo:point attribute metadata: longitude is not valid NaN'); - expect(e.message[2]).to.equal('Invalid geo:point attribute metadata: invalid location Error: ' + - 'Longitude must be in range [-180, 180).'); - expect(e.message[3]).to.equal('Invalid geo:point attribute: invalid location Error: ' + - 'Latitude must be in range [-90, 90).'); + expect(e.message[2]).to.equal( + 'Invalid geo:point attribute metadata: invalid location Error: ' + + 'Longitude must be in range [-180, 180).' + ); + expect(e.message[3]).to.equal( + 'Invalid geo:point attribute: invalid location Error: ' + 'Latitude must be in range [-90, 90).' + ); expect(e.message[4]).to.equal('Invalid geo:point attribute metadata: latitude is not valid NaN'); expect(e.message[5]).to.equal('Invalid geo:point attribute: invalid location 4559'); }; noticeExample.data = [ { - 'id': 'sensor-1', - 'type': 'tipeExample1', - 'Attr1': { - 'type': 'geo:point', - 'value': '47.41x8889, -3.691944, x', - 'metadata': { - 'metaAttr1': { + id: 'sensor-1', + type: 'tipeExample1', + Attr1: { + type: 'geo:point', + value: '47.41x8889, -3.691944, x', + metadata: { + metaAttr1: { type: 'geo:point', value: '47.55555, -ll3.333x-333' } @@ -492,13 +485,13 @@ describe('Notices NGSIv2', function() { } }, { - 'id': 'sensor-2', - 'type': 'tipeExample2', - 'Attr1': { - 'type': 'geo:point', - 'value': '43.41x8889, -5.691944', - 'metadata': { - 'metaAttr1': { + id: 'sensor-2', + type: 'tipeExample2', + Attr1: { + type: 'geo:point', + value: '43.41x8889, -5.691944', + metadata: { + metaAttr1: { type: 'geo:point', value: '47.55555, -ll3.333x-333' } @@ -506,13 +499,13 @@ describe('Notices NGSIv2', function() { } }, { - 'id': 'sensor-3', - 'type': 'tipeExample1', - 'Attr1': { - 'type': 'geo:point', - 'value': '47.418889, -3.691944', - 'metadata': { - 'metaAttr1': { + id: 'sensor-3', + type: 'tipeExample1', + Attr1: { + type: 'geo:point', + value: '47.418889, -3.691944', + metadata: { + metaAttr1: { type: 'geo:point', value: '47.55555, -333.333333' } @@ -520,22 +513,22 @@ describe('Notices NGSIv2', function() { } }, { - 'id': 'sensor-4', - 'type': 'tipeExample1', - 'Attr1': { - 'type': 'geo:point', - 'value': '470.418889, -3.691944', - 'metadata': {} + id: 'sensor-4', + type: 'tipeExample1', + Attr1: { + type: 'geo:point', + value: '470.418889, -3.691944', + metadata: {} } }, { - 'id': 'sensor-5', - 'type': 'tipeExample2', - 'Attr1': { - 'type': 'geo:point', - 'value': '43.41x8889, -5.691944', - 'metadata': { - 'metaAttr1': { + id: 'sensor-5', + type: 'tipeExample2', + Attr1: { + type: 'geo:point', + value: '43.41x8889, -5.691944', + metadata: { + metaAttr1: { type: 'geo:point', value: 'x4x7x.5555x5-, -3.33333' } @@ -543,13 +536,13 @@ describe('Notices NGSIv2', function() { } }, { - 'id': 'sensor-6', - 'type': 'tipeExample2', - 'Attr1': { - 'type': 'geo:point', - 'value': 4559, - 'metadata': { - 'metaAttr1': { + id: 'sensor-6', + type: 'tipeExample2', + Attr1: { + type: 'geo:point', + value: 4559, + metadata: { + metaAttr1: { type: 'geo:point', value: '47.55555, 3.33333' } @@ -557,45 +550,48 @@ describe('Notices NGSIv2', function() { } } ]; - noticeExample.subservice = '/test/notices/unit,/test/notices/unit,/test/notices/unit,' + - '/test/notices/unit,/test/notices/unit,/test/notices/unit'; + noticeExample.subservice = + '/test/notices/unit,/test/notices/unit,/test/notices/unit,' + + '/test/notices/unit,/test/notices/unit,/test/notices/unit'; notices.Do(noticeExample, callback); }); it('should fail parsing invalid DateTime attributes', function() { - var callback = function (e, request) { + var callback = function(e, request) { expect(e).exist; expect(request).not.exist; expect(e.httpCode).to.equal(400); - expect(e.message[0]).to.equal('Invalid DateTime attribute metadata: datetime' + - ' is not valid 2018-96-03T09:31:26.296Z'); - expect(e.message[1]).to.equal('Invalid DateTime attribute: datetime' + - ' is not valid 2018-08-32T09:31:26.296Z'); + expect(e.message[0]).to.equal( + 'Invalid DateTime attribute metadata: datetime' + ' is not valid 2018-96-03T09:31:26.296Z' + ); + expect(e.message[1]).to.equal( + 'Invalid DateTime attribute: datetime' + ' is not valid 2018-08-32T09:31:26.296Z' + ); }; noticeExample.data = [ { - 'id': 'sensor-1', - 'type': 'tipeExample1', - 'Attr1': { - 'type': 'DateTime', - 'value': '2018-06-03T09:31:26.296Z', - 'metadata': { - 'metaAttr1': { - 'value': '2018-96-03T09:31:26.296Z', - 'type': 'DateTime' + id: 'sensor-1', + type: 'tipeExample1', + Attr1: { + type: 'DateTime', + value: '2018-06-03T09:31:26.296Z', + metadata: { + metaAttr1: { + value: '2018-96-03T09:31:26.296Z', + type: 'DateTime' } } } }, { - 'id': 'sensor-2', - 'type': 'tipeExample2', - 'Attr1': { - 'type': 'DateTime', - 'value': '2018-08-32T09:31:26.296Z', - 'metadata': { - 'metaAttr1': { - 'value': '2018-06-03T09:31:26.296Z', - 'type': 'DateTime' + id: 'sensor-2', + type: 'tipeExample2', + Attr1: { + type: 'DateTime', + value: '2018-08-32T09:31:26.296Z', + metadata: { + metaAttr1: { + value: '2018-06-03T09:31:26.296Z', + type: 'DateTime' } } } @@ -605,4 +601,4 @@ describe('Notices NGSIv2', function() { notices.Do(noticeExample, callback); }); }); -}); \ No newline at end of file +}); diff --git a/test/unit/nsr_utest.js b/test/unit/nsr_utest.js index f5195263..a7a86a7a 100644 --- a/test/unit/nsr_utest.js +++ b/test/unit/nsr_utest.js @@ -28,23 +28,23 @@ 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() { @@ -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/updateAction.js b/test/unit/updateAction.js index 60768265..06f901fd 100644 --- a/test/unit/updateAction.js +++ b/test/unit/updateAction.js @@ -34,318 +34,307 @@ var sinonChai = require('sinon-chai'); 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', - 'parameters': { - 'version': '2', - 'attributes': [ + type: 'update', + parameters: { + version: '2', + attributes: [ { - 'name':'streetLightID', - 'type': 'Text', - 'value': '${id}' + name: 'streetLightID', + type: 'Text', + value: '${id}' }, { - 'name':'textNumberLit', - 'type': 'Text', - 'value': 666 + name: 'textNumberLit', + type: 'Text', + value: 666 }, { - 'name':'textBoolLit', - 'type': 'Text', - 'value': false + name: 'textBoolLit', + type: 'Text', + value: false }, { - 'name':'textObjLit', - 'type': 'Text', - 'value': {a: 1, b: 2} + name: 'textObjLit', + type: 'Text', + value: { a: 1, b: 2 } }, { - 'name':'streetLightID', - 'type': 'Text', - 'value': '${id}' + name: 'streetLightID', + type: 'Text', + value: '${id}' }, { - 'name':'illuminanceLevel', - 'type': 'Number', - 'value': '${lastLightIllumNumber}' + name: 'illuminanceLevel', + type: 'Number', + value: '${lastLightIllumNumber}' }, { - 'name':'illuminanceLevel2', - 'type': 'Number', - 'value': '${lastLightIllumStringNumber}' + name: 'illuminanceLevel2', + type: 'Number', + value: '${lastLightIllumStringNumber}' }, { - 'name':'illuminanceLevel3', - 'type': 'Number', - 'value': 12.5 + name: 'illuminanceLevel3', + type: 'Number', + value: 12.5 }, { - 'name':'lastchange', - 'type': 'DateTime', - 'value': '${stringDate}' + name: 'lastchange', + type: 'DateTime', + value: '${stringDate}' }, { - 'name':'lastchange2', - 'type': 'DateTime', - 'value': '${stringDateMs}' + name: 'lastchange2', + type: 'DateTime', + value: '${stringDateMs}' }, { - 'name':'lastchange3', - 'type': 'DateTime', - 'value': '${numberDateMs}' + name: 'lastchange3', + type: 'DateTime', + value: '${numberDateMs}' }, { - 'name':'isBool1', - 'type': 'Boolean', - 'value': '${isconnected}', - 'metadata': metaExample + name: 'isBool1', + type: 'Boolean', + value: '${isconnected}', + metadata: metaExample }, { - 'name':'isBool2', - 'type': 'Boolean', - 'value': 'TRUE' + name: 'isBool2', + type: 'Boolean', + value: 'TRUE' }, { - 'name':'isBool3', - 'type': 'Boolean', - 'value': 'true' + name: 'isBool3', + type: 'Boolean', + value: 'true' }, { - 'name':'isBool4', - 'type': 'Boolean', - 'value': 'False' + name: 'isBool4', + type: 'Boolean', + value: 'False' }, { - 'name':'isBool5', - 'type': 'Boolean', - 'value': 'other' + name: 'isBool5', + type: 'Boolean', + value: 'other' }, { - 'name':'isBool6', - 'type': 'Boolean', - 'value': true + name: 'isBool6', + type: 'Boolean', + value: true }, { - 'name':'isBool7', - 'type': 'Boolean', - 'value': false + name: 'isBool7', + type: 'Boolean', + value: false }, { - 'name':'district', - 'type': 'Text', - 'value': '${areaServed}' + name: 'district', + type: 'Text', + value: '${areaServed}' }, { - 'name':'status', - 'type': 'Text', - 'value': '${laststatus}' + name: 'status', + type: 'Text', + value: '${laststatus}' }, { - 'name':'address', - 'type': 'Address', - 'value': '${streetAddress}, ${addressLocality}' + name: 'address', + type: 'Address', + value: '${streetAddress}, ${addressLocality}' }, { - 'name':'powerState', - 'type': 'Text', - 'value': '${powerState}' + name: 'powerState', + type: 'Text', + value: '${powerState}' }, { - 'name':'refNone', - 'type': '${refNoneType}', - 'value': 'futureNull' + name: 'refNone', + type: '${refNoneType}', + value: 'futureNull' }, { - 'name':'refNone2', - 'type': '${refNoneType}', - 'value': '123' + name: 'refNone2', + type: '${refNoneType}', + value: '123' }, { - 'name':'refNone3', - 'type': '${refNoneType}', - 'value': null + name: 'refNone3', + type: '${refNoneType}', + value: null } ] } }; var event1 = { - 'ruleName': 'switch_on', - 'id': 'AmbientLightSensor:1', - 'type': 'AmbientLightSensor', - 'lastLightIllumNumber': 80, - 'lastLightIllumStringNumber': '69', - 'isconnected': true, - 'streetAddress': 'Vasagatan 1', - 'addressLocality': 'Stockholm', - 'laststatus': 'allright', - 'powerState':'on', - 'stringDate': '2018-12-05T11:31:39.00Z', - 'stringDateMs': '1548843060657', - 'numberDateMs': 1548843229832, - 'subservice': '/', - 'areaServed': 'Stockholm center', - 'service': 'dev_test', - 'refNoneType': 'None', - 'fiwarePerseoContext': { - 'path': '/actions/do', - 'op': '/actions/do', - 'comp': 'perseo-fe', - 'trans': 'f8636710-5fc6-4070-9b1e-8d414fc6522a', - 'corr': 'd5f0a9cc-0258-11e9-b678-0242ac160003; perseocep=15', - 'srv': 'dev_test', - 'subsrv': '/' + ruleName: 'switch_on', + id: 'AmbientLightSensor:1', + type: 'AmbientLightSensor', + lastLightIllumNumber: 80, + lastLightIllumStringNumber: '69', + isconnected: true, + streetAddress: 'Vasagatan 1', + addressLocality: 'Stockholm', + laststatus: 'allright', + powerState: 'on', + stringDate: '2018-12-05T11:31:39.00Z', + stringDateMs: '1548843060657', + numberDateMs: 1548843229832, + subservice: '/', + areaServed: 'Stockholm center', + service: 'dev_test', + refNoneType: 'None', + fiwarePerseoContext: { + path: '/actions/do', + op: '/actions/do', + comp: 'perseo-fe', + trans: 'f8636710-5fc6-4070-9b1e-8d414fc6522a', + corr: 'd5f0a9cc-0258-11e9-b678-0242ac160003; perseocep=15', + srv: 'dev_test', + subsrv: '/' } }; var expectedChanges = { - 'address': { - 'value': 'Vasagatan 1, Stockholm', - 'type': 'Address' + address: { + value: 'Vasagatan 1, Stockholm', + type: 'Address' }, - 'status': { - 'value': 'allright', - 'type': 'Text' + status: { + value: 'allright', + type: 'Text' }, - 'textBoolLit': { - 'value': 'false', - 'type': 'Text' + textBoolLit: { + value: 'false', + type: 'Text' }, - 'textNumberLit': { - 'value': '666', - 'type': 'Text' + textNumberLit: { + value: '666', + type: 'Text' }, - 'textObjLit': { - 'value': '[object Object]', - 'type': 'Text' + textObjLit: { + value: '[object Object]', + type: 'Text' }, - 'refNone': { - 'value': null, - 'type': 'None' + refNone: { + value: null, + type: 'None' }, - 'refNone2': { - 'value': null, - 'type': 'None' + refNone2: { + value: null, + type: 'None' }, - 'refNone3': { - 'value': null, - 'type': 'None' + refNone3: { + value: null, + type: 'None' }, - 'isBool1': { - 'value': true, - 'type': 'Boolean', - 'metadata': metaExample + isBool1: { + value: true, + type: 'Boolean', + metadata: metaExample }, - 'isBool2': { - 'value': true, - 'type': 'Boolean' + isBool2: { + value: true, + type: 'Boolean' }, - 'isBool3': { - 'value': true, - 'type': 'Boolean' + isBool3: { + value: true, + type: 'Boolean' }, - 'isBool4': { - 'value': false, - 'type': 'Boolean' + isBool4: { + value: false, + type: 'Boolean' }, - 'isBool5': { - 'value': false, - 'type': 'Boolean' + isBool5: { + value: false, + type: 'Boolean' }, - 'isBool6': { - 'value': true, - 'type': 'Boolean' + isBool6: { + value: true, + type: 'Boolean' }, - 'isBool7': { - 'value': false, - 'type': 'Boolean' + isBool7: { + value: false, + type: 'Boolean' }, - 'powerState': { - 'value': 'on', - 'type': 'Text' + powerState: { + value: 'on', + type: 'Text' }, - 'illuminanceLevel': { - 'value': 80, - 'type': 'Number' + illuminanceLevel: { + value: 80, + type: 'Number' }, - 'illuminanceLevel2': { - 'value': 69, - 'type': 'Number' + illuminanceLevel2: { + value: 69, + type: 'Number' }, - 'illuminanceLevel3': { - 'value': 12.5, - 'type': 'Number' + illuminanceLevel3: { + value: 12.5, + type: 'Number' }, - 'streetLightID': { - 'value': 'AmbientLightSensor:1', - 'type': 'Text' + streetLightID: { + value: 'AmbientLightSensor:1', + type: 'Text' }, - 'district': { - 'value': 'Stockholm center', - 'type': 'Text' + district: { + value: 'Stockholm center', + type: 'Text' }, - 'lastchange': { - 'value': '2018-12-05T11:31:39.000Z', - 'type': 'DateTime' + lastchange: { + value: '2018-12-05T11:31:39.000Z', + type: 'DateTime' }, - 'lastchange2': { - 'value': '2019-01-30T10:11:00.657Z', - 'type': 'DateTime' + lastchange2: { + value: '2019-01-30T10:11:00.657Z', + type: 'DateTime' }, - 'lastchange3': { - 'value': '2019-01-30T10:13:49.832Z', - 'type': 'DateTime' + lastchange3: { + value: '2019-01-30T10:13:49.832Z', + type: 'DateTime' } }; describe('doIt', function() { - describe('#NGSIv2 updateActions', function() { + beforeEach(function() {}); - beforeEach(function () { - }); - - it('should accept NGSIv2 entities', function (done) { - + it('should accept NGSIv2 entities', function(done) { // Mocks - var createEntityThen = sinon.spy(function (successCB, errorCB) { - setTimeout(function () { - successCB({'httpCode': '200', 'message': 'all right'}); // success callback + var createEntityThen = sinon.spy(function(successCB, errorCB) { + setTimeout(function() { + successCB({ httpCode: '200', message: 'all right' }); // success callback }, 0); return '__TEST'; }); - var createEntityMock = sinon.spy( - function (changes, options) { - return {'then': createEntityThen}; - } - ); - var NGSICloseMock = sinon.spy( - function () { - return 'closed'; - } - ); - var NGSIConnectionMock = sinon.spy( - function () { - return { - 'v2': {'createEntity': createEntityMock}, - 'close': NGSICloseMock - }; - } - ); + var createEntityMock = sinon.spy(function(changes, options) { + return { then: createEntityThen }; + }); + var NGSICloseMock = sinon.spy(function() { + return 'closed'; + }); + var NGSIConnectionMock = sinon.spy(function() { + return { + v2: { createEntity: createEntityMock }, + close: NGSICloseMock + }; + }); updateAction.__with__({ 'NGSI.Connection': NGSIConnectionMock - })(function () { - var callback = function (e, request) { + })(function() { + var callback = function(e, request) { should.exist(request); should.not.exist(e); should.equal(request.httpCode, 200); expectedChanges.id = 'AmbientLightSensor:1_NGSIv2Test'; expectedChanges.type = 'NGSIv2TypesTest'; - createEntityMock.should.be.calledOnceWith(expectedChanges, {upsert: true}); + createEntityMock.should.be.calledOnceWith(expectedChanges, { upsert: true }); done(); }; action1.parameters.id = '${id}_NGSIv2Test'; @@ -354,44 +343,37 @@ describe('doIt', function() { }); }); - it('should accept NGSIv2 entities without type and id', function (done) { - + it('should accept NGSIv2 entities without type and id', function(done) { // Mocks - var createEntityThen = sinon.spy(function (successCB, errorCB) { - setTimeout(function () { - successCB({'httpCode': '200', 'message': 'all right'}); // success callback + var createEntityThen = sinon.spy(function(successCB, errorCB) { + setTimeout(function() { + successCB({ httpCode: '200', message: 'all right' }); // success callback }, 0); return '__TEST'; }); - var createEntityMock = sinon.spy( - function (changes, options) { - return {'then': createEntityThen}; - } - ); - var NGSICloseMock = sinon.spy( - function () { - return 'closed'; - } - ); - var NGSIConnectionMock = sinon.spy( - function () { - return { - 'v2': {'createEntity': createEntityMock}, - 'close': NGSICloseMock - }; - } - ); + var createEntityMock = sinon.spy(function(changes, options) { + return { then: createEntityThen }; + }); + var NGSICloseMock = sinon.spy(function() { + return 'closed'; + }); + var NGSIConnectionMock = sinon.spy(function() { + return { + v2: { createEntity: createEntityMock }, + close: NGSICloseMock + }; + }); updateAction.__with__({ 'NGSI.Connection': NGSIConnectionMock - })(function () { - var callback = function (e, request) { + })(function() { + var callback = function(e, request) { should.exist(request); should.not.exist(e); should.equal(request.httpCode, 200); expectedChanges.id = 'AmbientLightSensor:1'; expectedChanges.type = 'AmbientLightSensor'; - createEntityMock.should.be.calledOnceWith(expectedChanges, {upsert: true}); + createEntityMock.should.be.calledOnceWith(expectedChanges, { upsert: true }); done(); }; delete action1.parameters.id; @@ -400,45 +382,38 @@ describe('doIt', function() { }); }); - it('should control failed update actions', function (done) { - + it('should control failed update actions', function(done) { // Mocks var theCBError = new Error(); - var createEntityThen = sinon.spy(function (successCB, errorCB) { - setTimeout(function () { + var createEntityThen = sinon.spy(function(successCB, errorCB) { + setTimeout(function() { errorCB(theCBError); // success callback }, 0); return '__TEST'; }); - var createEntityMock = sinon.spy( - function (changes, options) { - return {'then': createEntityThen}; - } - ); - var NGSICloseMock = sinon.spy( - function () { - return 'closed'; - } - ); - var NGSIConnectionMock = sinon.spy( - function () { - return { - 'v2': {'createEntity': createEntityMock}, - 'close': NGSICloseMock - }; - } - ); + var createEntityMock = sinon.spy(function(changes, options) { + return { then: createEntityThen }; + }); + var NGSICloseMock = sinon.spy(function() { + return 'closed'; + }); + var NGSIConnectionMock = sinon.spy(function() { + return { + v2: { createEntity: createEntityMock }, + close: NGSICloseMock + }; + }); updateAction.__with__({ 'NGSI.Connection': NGSIConnectionMock - })(function () { - var callback = function (e, request) { + })(function() { + var callback = function(e, request) { should.not.exist(request); should.exist(e); e.should.be.instanceof(Error); expectedChanges.id = 'AmbientLightSensor:1_NGSIv2Test'; expectedChanges.type = 'NGSIv2TypesTest'; - createEntityMock.should.be.calledOnceWith(expectedChanges, {upsert: true}); + createEntityMock.should.be.calledOnceWith(expectedChanges, { upsert: true }); done(); }; action1.parameters.id = '${id}_NGSIv2Test'; @@ -446,6 +421,5 @@ describe('doIt', function() { updateAction.doIt(action1, event1, callback); }); }); - }); -}); \ No newline at end of file +}); diff --git a/test/unit/visualrules_utest.js b/test/unit/visualrules_utest.js index d87c069c..f1d1ba48 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..ab43fdf2 100644 --- a/test/utils/testEnvironment.js +++ b/test/utils/testEnvironment.js @@ -76,7 +76,8 @@ function commonBeforeEach(done) { callback(err); }); } - ], done + ], + done ); } function commonAfterEach(done) { diff --git a/test/utils/utilsT.js b/test/utils/utilsT.js index ee1604b4..945d9657 100644 --- a/test/utils/utilsT.js +++ b/test/utils/utilsT.js @@ -45,29 +45,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) { @@ -77,43 +80,49 @@ function dropExecutions(callback) { remove(config.collections.executions, callback); } function dropEntities(callback) { - MongoClient.connect(new URL('v1/updateContext', config.orion.URL), function(err, db) { - if (err) { - return callback(err); - } - db.collection(config.orionDb.collection, {}, function(err, coll) { + MongoClient.connect( + new URL('v1/updateContext', 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); @@ -123,100 +132,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'; @@ -240,22 +264,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; @@ -282,4 +308,3 @@ module.exports.setServerCallback = function(fxn) { fakeServerCallback = fxn; }; module.exports.getConfig = getConfig; -