Update tests for runtime/api separation

This commit is contained in:
Nick O'Leary
2015-11-12 07:56:23 +00:00
parent f43738446e
commit 9f5e6a4b37
53 changed files with 246 additions and 284 deletions

View File

@@ -0,0 +1,484 @@
/**
* Copyright 2014, 2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var should = require("should");
var sinon = require("sinon");
var when = require("when");
var http = require('http');
var express = require('express');
var app = express();
var WebSocket = require('ws');
var comms = require("../../../red/runtime/comms");
var Users = require("../../../red/api/auth/users");
var Tokens = require("../../../red/api/auth/tokens");
var address = '127.0.0.1';
var listenPort = 0; // use ephemeral port
describe("runtime/comms", function() {
describe("with default keepalive", function() {
var server;
var url;
var port;
before(function(done) {
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/comms';
comms.start();
done();
});
});
after(function() {
comms.stop();
});
it('accepts connection', function(done) {
var ws = new WebSocket(url);
ws.on('open', function() {
ws.close();
done();
});
});
it('publishes message after subscription', function(done) {
var ws = new WebSocket(url);
ws.on('open', function() {
ws.send('{"subscribe":"topic1"}');
comms.publish('topic1', 'foo');
});
ws.on('message', function(msg) {
msg.should.equal('{"topic":"topic1","data":"foo"}');
ws.close();
done();
});
});
it('publishes retained message for subscription', function(done) {
comms.publish('topic2', 'bar', true);
var ws = new WebSocket(url);
ws.on('open', function() {
ws.send('{"subscribe":"topic2"}');
});
ws.on('message', function(msg) {
msg.should.equal('{"topic":"topic2","data":"bar"}');
ws.close();
done();
});
});
it('retained message is deleted by non-retained message', function(done) {
comms.publish('topic3', 'retained', true);
comms.publish('topic3', 'non-retained');
var ws = new WebSocket(url);
ws.on('open', function() {
ws.send('{"subscribe":"topic3"}');
comms.publish('topic3', 'new');
});
ws.on('message', function(msg) {
msg.should.equal('{"topic":"topic3","data":"new"}');
ws.close();
done();
});
});
it('malformed messages are ignored',function(done) {
var ws = new WebSocket(url);
ws.on('open', function() {
ws.send('not json');
ws.send('[]');
ws.send('{"subscribe":"topic3"}');
comms.publish('topic3', 'correct');
});
ws.on('message', function(msg) {
msg.should.equal('{"topic":"topic3","data":"correct"}');
ws.close();
done();
});
});
// The following test currently fails due to minimum viable
// implementation. More test should be written to test topic
// matching once this one is passing
if (0) {
it('receives message on correct topic', function(done) {
var ws = new WebSocket(url);
ws.on('open', function() {
ws.send('{"subscribe":"topic4"}');
comms.publish('topic5', 'foo');
comms.publish('topic4', 'bar');
});
ws.on('message', function(msg) {
msg.should.equal('{"topic":"topic4","data":"bar"}');
ws.close();
done();
});
});
}
});
describe("disabled editor", function() {
var server;
var url;
var port;
before(function(done) {
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {disableEditor:true});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/comms';
comms.start();
done();
});
});
after(function() {
comms.stop();
});
it('rejects websocket connections',function(done) {
var ws = new WebSocket(url);
ws.on('open', function() {
done(new Error("Socket connection unexpectedly accepted"));
ws.close();
});
ws.on('error', function() {
done();
});
});
});
describe("non-default httpAdminRoot set: /adminPath", function() {
var server;
var url;
var port;
before(function(done) {
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {httpAdminRoot:"/adminPath"});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/adminPath/comms';
comms.start();
done();
});
});
after(function() {
comms.stop();
});
it('accepts connections',function(done) {
var ws = new WebSocket(url);
ws.on('open', function() {
ws.close();
done();
});
ws.on('error', function() {
done(new Error("Socket connection failed"));
});
});
});
describe("non-default httpAdminRoot set: /adminPath/", function() {
var server;
var url;
var port;
before(function(done) {
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {httpAdminRoot:"/adminPath/"});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/adminPath/comms';
comms.start();
done();
});
});
after(function() {
comms.stop();
});
it('accepts connections',function(done) {
var ws = new WebSocket(url);
ws.on('open', function() {
ws.close();
done();
});
ws.on('error', function() {
done(new Error("Socket connection failed"));
});
});
});
describe("non-default httpAdminRoot set: adminPath", function() {
var server;
var url;
var port;
before(function(done) {
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {httpAdminRoot:"adminPath"});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/adminPath/comms';
comms.start();
done();
});
});
after(function() {
comms.stop();
});
it('accepts connections',function(done) {
var ws = new WebSocket(url);
ws.on('open', function() {
ws.close();
done();
});
ws.on('error', function() {
done(new Error("Socket connection failed"));
});
});
});
describe("keep alives", function() {
var server;
var url;
var port;
before(function(done) {
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {webSocketKeepAliveTime: 100});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/comms';
comms.start();
done();
});
});
after(function() {
comms.stop();
});
it('are sent', function(done) {
var ws = new WebSocket(url);
var count = 0;
ws.on('message', function(data) {
var msg = JSON.parse(data);
msg.should.have.property('topic','hb');
msg.should.have.property('data').be.a.Number;
count++;
if (count == 3) {
ws.close();
done();
}
});
});
it('are not sent if other messages are sent', function(done) {
var ws = new WebSocket(url);
var count = 0;
var interval;
ws.on('open', function() {
ws.send('{"subscribe":"foo"}');
interval = setInterval(function() {
comms.publish('foo', 'bar');
}, 50);
});
ws.on('message', function(data) {
var msg = JSON.parse(data);
// It is possible a heartbeat message may arrive - so ignore them
if (msg.topic != "hb") {
msg.should.have.property('topic', 'foo');
msg.should.have.property('data', 'bar');
count++;
if (count == 5) {
clearInterval(interval);
ws.close();
done();
}
}
});
});
});
describe('authentication required, no anonymous',function() {
var server;
var url;
var port;
var getDefaultUser;
var getUser;
var getToken;
before(function(done) {
getDefaultUser = sinon.stub(Users,"default",function() { return when.resolve(null);});
getUser = sinon.stub(Users,"get", function(username) {
if (username == "fred") {
return when.resolve({permissions:"read"});
} else {
return when.resolve(null);
}
});
getToken = sinon.stub(Tokens,"get",function(token) {
if (token == "1234") {
return when.resolve({user:"fred",scope:["*"]});
} else if (token == "5678") {
return when.resolve({user:"barney",scope:["*"]});
} else {
return when.resolve(null);
}
});
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {adminAuth:{}});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/comms';
comms.start();
done();
});
});
after(function() {
getDefaultUser.restore();
getUser.restore();
getToken.restore();
comms.stop();
});
it('prevents connections that do not authenticate',function(done) {
var ws = new WebSocket(url);
var count = 0;
var interval;
ws.on('open', function() {
ws.send('{"subscribe":"foo"}');
});
ws.on('close', function() {
done();
});
});
it('allows connections that do authenticate',function(done) {
var ws = new WebSocket(url);
var received = 0;
ws.on('open', function() {
ws.send('{"auth":"1234"}');
});
ws.on('message', function(msg) {
received++;
if (received == 1) {
msg.should.equal('{"auth":"ok"}');
ws.send('{"subscribe":"foo"}');
comms.publish('foo', 'correct');
} else {
msg.should.equal('{"topic":"foo","data":"correct"}');
ws.close();
}
});
ws.on('close', function() {
try {
received.should.equal(2);
done();
} catch(err) {
done(err);
}
});
});
it('rejects connections for non-existant token',function(done) {
var ws = new WebSocket(url);
var received = 0;
ws.on('open', function() {
ws.send('{"auth":"2345"}');
});
ws.on('close', function() {
done();
});
});
it('rejects connections for invalid token',function(done) {
var ws = new WebSocket(url);
var received = 0;
ws.on('open', function() {
ws.send('{"auth":"5678"}');
});
ws.on('close', function() {
done();
});
});
});
describe('authentication required, anonymous enabled',function() {
var server;
var url;
var port;
var getDefaultUser;
before(function(done) {
getDefaultUser = sinon.stub(Users,"default",function() { return when.resolve({permissions:"read"});});
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {adminAuth:{}});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/comms';
comms.start();
done();
});
});
after(function() {
getDefaultUser.restore();
comms.stop();
});
it('allows anonymous connections that do not authenticate',function(done) {
var ws = new WebSocket(url);
var count = 0;
var interval;
ws.on('open', function() {
ws.send('{"subscribe":"foo"}');
setTimeout(function() {
comms.publish('foo', 'correct');
},200);
});
ws.on('message', function(msg) {
msg.should.equal('{"topic":"foo","data":"correct"}');
count++;
ws.close();
});
ws.on('close', function() {
try {
count.should.equal(1);
done();
} catch(err) {
done(err);
}
});
});
});
});

View File

@@ -0,0 +1,23 @@
/**
* Copyright 2014 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var should = require("should");
describe("runtime/events", function() {
it('can be required without errors', function() {
require("../../../red/runtime/events");
});
it.skip('more tests needed', function(){})
});

View File

@@ -0,0 +1,22 @@
/**
* Copyright 2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
describe("runtime/i18n", function() {
it('can be required without errors', function() {
require("../../../red/runtime/i18n");
});
it.skip('more tests needed', function(){})
});

View File

@@ -0,0 +1,251 @@
/**
* Copyright 2014, 2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var should = require("should");
var when = require("when");
var sinon = require("sinon");
var path = require("path");
var api = require("../../../red/api");
var runtime = require("../../../red/runtime");
var comms = require("../../../red/runtime/comms");
var redNodes = require("../../../red/runtime/nodes");
var storage = require("../../../red/runtime/storage");
var settings = require("../../../red/runtime/settings");
var log = require("../../../red/runtime/log");
describe("runtime", function() {
var commsMessages = [];
var commsPublish;
beforeEach(function() {
commsMessages = [];
});
afterEach(function() {
if (console.log.restore) {
console.log.restore();
}
})
before(function() {
commsPublish = sinon.stub(comms,"publish", function(topic,msg,retained) {
commsMessages.push({topic:topic,msg:msg,retained:retained});
});
process.env.NODE_RED_HOME = path.resolve(path.join(__dirname,"..","..",".."))
});
after(function() {
commsPublish.restore();
delete process.env.NODE_RED_HOME;
});
describe("init", function() {
beforeEach(function() {
sinon.stub(log,"init",function() {});
sinon.stub(settings,"init",function() {});
sinon.stub(comms,"init",function() {});
});
afterEach(function() {
log.init.restore();
settings.init.restore();
comms.init.restore();
})
it("initialises components", function() {
var dummyServer = {};
runtime.init(dummyServer,{testSettings: true, httpAdminRoot:"/"});
log.init.called.should.be.true;
settings.init.called.should.be.true;
comms.init.called.should.be.true;
});
it("returns version", function() {
var dummyServer = {};
runtime.init(dummyServer,{testSettings: true, httpAdminRoot:"/"});
/^\d+\.\d+\.\d+(-git)?$/.test(runtime.version()).should.be.true;
})
});
describe("start",function() {
var commsInit;
var storageInit;
var settingsLoad;
var logMetric;
var logWarn;
var logInfo;
var logLog;
var redNodesInit;
var redNodesLoad;
var redNodesCleanModuleList;
var redNodesGetNodeList;
var redNodesLoadFlows;
var redNodesStartFlows;
var commsStart;
beforeEach(function() {
commsInit = sinon.stub(comms,"init",function() {});
storageInit = sinon.stub(storage,"init",function(settings) {return when.resolve();});
logMetric = sinon.stub(log,"metric",function() { return false; });
logWarn = sinon.stub(log,"warn",function() { });
logInfo = sinon.stub(log,"info",function() { });
logLog = sinon.stub(log,"log",function(m) {});
redNodesInit = sinon.stub(redNodes,"init", function() {});
redNodesLoad = sinon.stub(redNodes,"load", function() {return when.resolve()});
redNodesCleanModuleList = sinon.stub(redNodes,"cleanModuleList",function(){});
redNodesLoadFlows = sinon.stub(redNodes,"loadFlows",function() {return when.resolve()});
redNodesStartFlows = sinon.stub(redNodes,"startFlows",function() {});
commsStart = sinon.stub(comms,"start",function(){});
});
afterEach(function() {
commsInit.restore();
storageInit.restore();
logMetric.restore();
logWarn.restore();
logInfo.restore();
logLog.restore();
redNodesInit.restore();
redNodesLoad.restore();
redNodesGetNodeList.restore();
redNodesCleanModuleList.restore();
redNodesLoadFlows.restore();
redNodesStartFlows.restore();
commsStart.restore();
});
it("reports errored/missing modules",function(done) {
redNodesGetNodeList = sinon.stub(redNodes,"getNodeList", function(cb) {
return [
{ err:"errored",name:"errName" }, // error
{ module:"module",enabled:true,loaded:false,types:["typeA","typeB"]} // missing
].filter(cb);
});
runtime.init({},{testSettings: true, httpAdminRoot:"/", load:function() { return when.resolve();}});
sinon.stub(console,"log");
runtime.start().then(function() {
console.log.restore();
try {
storageInit.calledOnce.should.be.true;
redNodesInit.calledOnce.should.be.true;
redNodesLoad.calledOnce.should.be.true;
commsStart.calledOnce.should.be.true;
redNodesLoadFlows.calledOnce.should.be.true;
logWarn.calledWithMatch("Failed to register 1 node type");
logWarn.calledWithMatch("Missing node modules");
logWarn.calledWithMatch(" - module: typeA, typeB");
redNodesCleanModuleList.calledOnce.should.be.true;
done();
} catch(err) {
done(err);
}
});
});
it("initiates load of missing modules",function(done) {
redNodesGetNodeList = sinon.stub(redNodes,"getNodeList", function(cb) {
return [
{ err:"errored",name:"errName" }, // error
{ err:"errored",name:"errName" }, // error
{ module:"module",enabled:true,loaded:false,types:["typeA","typeB"]}, // missing
{ module:"node-red",enabled:true,loaded:false,types:["typeC","typeD"]} // missing
].filter(cb);
});
var serverInstallModule = sinon.stub(redNodes,"installModule",function(name) { return when.resolve();});
runtime.init({},{testSettings: true, autoInstallModules:true, httpAdminRoot:"/", load:function() { return when.resolve();}});
sinon.stub(console,"log");
runtime.start().then(function() {
console.log.restore();
try {
logWarn.calledWithMatch("Failed to register 2 node types");
logWarn.calledWithMatch("Missing node modules");
logWarn.calledWithMatch(" - module: typeA, typeB");
logWarn.calledWithMatch(" - node-red: typeC, typeD");
redNodesCleanModuleList.calledOnce.should.be.false;
serverInstallModule.calledOnce.should.be.true;
serverInstallModule.calledWithMatch("module");
done();
} catch(err) {
done(err);
} finally {
serverInstallModule.restore();
}
});
});
it("reports errored modules when verbose is enabled",function(done) {
redNodesGetNodeList = sinon.stub(redNodes,"getNodeList", function(cb) {
return [
{ err:"errored",name:"errName" } // error
].filter(cb);
});
runtime.init({},{testSettings: true, verbose:true, httpAdminRoot:"/", load:function() { return when.resolve();}});
sinon.stub(console,"log");
runtime.start().then(function() {
console.log.restore();
try {
logWarn.neverCalledWithMatch("Failed to register 1 node type");
logWarn.calledWithMatch("[errName] errored");
done();
} catch(err) {
done(err);
}
});
});
it("reports runtime metrics",function(done) {
var commsStop = sinon.stub(comms,"stop",function() {} );
var stopFlows = sinon.stub(redNodes,"stopFlows",function() {} );
redNodesGetNodeList = sinon.stub(redNodes,"getNodeList", function() {return []});
logMetric.restore();
logMetric = sinon.stub(log,"metric",function() { return true; });
runtime.init({},{testSettings: true, runtimeMetricInterval:200, httpAdminRoot:"/", load:function() { return when.resolve();}});
sinon.stub(console,"log");
runtime.start().then(function() {
console.log.restore();
setTimeout(function() {
try {
logLog.args.should.have.lengthOf(3);
logLog.args[0][0].should.have.property("level",log.METRIC);
logLog.args[0][0].should.have.property("event","runtime.memory.rss");
logLog.args[1][0].should.have.property("level",log.METRIC);
logLog.args[1][0].should.have.property("event","runtime.memory.heapTotal");
logLog.args[2][0].should.have.property("level",log.METRIC);
logLog.args[2][0].should.have.property("event","runtime.memory.heapUsed");
done();
} catch(err) {
done(err);
} finally {
runtime.stop();
commsStop.restore();
stopFlows.restore();
}
},300);
});
});
});
it("stops components", function() {
var commsStop = sinon.stub(comms,"stop",function() {} );
var stopFlows = sinon.stub(redNodes,"stopFlows",function() {} );
runtime.stop();
commsStop.called.should.be.true;
stopFlows.called.should.be.true;
commsStop.restore();
stopFlows.restore();
});
});

View File

@@ -0,0 +1,159 @@
/**
* Copyright 2014, 205 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var should = require("should");
var sinon = require("sinon");
var util = require("util");
var log = require("../../../red/runtime/log");
describe("runtime/log", function() {
beforeEach(function () {
var spy = sinon.stub(util, 'log', function(arg){});
var settings = {logging: { console: { level: 'metric', metrics: true } } };
log.init(settings);
});
afterEach(function() {
util.log.restore();
});
it('it can raise an error', function() {
var ret = log.error("This is an error");
sinon.assert.calledWithMatch(util.log,"[error] This is an error");
});
it('it can raise a trace', function() {
var ret = log.trace("This is a trace");
sinon.assert.calledWithMatch(util.log,"[trace] This is a trace");
});
it('it can raise a debug', function() {
var ret = log.debug("This is a debug");
sinon.assert.calledWithMatch(util.log,"[debug] This is a debug");
});
it('it can raise a info', function() {
var ret = log.info("This is an info");
sinon.assert.calledWithMatch(util.log,"[info] This is an info");
});
it('it can raise a warn', function() {
var ret = log.warn("This is a warn");
sinon.assert.calledWithMatch(util.log,"[warn] This is a warn");
});
it('it can raise a metric', function() {
var metrics = {};
metrics.level = log.METRIC;
metrics.nodeid = "testid";
metrics.event = "node.test.testevent";
metrics.msgid = "12345";
metrics.value = "the metric payload";
var ret = log.log(metrics);
util.log.calledOnce.should.be.true;
util.log.firstCall.args[0].indexOf("[metric] ").should.equal(0);
var body = JSON.parse(util.log.firstCall.args[0].substring(9));
body.should.have.a.property("nodeid","testid");
body.should.have.a.property("event","node.test.testevent");
body.should.have.a.property("msgid","12345");
body.should.have.a.property("value","the metric payload");
body.should.have.a.property("timestamp");
body.should.have.a.property("level",log.METRIC);
});
it('it checks metrics are enabled', function() {
log.metric().should.equal(true);
var sett = {logging: { console: { level: 'info', metrics: false } } };
log.init(sett);
log.metric().should.equal(false);
});
it('it logs node type and name if provided',function() {
log.log({level:log.INFO,type:"nodeType",msg:"test",name:"nodeName",id:"nodeId"});
util.log.calledOnce.should.be.true;
util.log.firstCall.args[0].indexOf("[nodeType:nodeName]").should.not.equal(-1);
});
it('it logs node type and id if no name provided',function() {
log.log({level:log.INFO,type:"nodeType",msg:"test",id:"nodeId"});
util.log.calledOnce.should.be.true;
util.log.firstCall.args[0].indexOf("[nodeType:nodeId]").should.not.equal(-1);
});
it('ignores lower level messages and metrics', function() {
var settings = {logging: { console: { level: 'warn', metrics: false } } };
log.init(settings);
log.error("This is an error");
log.warn("This is a warn");
log.info("This is an info");
log.debug("This is a debug");
log.trace("This is a trace");
log.log({level:log.METRIC,msg:"testMetric"});
sinon.assert.calledWithMatch(util.log,"[error] This is an error");
sinon.assert.calledWithMatch(util.log,"[warn] This is a warn");
sinon.assert.neverCalledWithMatch(util.log,"[info] This is an info");
sinon.assert.neverCalledWithMatch(util.log,"[debug] This is a debug");
sinon.assert.neverCalledWithMatch(util.log,"[trace] This is a trace");
sinon.assert.neverCalledWithMatch(util.log,"[metric] ");
});
it('ignores lower level messages but accepts metrics', function() {
var settings = {logging: { console: { level: 'log', metrics: true } } };
log.init(settings);
log.error("This is an error");
log.warn("This is a warn");
log.info("This is an info");
log.debug("This is a debug");
log.trace("This is a trace");
log.log({level:log.METRIC,msg:"testMetric"});
sinon.assert.calledWithMatch(util.log,"[error] This is an error");
sinon.assert.calledWithMatch(util.log,"[warn] This is a warn");
sinon.assert.calledWithMatch(util.log,"[info] This is an info");
sinon.assert.neverCalledWithMatch(util.log,"[debug] This is a debug");
sinon.assert.neverCalledWithMatch(util.log,"[trace] This is a trace");
sinon.assert.calledWithMatch(util.log,"[metric] ");
});
it('default settings set to INFO and metrics off', function() {
log.init({logging:{}});
log.error("This is an error");
log.warn("This is a warn");
log.info("This is an info");
log.debug("This is a debug");
log.trace("This is a trace");
log.log({level:log.METRIC,msg:"testMetric"});
sinon.assert.calledWithMatch(util.log,"[error] This is an error");
sinon.assert.calledWithMatch(util.log,"[warn] This is a warn");
sinon.assert.calledWithMatch(util.log,"[info] This is an info");
sinon.assert.neverCalledWithMatch(util.log,"[debug] This is a debug");
sinon.assert.neverCalledWithMatch(util.log,"[trace] This is a trace");
sinon.assert.neverCalledWithMatch(util.log,"[metric] ");
});
it('no logger used if custom logger handler does not exist', function() {
var settings = {logging: { customLogger: { level: 'trace', metrics: true } } };
log.init(settings);
log.error("This is an error");
log.warn("This is a warn");
log.info("This is an info");
log.debug("This is a debug");
log.trace("This is a trace");
log.log({level:log.METRIC,msg:"testMetric"});
sinon.assert.neverCalledWithMatch(util.log,"[error] This is an error");
sinon.assert.neverCalledWithMatch(util.log,"[warn] This is a warn");
sinon.assert.neverCalledWithMatch(util.log,"[info] This is an info");
sinon.assert.neverCalledWithMatch(util.log,"[debug] This is a debug");
sinon.assert.neverCalledWithMatch(util.log,"[trace] This is a trace");
sinon.assert.neverCalledWithMatch(util.log,"[metric] ");
});
});

View File

@@ -0,0 +1,545 @@
/**
* Copyright 2014, 2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var should = require("should");
var sinon = require('sinon');
var RedNode = require("../../../../red/runtime/nodes/Node");
var Log = require("../../../../red/runtime/log");
var flows = require("../../../../red/runtime/nodes/flows");
var comms = require("../../../../red/runtime/comms");
describe('Node', function() {
describe('#constructor',function() {
it('is called with an id and a type',function() {
var n = new RedNode({id:'123',type:'abc'});
n.should.have.property('id','123');
n.should.have.property('type','abc');
n.should.not.have.property('name');
n.wires.should.be.empty;
});
it('is called with an id, a type and a name',function() {
var n = new RedNode({id:'123',type:'abc',name:'barney'});
n.should.have.property('id','123');
n.should.have.property('type','abc');
n.should.have.property('name','barney');
n.wires.should.be.empty;
});
it('is called with an id, a type and some wires',function() {
var n = new RedNode({id:'123',type:'abc',wires:['123','456']});
n.should.have.property('id','123');
n.should.have.property('type','abc');
n.should.not.have.property('name');
n.wires.should.have.length(2);
});
});
describe('#close', function() {
it('emits close event when closed',function(done) {
var n = new RedNode({id:'123',type:'abc'});
n.on('close',function() {
done();
});
var p = n.close();
should.not.exist(p);
});
it('returns a promise when provided a callback with a done parameter',function(testdone) {
var n = new RedNode({id:'123',type:'abc'});
n.on('close',function(done) {
setTimeout(function() {
done();
},200);
});
var p = n.close();
should.exist(p);
p.then(function() {
testdone();
});
});
it('allows multiple close handlers to be registered',function(testdone) {
var n = new RedNode({id:'123',type:'abc'});
var callbacksClosed = 0;
n.on('close',function(done) {
setTimeout(function() {
callbacksClosed++;
done();
},200);
});
n.on('close',function(done) {
setTimeout(function() {
callbacksClosed++;
done();
},200);
});
n.on('close',function() {
callbacksClosed++;
});
var p = n.close();
should.exist(p);
p.then(function() {
callbacksClosed.should.eql(3);
testdone();
}).otherwise(function(e) {
testdone(e);
});
});
});
describe('#receive', function() {
it('emits input event when called', function(done) {
var n = new RedNode({id:'123',type:'abc'});
var message = {payload:"hello world"};
n.on('input',function(msg) {
should.deepEqual(msg,message);
done();
});
n.receive(message);
});
it('writes metric info with undefined msg', function(done){
var n = new RedNode({id:'123',type:'abc'});
n.on('input',function(msg) {
(typeof msg).should.not.be.equal("undefined");
(typeof msg._msgid).should.not.be.equal("undefined");
done();
});
n.receive();
});
it('writes metric info with null msg', function(done){
var n = new RedNode({id:'123',type:'abc'});
n.on('input',function(msg) {
(typeof msg).should.not.be.equal("undefined");
(typeof msg._msgid).should.not.be.equal("undefined");
done();
});
n.receive(null);
});
it('handles thrown errors', function(done) {
var n = new RedNode({id:'123',type:'abc'});
sinon.stub(n,"error",function(err,msg) {});
var message = {payload:"hello world"};
n.on('input',function(msg) {
throw new Error("test error");
});
n.receive(message);
n.error.called.should.be.true;
n.error.firstCall.args[1].should.equal(message);
done();
});
});
describe('#send', function() {
it('emits a single message', function(done) {
var n1 = new RedNode({id:'n1',type:'abc',wires:[['n2']]});
var n2 = new RedNode({id:'n2',type:'abc'});
var flowGet = sinon.stub(flows,"get",function(id) {
return {'n1':n1,'n2':n2}[id];
});
var message = {payload:"hello world"};
n2.on('input',function(msg) {
// msg equals message, and is not a new copy
should.deepEqual(msg,message);
should.strictEqual(msg,message);
flowGet.restore();
done();
});
n1.send(message);
});
it('emits multiple messages on a single output', function(done) {
var n1 = new RedNode({id:'n1',type:'abc',wires:[['n2']]});
var n2 = new RedNode({id:'n2',type:'abc'});
var flowGet = sinon.stub(flows,"get",function(id) {
return {'n1':n1,'n2':n2}[id];
});
var messages = [
{payload:"hello world"},
{payload:"hello world again"}
];
var rcvdCount = 0;
n2.on('input',function(msg) {
if (rcvdCount === 0) {
// first msg sent, don't clone
should.deepEqual(msg,messages[rcvdCount]);
should.strictEqual(msg,messages[rcvdCount]);
rcvdCount += 1;
} else {
// second msg sent, clone
msg.payload.should.equal(messages[rcvdCount].payload);
should.notStrictEqual(msg,messages[rcvdCount]);
flowGet.restore();
done();
}
});
n1.send([messages]);
});
it('emits messages to multiple outputs', function(done) {
var n1 = new RedNode({id:'n1',type:'abc',wires:[['n2'],['n3'],['n4','n5']]});
var n2 = new RedNode({id:'n2',type:'abc'});
var n3 = new RedNode({id:'n3',type:'abc'});
var n4 = new RedNode({id:'n4',type:'abc'});
var n5 = new RedNode({id:'n5',type:'abc'});
var flowGet = sinon.stub(flows,"get",function(id) {
return {'n1':n1,'n2':n2,'n3':n3,'n4':n4,'n5':n5}[id];
});
var messages = [
{payload:"hello world"},
null,
{payload:"hello world again"}
];
var rcvdCount = 0;
// first message sent, don't clone
// message uuids should match
n2.on('input',function(msg) {
should.deepEqual(msg,messages[0]);
should.strictEqual(msg,messages[0]);
rcvdCount += 1;
if (rcvdCount == 3) {
flowGet.restore();
done();
}
});
n3.on('input',function(msg) {
should.fail(null,null,"unexpected message");
});
// second message sent, clone
// message uuids wont match since we've cloned
n4.on('input',function(msg) {
msg.payload.should.equal(messages[2].payload);
should.notStrictEqual(msg,messages[2]);
rcvdCount += 1;
if (rcvdCount == 3) {
flowGet.restore();
done();
}
});
// third message sent, clone
// message uuids wont match since we've cloned
n5.on('input',function(msg) {
msg.payload.should.equal(messages[2].payload);
should.notStrictEqual(msg,messages[2]);
rcvdCount += 1;
if (rcvdCount == 3) {
flowGet.restore();
done();
}
});
n1.send(messages);
});
it('emits no messages', function(done) {
var n1 = new RedNode({id:'n1',type:'abc',wires:[['n2']]});
var n2 = new RedNode({id:'n2',type:'abc'});
var flowGet = sinon.stub(flows,"get",function(id) {
return {'n1':n1,'n2':n2}[id];
});
n2.on('input',function(msg) {
should.fail(null,null,"unexpected message");
});
setTimeout(function() {
flowGet.restore();
done();
}, 200);
n1.send();
});
it('emits messages ignoring non-existent nodes', function(done) {
var n1 = new RedNode({id:'n1',type:'abc',wires:[['n9'],['n2']]});
var n2 = new RedNode({id:'n2',type:'abc'});
var flowGet = sinon.stub(flows,"get",function(id) {
return {'n1':n1,'n2':n2}[id];
});
var messages = [
{payload:"hello world"},
{payload:"hello world again"}
];
// only one message sent, so no copy needed
n2.on('input',function(msg) {
should.deepEqual(msg,messages[1]);
should.strictEqual(msg,messages[1]);
flowGet.restore();
done();
});
n1.send(messages);
});
it('emits messages without cloning req or res', function(done) {
var n1 = new RedNode({id:'n1',type:'abc',wires:[[['n2'],['n3']]]});
var n2 = new RedNode({id:'n2',type:'abc'});
var n3 = new RedNode({id:'n3',type:'abc'});
var flowGet = sinon.stub(flows,"get",function(id) {
return {'n1':n1,'n2':n2,'n3':n3}[id];
});
var req = {};
var res = {};
var cloned = {};
var message = {payload: "foo", cloned: cloned, req: req, res: res};
var rcvdCount = 0;
// first message to be sent, so should not be cloned
n2.on('input',function(msg) {
should.deepEqual(msg, message);
msg.cloned.should.be.exactly(message.cloned);
msg.req.should.be.exactly(message.req);
msg.res.should.be.exactly(message.res);
rcvdCount += 1;
if (rcvdCount == 2) {
flowGet.restore();
done();
}
});
// second message to be sent, so should be cloned
// message uuids wont match since we've cloned
n3.on('input',function(msg) {
msg.payload.should.equal(message.payload);
msg.cloned.should.not.be.exactly(message.cloned);
msg.req.should.be.exactly(message.req);
msg.res.should.be.exactly(message.res);
rcvdCount += 1;
if (rcvdCount == 2) {
flowGet.restore();
done();
}
});
n1.send(message);
});
it("logs the uuid for all messages sent", function(done) {
var flowGet = sinon.stub(flows,"get",function(id) {
return {'n1':sender,'n2':receiver1,'n3':receiver2}[id];
});
var logHandler = {
messagesSent: 0,
emit: function(event, msg) {
if (msg.event == "node.abc.send" && msg.level == Log.METRIC) {
this.messagesSent++;
(typeof msg.msgid).should.not.be.equal("undefined");
flowGet.restore();
done();
}
}
};
Log.addHandler(logHandler);
var sender = new RedNode({id:'n1',type:'abc', wires:[['n2', 'n3']]});
var receiver1 = new RedNode({id:'n2',type:'abc'});
var receiver2 = new RedNode({id:'n3',type:'abc'});
sender.send({"some": "message"});
})
});
describe('#log', function() {
it('produces a log message', function(done) {
var n = new RedNode({id:'123',type:'abc'});
var loginfo = {};
sinon.stub(Log, 'log', function(msg) {
loginfo = msg;
});
n.log("a log message");
should.deepEqual({level:Log.INFO, id:n.id,
type:n.type, msg:"a log message", }, loginfo);
Log.log.restore();
done();
});
it('produces a log message with a name', function(done) {
var n = new RedNode({id:'123', type:'abc', name:"barney"});
var loginfo = {};
sinon.stub(Log, 'log', function(msg) {
loginfo = msg;
});
n.log("a log message");
should.deepEqual({level:Log.INFO, id:n.id, name: "barney",
type:n.type, msg:"a log message"}, loginfo);
Log.log.restore();
done();
});
});
describe('#warn', function() {
it('produces a warning message', function(done) {
var n = new RedNode({id:'123',type:'abc'});
var loginfo = {};
sinon.stub(Log, 'log', function(msg) {
loginfo = msg;
});
n.warn("a warning");
should.deepEqual({level:Log.WARN, id:n.id,
type:n.type, msg:"a warning"}, loginfo);
Log.log.restore();
done();
});
});
describe('#error', function() {
it('handles a null error message', function(done) {
var n = new RedNode({id:'123',type:'abc'});
var loginfo = {};
sinon.stub(Log, 'log', function(msg) {
loginfo = msg;
});
sinon.stub(flows,"handleError", function(node,message,msg) {
});
var message = {a:1};
n.error(null,message);
should.deepEqual({level:Log.ERROR, id:n.id, type:n.type, msg:""}, loginfo);
flows.handleError.called.should.be.true;
flows.handleError.args[0][0].should.eql(n);
flows.handleError.args[0][1].should.eql("");
flows.handleError.args[0][2].should.eql(message);
Log.log.restore();
flows.handleError.restore();
done();
});
it('produces an error message', function(done) {
var n = new RedNode({id:'123',type:'abc'});
var loginfo = {};
sinon.stub(Log, 'log', function(msg) {
loginfo = msg;
});
sinon.stub(flows,"handleError", function(node,message,msg) {
});
var message = {a:2};
n.error("This is an error",message);
should.deepEqual({level:Log.ERROR, id:n.id, type:n.type, msg:"This is an error"}, loginfo);
flows.handleError.called.should.be.true;
flows.handleError.args[0][0].should.eql(n);
flows.handleError.args[0][1].should.eql("This is an error");
flows.handleError.args[0][2].should.eql(message);
Log.log.restore();
flows.handleError.restore();
done();
});
});
describe('#metric', function() {
it('produces a metric message', function(done) {
var n = new RedNode({id:'123',type:'abc'});
var loginfo = {};
sinon.stub(Log, 'log', function(msg) {
loginfo = msg;
});
var msg = {payload:"foo", _msgid:"987654321"};
n.metric("test.metric",msg,"15mb");
should.deepEqual({value:"15mb", level:Log.METRIC, nodeid:n.id,
event:"node.abc.test.metric",msgid:"987654321"}, loginfo);
Log.log.restore();
done();
});
});
describe('#metric', function() {
it('returns metric value if eventname undefined', function(done) {
var n = new RedNode({id:'123',type:'abc'});
var loginfo = {};
sinon.stub(Log, 'log', function(msg) {
loginfo = msg;
});
var msg = {payload:"foo", _msgid:"987654321"};
var m = n.metric(undefined,msg,"15mb");
m.should.be.a.boolean;
Log.log.restore();
done();
});
it('returns not defined if eventname defined', function(done) {
var n = new RedNode({id:'123',type:'abc'});
var loginfo = {};
sinon.stub(Log, 'log', function(msg) {
loginfo = msg;
});
var msg = {payload:"foo", _msgid:"987654321"};
var m = n.metric("info",msg,"15mb");
should(m).be.undefined;
Log.log.restore();
done();
});
});
describe('#status', function() {
after(function() {
comms.publish.restore();
});
it('publishes status', function(done) {
sinon.stub(flows,"handleStatus", function(node,message,msg) {});
var n = new RedNode({id:'123',type:'abc'});
var status = {fill:"green",shape:"dot",text:"connected"};
var topic;
var message;
var retain;
sinon.stub(comms, 'publish', function(_topic, _message, _retain) {
topic = _topic;
message = _message;
retain = _retain;
});
n.status(status);
topic.should.equal('status/123');
message.should.equal(status);
retain.should.be.true;
flows.handleStatus.called.should.be.true;
flows.handleStatus.args[0][0].should.eql(n);
flows.handleStatus.args[0][1].should.eql(status);
flows.handleStatus.restore();
done();
});
});
});

View File

@@ -0,0 +1,264 @@
/**
* Copyright 2014, 2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var should = require("should");
var sinon = require("sinon");
var when = require("when");
var util = require("util");
var express = require("express");
var request = require("supertest");
var index = require("../../../../red/runtime/nodes/index");
var credentials = require("../../../../red/runtime/nodes/credentials");
var log = require("../../../../red/runtime/log");
var auth = require("../../../../red/api/auth");
describe('Credentials', function() {
afterEach(function() {
index.clearRegistry();
});
it('loads from storage',function(done) {
var storage = {
getCredentials: function() {
return when.promise(function(resolve,reject) {
resolve({"a":{"b":1,"c":2}});
});
}
};
credentials.init(storage);
credentials.load().then(function() {
credentials.get("a").should.have.property('b',1);
credentials.get("a").should.have.property('c',2);
done();
});
});
it('saves to storage', function(done) {
var storage = {
saveCredentials: function(creds) {
return when.resolve("saveCalled");
}
};
credentials.init(storage);
credentials.save().then(function(res) {
res.should.equal("saveCalled");
done();
});
});
it('saves to storage when new cred added', function(done) {
var storage = {
getCredentials: function() {
return when.promise(function(resolve,reject) {
resolve({"a":{"b":1,"c":2}});
});
},
saveCredentials: function(creds) {
return when(true);
}
};
sinon.spy(storage,"saveCredentials");
credentials.init(storage);
credentials.load().then(function() {
should.not.exist(credentials.get("b"))
credentials.add('b',{"d":3});
storage.saveCredentials.callCount.should.be.exactly(1);
credentials.get("b").should.have.property('d',3);
storage.saveCredentials.restore();
done();
});
});
it('deletes from storage', function(done) {
var storage = {
getCredentials: function() {
return when.promise(function(resolve,reject) {
resolve({"a":{"b":1,"c":2}});
});
},
saveCredentials: function(creds) {
return when(true);
}
};
sinon.spy(storage,"saveCredentials");
credentials.init(storage);
credentials.load().then(function() {
should.exist(credentials.get("a"))
credentials.delete('a');
storage.saveCredentials.callCount.should.be.exactly(1);
should.not.exist(credentials.get("a"));
storage.saveCredentials.restore();
done();
});
});
it('clean up from storage', function(done) {
var storage = {
getCredentials: function() {
return when.promise(function(resolve,reject) {
resolve({"a":{"b":1,"c":2}});
});
},
saveCredentials: function(creds) {
return when(true);
}
};
sinon.spy(storage,"saveCredentials");
credentials.init(storage);
credentials.load().then(function() {
should.exist(credentials.get("a"));
credentials.clean([]);
storage.saveCredentials.callCount.should.be.exactly(1);
should.not.exist(credentials.get("a"));
storage.saveCredentials.restore();
done();
});
});
it('handle error loading from storage', function(done) {
var storage = {
getCredentials: function() {
return when.promise(function(resolve,reject) {
reject("test forcing failure");
});
},
saveCredentials: function(creds) {
return when(true);
}
};
var logmsg = 'nothing logged yet';
sinon.stub(log, 'warn', function(msg) {
logmsg = msg;
});
credentials.init(storage);
credentials.load().then(function() {
log.warn.calledOnce.should.be.true;
log.warn.restore();
done();
}).otherwise(function(err){
log.warn.restore();
done(err);
});
});
it('credential type is not registered when extract', function(done) {
var testFlows = [{"type":"test","id":"tab1","label":"Sheet 1"}];
var storage = {
getFlows: function() {
var defer = when.defer();
defer.resolve(testFlows);
return defer.promise;
},
getCredentials: function() {
return when.promise(function(resolve,reject) {
resolve({"tab1":{"b":1,"c":2}});
});
},
saveFlows: function(conf) {
var defer = when.defer();
defer.resolve();
should.deepEqual(testFlows, conf);
return defer.promise;
},
saveCredentials: function(creds) {
return when(true);
},
getSettings: function() {
return when({});
},
saveSettings: function(s) {
return when();
}
};
function TestNode(n) {
index.createNode(this, n);
this.id = 'tab1';
this.type = 'test';
this.name = 'barney';
var node = this;
this.on("log", function() {
// do nothing
});
}
var logmsg = 'nothing logged yet';
sinon.stub(log, 'warn', function(msg) {
logmsg = msg;
});
var settings = {
available: function() { return false;}
}
index.init(settings, storage);
index.registerType('test', TestNode);
index.loadFlows().then(function() {
var testnode = new TestNode({id:'tab1',type:'test',name:'barney'});
credentials.extract(testnode);
log.warn.calledOnce.should.be.true;
log.warn.restore();
done();
}).otherwise(function(err){
log.warn.restore();
done(err);
});
});
it('extract and store credential updates in the provided node', function(done) {
credentials.init({saveCredentials:function(){}},express());
credentials.register("test",{
user1:{type:"text"},
password1:{type:"password"},
user2:{type:"text"},
password2:{type:"password"},
user3:{type:"text"},
password3:{type:"password"}
});
credentials.add("node",{user1:"abc",password1:"123",user2:"def",password2:"456",user3:"ghi",password3:"789"});
var node = {id:"node",type:"test",credentials:{
// user1 unchanged
password1:"__PWRD__",
user2: "",
password2:" ",
user3:"newUser",
password3:"newPassword"
}};
credentials.extract(node);
node.should.not.have.a.property("credentials");
var newCreds = credentials.get("node");
newCreds.should.have.a.property("user1","abc");
newCreds.should.have.a.property("password1","123");
newCreds.should.not.have.a.property("user2");
newCreds.should.not.have.a.property("password2");
newCreds.should.have.a.property("user3","newUser");
newCreds.should.have.a.property("password3","newPassword");
done();
});
})

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,500 @@
/**
* Copyright 2014, 2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var should = require("should");
var sinon = require("sinon");
var when = require("when");
var clone = require("clone");
var flows = require("../../../../../red/runtime/nodes/flows");
var RedNode = require("../../../../../red/runtime/nodes/Node");
var RED = require("../../../../../red/runtime/nodes");
var events = require("../../../../../red/runtime/events");
var credentials = require("../../../../../red/runtime/nodes/credentials");
var typeRegistry = require("../../../../../red/runtime/nodes/registry");
var Flow = require("../../../../../red/runtime/nodes/flows/Flow");
describe('flows/index', function() {
var storage;
var eventsOn;
var credentialsExtract;
var credentialsSave;
var credentialsClean;
var credentialsLoad;
var flowCreate;
var getType;
before(function() {
getType = sinon.stub(typeRegistry,"get",function(type) {
return type.indexOf('missing') === -1;
});
});
after(function() {
getType.restore();
});
beforeEach(function() {
eventsOn = sinon.spy(events,"on");
credentialsExtract = sinon.stub(credentials,"extract",function(conf) {
delete conf.credentials;
});
credentialsSave = sinon.stub(credentials,"save",function() {
return when.resolve();
});
credentialsClean = sinon.stub(credentials,"clean",function(conf) {
return when.resolve();
});
credentialsLoad = sinon.stub(credentials,"load",function() {
return when.resolve();
});
flowCreate = sinon.stub(Flow,"create",function(global, flow) {
var id;
if (typeof flow === 'undefined') {
flow = global;
id = '_GLOBAL_';
} else {
id = flow.id;
}
flowCreate.flows[id] = {
flow: flow,
global: global,
start: sinon.spy(),
update: sinon.spy(),
stop: sinon.spy(),
getActiveNodes: function() {
return flow.nodes||{};
},
handleError: sinon.spy(),
handleStatus: sinon.spy()
}
return flowCreate.flows[id];
});
flowCreate.flows = {};
storage = {
saveFlows: function(conf) {
storage.conf = conf;
return when.resolve();
}
}
});
afterEach(function(done) {
eventsOn.restore();
credentialsExtract.restore();
credentialsSave.restore();
credentialsClean.restore();
credentialsLoad.restore();
flowCreate.restore();
flows.stopFlows().then(done);
});
// describe('#init',function() {
// it('registers the type-registered handler', function() {
// flows.init({},{});
// eventsOn.calledOnce.should.be.true;
// });
// });
describe('#setFlows', function() {
it('sets the full flow', function(done) {
var originalConfig = [
{id:"t1-1",x:10,y:10,z:"t1",type:"test",wires:[]},
{id:"t1",type:"tab"}
];
flows.init({},storage);
flows.setFlows(originalConfig).then(function() {
credentialsExtract.called.should.be.false;
credentialsClean.called.should.be.true;
storage.hasOwnProperty('conf').should.be.true;
flows.getFlows().should.eql(originalConfig);
done();
});
});
it('sets the full flow for type load', function(done) {
var originalConfig = [
{id:"t1-1",x:10,y:10,z:"t1",type:"test",wires:[]},
{id:"t1",type:"tab"}
];
flows.init({},storage);
flows.setFlows(originalConfig,"load").then(function() {
credentialsExtract.called.should.be.false;
credentialsClean.called.should.be.true;
// 'load' type does not trigger a save
storage.hasOwnProperty('conf').should.be.false;
flows.getFlows().should.eql(originalConfig);
done();
});
});
it('extracts credentials from the full flow', function(done) {
var originalConfig = [
{id:"t1-1",x:10,y:10,z:"t1",type:"test",wires:[],credentials:{}},
{id:"t1",type:"tab"}
];
flows.init({},storage);
flows.setFlows(originalConfig).then(function() {
credentialsExtract.called.should.be.true;
credentialsClean.called.should.be.true;
storage.hasOwnProperty('conf').should.be.true;
var cleanedFlows = flows.getFlows();
storage.conf.should.eql(cleanedFlows);
cleanedFlows.should.not.eql(originalConfig);
cleanedFlows[0].credentials = {};
cleanedFlows.should.eql(originalConfig);
done();
});
});
it('updates existing flows with partial deployment - nodes', function(done) {
var originalConfig = [
{id:"t1-1",x:10,y:10,z:"t1",type:"test",wires:[]},
{id:"t1",type:"tab"}
];
var newConfig = clone(originalConfig);
newConfig.push({id:"t1-2",x:10,y:10,z:"t1",type:"test",wires:[]});
newConfig.push({id:"t2",type:"tab"});
newConfig.push({id:"t2-1",x:10,y:10,z:"t2",type:"test",wires:[]});
storage.getFlows = function() {
return when.resolve(originalConfig);
}
events.once('nodes-started',function() {
flows.setFlows(newConfig,"nodes").then(function() {
flows.getFlows().should.eql(newConfig);
flowCreate.flows['t1'].update.called.should.be.true;
flowCreate.flows['t2'].start.called.should.be.true;
flowCreate.flows['_GLOBAL_'].update.called.should.be.true;
done();
})
});
flows.init({},storage);
flows.load().then(function() {
flows.startFlows();
});
});
it('updates existing flows with partial deployment - flows', function(done) {
var originalConfig = [
{id:"t1-1",x:10,y:10,z:"t1",type:"test",wires:[]},
{id:"t1",type:"tab"}
];
var newConfig = clone(originalConfig);
newConfig.push({id:"t1-2",x:10,y:10,z:"t1",type:"test",wires:[]});
newConfig.push({id:"t2",type:"tab"});
newConfig.push({id:"t2-1",x:10,y:10,z:"t2",type:"test",wires:[]});
storage.getFlows = function() {
return when.resolve(originalConfig);
}
events.once('nodes-started',function() {
flows.setFlows(newConfig,"nodes").then(function() {
flows.getFlows().should.eql(newConfig);
flowCreate.flows['t1'].update.called.should.be.true;
flowCreate.flows['t2'].start.called.should.be.true;
flowCreate.flows['_GLOBAL_'].update.called.should.be.true;
flows.stopFlows().then(done);
})
});
flows.init({},storage);
flows.load().then(function() {
flows.startFlows();
});
});
});
describe('#load', function() {
it('loads the flow config', function(done) {
var originalConfig = [
{id:"t1-1",x:10,y:10,z:"t1",type:"test",wires:[]},
{id:"t1",type:"tab"}
];
storage.getFlows = function() {
return when.resolve(originalConfig);
}
flows.init({},storage);
flows.load().then(function() {
credentialsExtract.called.should.be.false;
credentialsLoad.called.should.be.true;
credentialsClean.called.should.be.true;
// 'load' type does not trigger a save
storage.hasOwnProperty('conf').should.be.false;
flows.getFlows().should.eql(originalConfig);
done();
});
});
});
describe('#startFlows', function() {
it('starts the loaded config', function(done) {
var originalConfig = [
{id:"t1-1",x:10,y:10,z:"t1",type:"test",wires:[]},
{id:"t1",type:"tab"}
];
storage.getFlows = function() {
return when.resolve(originalConfig);
}
events.once('nodes-started',function() {
Object.keys(flowCreate.flows).should.eql(['_GLOBAL_','t1']);
done();
});
flows.init({},storage);
flows.load().then(function() {
flows.startFlows();
});
});
it('does not start if nodes missing', function(done) {
var originalConfig = [
{id:"t1-1",x:10,y:10,z:"t1",type:"test",wires:[]},
{id:"t1-2",x:10,y:10,z:"t1",type:"missing",wires:[]},
{id:"t1",type:"tab"}
];
storage.getFlows = function() {
return when.resolve(originalConfig);
}
flows.init({},storage);
flows.load().then(function() {
flows.startFlows();
flowCreate.called.should.be.false;
done();
});
});
it('starts when missing nodes registered', function(done) {
var originalConfig = [
{id:"t1-1",x:10,y:10,z:"t1",type:"test",wires:[]},
{id:"t1-2",x:10,y:10,z:"t1",type:"missing",wires:[]},
{id:"t1-3",x:10,y:10,z:"t1",type:"missing2",wires:[]},
{id:"t1",type:"tab"}
];
storage.getFlows = function() {
return when.resolve(originalConfig);
}
flows.init({},storage);
flows.load().then(function() {
flows.startFlows();
flowCreate.called.should.be.false;
events.emit("type-registered","missing");
setTimeout(function() {
flowCreate.called.should.be.false;
events.emit("type-registered","missing2");
setTimeout(function() {
flowCreate.called.should.be.true;
done();
},10);
},10);
});
});
});
describe('#get',function() {
});
describe('#eachNode', function() {
it('iterates the flow nodes', function(done) {
var originalConfig = [
{id:"t1-1",x:10,y:10,z:"t1",type:"test",wires:[]},
{id:"t1",type:"tab"}
];
storage.getFlows = function() {
return when.resolve(originalConfig);
}
flows.init({},storage);
flows.load().then(function() {
var c = 0;
flows.eachNode(function(node) {
c++
})
c.should.equal(2);
done();
});
});
});
describe('#stopFlows', function() {
});
describe('#handleError', function() {
it('passes error to correct flow', function(done) {
var originalConfig = [
{id:"t1-1",x:10,y:10,z:"t1",type:"test",wires:[]},
{id:"t1",type:"tab"}
];
storage.getFlows = function() {
return when.resolve(originalConfig);
}
events.once('nodes-started',function() {
flows.handleError(originalConfig[0],"message",{});
flowCreate.flows['t1'].handleError.called.should.be.true;
done();
});
flows.init({},storage);
flows.load().then(function() {
flows.startFlows();
});
});
it('passes error to flows that use the originating global config', function(done) {
var originalConfig = [
{id:"configNode",type:"test"},
{id:"t1",type:"tab"},
{id:"t1-1",x:10,y:10,z:"t1",type:"test",config:"configNode",wires:[]},
{id:"t2",type:"tab"},
{id:"t2-1",x:10,y:10,z:"t2",type:"test",wires:[]},
{id:"t3",type:"tab"},
{id:"t3-1",x:10,y:10,z:"t3",type:"test",config:"configNode",wires:[]}
];
storage.getFlows = function() {
return when.resolve(originalConfig);
}
events.once('nodes-started',function() {
flows.handleError(originalConfig[0],"message",{});
try {
flowCreate.flows['t1'].handleError.called.should.be.true;
flowCreate.flows['t2'].handleError.called.should.be.false;
flowCreate.flows['t3'].handleError.called.should.be.true;
done();
} catch(err) {
done(err);
}
});
flows.init({},storage);
flows.load().then(function() {
flows.startFlows();
});
});
});
describe('#handleStatus', function() {
it('passes status to correct flow', function(done) {
var originalConfig = [
{id:"t1-1",x:10,y:10,z:"t1",type:"test",wires:[]},
{id:"t1",type:"tab"}
];
storage.getFlows = function() {
return when.resolve(originalConfig);
}
events.once('nodes-started',function() {
flows.handleStatus(originalConfig[0],"message");
flowCreate.flows['t1'].handleStatus.called.should.be.true;
done();
});
flows.init({},storage);
flows.load().then(function() {
flows.startFlows();
});
});
it('passes status to flows that use the originating global config', function(done) {
var originalConfig = [
{id:"configNode",type:"test"},
{id:"t1",type:"tab"},
{id:"t1-1",x:10,y:10,z:"t1",type:"test",config:"configNode",wires:[]},
{id:"t2",type:"tab"},
{id:"t2-1",x:10,y:10,z:"t2",type:"test",wires:[]},
{id:"t3",type:"tab"},
{id:"t3-1",x:10,y:10,z:"t3",type:"test",config:"configNode",wires:[]}
];
storage.getFlows = function() {
return when.resolve(originalConfig);
}
events.once('nodes-started',function() {
flows.handleStatus(originalConfig[0],"message");
try {
flowCreate.flows['t1'].handleStatus.called.should.be.true;
flowCreate.flows['t2'].handleStatus.called.should.be.false;
flowCreate.flows['t3'].handleStatus.called.should.be.true;
done();
} catch(err) {
done(err);
}
});
flows.init({},storage);
flows.load().then(function() {
flows.startFlows();
});
});
});
describe('#checkTypeInUse', function() {
before(function() {
sinon.stub(typeRegistry,"getNodeInfo",function(id) {
if (id === 'unused-module') {
return {types:['one','two','three']}
} else {
return {types:['one','test','three']}
}
});
});
after(function() {
typeRegistry.getNodeInfo.restore();
});
it('returns cleanly if type not is use', function(done) {
var originalConfig = [
{id:"t1-1",x:10,y:10,z:"t1",type:"test",wires:[]},
{id:"t1",type:"tab"}
];
flows.init({},storage);
flows.setFlows(originalConfig).then(function() {
flows.checkTypeInUse("unused-module");
done();
});
});
it('throws error if type is in use', function(done) {
var originalConfig = [
{id:"t1-1",x:10,y:10,z:"t1",type:"test",wires:[]},
{id:"t1",type:"tab"}
];
flows.init({},storage);
flows.setFlows(originalConfig).then(function() {
/*jshint immed: false */
try {
flows.checkTypeInUse("used-module");
done("type_in_use error not thrown");
} catch(err) {
err.code.should.eql("type_in_use");
done();
}
});
});
});
});

View File

@@ -0,0 +1,604 @@
/**
* Copyright 2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var should = require("should");
var sinon = require("sinon");
var when = require("when");
var clone = require("clone");
var flowUtil = require("../../../../../red/runtime/nodes/flows/util");
var typeRegistry = require("../../../../../red/runtime/nodes/registry");
var redUtil = require("../../../../../red/runtime/util");
describe('flows/util', function() {
var getType;
before(function() {
getType = sinon.stub(typeRegistry,"get",function(type) {
return type!=='missing';
});
});
after(function() {
getType.restore();
});
describe('#diffNodes',function() {
it('handles a null old node', function() {
flowUtil.diffNodes(null,{}).should.be.true;
});
it('ignores x/y changes', function() {
flowUtil.diffNodes({x:10,y:10},{x:20,y:10}).should.be.false;
flowUtil.diffNodes({x:10,y:10},{x:10,y:20}).should.be.false;
});
it('ignores wiring changes', function() {
flowUtil.diffNodes({wires:[]},{wires:[1,2,3]}).should.be.false;
});
it('spots existing property change - string', function() {
flowUtil.diffNodes({a:"foo"},{a:"bar"}).should.be.true;
});
it('spots existing property change - number', function() {
flowUtil.diffNodes({a:0},{a:1}).should.be.true;
});
it('spots existing property change - boolean', function() {
flowUtil.diffNodes({a:true},{a:false}).should.be.true;
});
it('spots existing property change - truthy', function() {
flowUtil.diffNodes({a:true},{a:1}).should.be.true;
});
it('spots existing property change - falsey', function() {
flowUtil.diffNodes({a:false},{a:0}).should.be.true;
});
it('spots existing property change - array', function() {
flowUtil.diffNodes({a:[0,1,2]},{a:[0,2,3]}).should.be.true;
});
it('spots existing property change - object', function() {
flowUtil.diffNodes({a:{a:[0,1,2]}},{a:{a:[0,2,3]}}).should.be.true;
flowUtil.diffNodes({a:{a:[0,1,2]}},{a:{b:[0,1,2]}}).should.be.true;
});
it('spots added property', function() {
flowUtil.diffNodes({a:"foo"},{a:"foo",b:"bar"}).should.be.true;
});
it('spots removed property', function() {
flowUtil.diffNodes({a:"foo",b:"bar"},{a:"foo"}).should.be.true;
});
});
describe('#parseConfig',function() {
it('parses a single-tab flow', function() {
var originalConfig = [
{id:"t1-1",x:10,y:10,z:"t1",type:"test",wires:[]},
{id:"t1",type:"tab"}
];
var parsedConfig = flowUtil.parseConfig(originalConfig);
var expectedConfig = {"allNodes":{"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"test","wires":[]},"t1":{"id":"t1","type":"tab"}},"subflows":{},"configs":{},"flows":{"t1":{"id":"t1","type":"tab","subflows":{},"configs":{},"nodes":{"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"test","wires":[]}}}},"missingTypes":[]};
redUtil.compareObjects(parsedConfig,expectedConfig).should.be.true;
});
it('parses a single-tab flow with global config node', function() {
var originalConfig = [
{id:"t1-1",x:10,y:10,z:"t1",type:"test",foo:"cn", wires:[]},
{id:"cn",type:"test"},
{id:"t1",type:"tab"}
];
var parsedConfig = flowUtil.parseConfig(originalConfig);
var expectedConfig = {"allNodes":{"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"test","foo":"cn","wires":[]},"cn":{"id":"cn","type":"test"},"t1":{"id":"t1","type":"tab"}},"subflows":{},"configs":{"cn":{"id":"cn","type":"test","_users":["t1-1"]}},"flows":{"t1":{"id":"t1","type":"tab","subflows":{},"configs":{},"nodes":{"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"test","foo":"cn","wires":[]}}}},"missingTypes":[]};
redUtil.compareObjects(parsedConfig,expectedConfig).should.be.true;
});
it('parses a multi-tab flow', function() {
var originalConfig = [
{id:"t1",type:"tab"},
{id:"t1-1",x:10,y:10,z:"t1",type:"test",wires:[]},
{id:"t2",type:"tab"},
{id:"t2-1",x:10,y:10,z:"t2",type:"test",wires:[]}
];
var parsedConfig = flowUtil.parseConfig(originalConfig);
var expectedConfig = {"allNodes":{"t1":{"id":"t1","type":"tab"},"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"test","wires":[]},"t2":{"id":"t2","type":"tab"},"t2-1":{"id":"t2-1","x":10,"y":10,"z":"t2","type":"test","wires":[]}},"subflows":{},"configs":{},"flows":{"t1":{"id":"t1","type":"tab","subflows":{},"configs":{},"nodes":{"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"test","wires":[]}}},"t2":{"id":"t2","type":"tab","subflows":{},"configs":{},"nodes":{"t2-1":{"id":"t2-1","x":10,"y":10,"z":"t2","type":"test","wires":[]}}}},"missingTypes":[]};
redUtil.compareObjects(parsedConfig,expectedConfig).should.be.true;
});
it('parses a subflow flow', function() {
var originalConfig = [
{id:"t1",type:"tab"},
{id:"t1-1",x:10,y:10,z:"t1",type:"subflow:sf1",wires:[]},
{id:"sf1",type:"subflow"},
{id:"sf1-1",x:10,y:10,z:"sf1",type:"test",wires:[]}
];
var parsedConfig = flowUtil.parseConfig(originalConfig);
var expectedConfig = {"allNodes":{"t1":{"id":"t1","type":"tab"},"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"subflow:sf1","wires":[]},"sf1":{"id":"sf1","type":"subflow"},"sf1-1":{"id":"sf1-1","x":10,"y":10,"z":"sf1","type":"test","wires":[]}},"subflows":{"sf1":{"id":"sf1","type":"subflow","configs":{},"nodes":{"sf1-1":{"id":"sf1-1","x":10,"y":10,"z":"sf1","type":"test","wires":[]}},"instances":[{"id":"t1-1","x":10,"y":10,"z":"t1","type":"subflow:sf1","wires":[],"subflow":"sf1"}]}},"configs":{},"flows":{"t1":{"id":"t1","type":"tab","subflows":{},"configs":{},"nodes":{"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"subflow:sf1","wires":[],"subflow":"sf1"}}}},"missingTypes":[]};
redUtil.compareObjects(parsedConfig,expectedConfig).should.be.true;
});
it('parses a flow with a missing type', function() {
var originalConfig = [
{id:"t1",type:"tab"},
{id:"t1-1",x:10,y:10,z:"t1",type:"sf1",wires:[]},
{id:"t1-2",x:10,y:10,z:"t1",type:"missing",wires:[]},
];
var parsedConfig = flowUtil.parseConfig(originalConfig);
parsedConfig.missingTypes.should.eql(['missing']);
var expectedConfig = {"allNodes":{"t1":{"id":"t1","type":"tab"},"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"sf1","wires":[]},"t1-2":{"id":"t1-2","x":10,"y":10,"z":"t1","type":"missing","wires":[]}},"subflows":{},"configs":{},"flows":{"t1":{"id":"t1","type":"tab","subflows":{},"configs":{},"nodes":{"t1-1":{"id":"t1-1","x":10,"y":10,"z":"t1","type":"sf1","wires":[]}}}},"missingTypes":["missing"]};
redUtil.compareObjects(parsedConfig,expectedConfig).should.be.true;
});
});
describe('#diffConfigs', function() {
it('handles an identical configuration', function() {
var config = [{id:"123",type:"test",foo:"a",wires:[]}];
var originalConfig = flowUtil.parseConfig(clone(config));
var changedConfig = flowUtil.parseConfig(clone(config));
originalConfig.missingTypes.should.have.length(0);
var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
diffResult.added.should.have.length(0);
diffResult.changed.should.have.length(0);
diffResult.removed.should.have.length(0);
diffResult.rewired.should.have.length(0);
diffResult.linked.should.have.length(0);
});
it('identifies nodes with changed properties, including downstream linked', function() {
var config = [{id:"1",type:"test",foo:"a",wires:[]},{id:"2",type:"test",bar:"b",wires:[[1]]},{id:"3",type:"test",foo:"a",wires:[]}];
var newConfig = clone(config);
newConfig[0].foo = "b";
var originalConfig = flowUtil.parseConfig(config);
var changedConfig = flowUtil.parseConfig(newConfig);
originalConfig.missingTypes.should.have.length(0);
var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
diffResult.added.should.have.length(0);
diffResult.changed.should.eql(["1"]);
diffResult.removed.should.have.length(0);
diffResult.rewired.should.have.length(0);
diffResult.linked.should.eql(["2"]);
});
it('identifies nodes with changed properties, including upstream linked', function() {
var config = [{id:"1",type:"test",foo:"a",wires:[]},{id:"2",type:"test",bar:"b",wires:[["1"]]},{id:"3",type:"test",foo:"a",wires:[]}];
var newConfig = clone(config);
newConfig[1].bar = "c";
var originalConfig = flowUtil.parseConfig(config);
var changedConfig = flowUtil.parseConfig(newConfig);
originalConfig.missingTypes.should.have.length(0);
var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
diffResult.added.should.have.length(0);
diffResult.changed.should.eql(["2"]);
diffResult.removed.should.have.length(0);
diffResult.rewired.should.have.length(0);
diffResult.linked.should.eql(["1"]);
});
it('identifies nodes with changed credentials, including downstream linked', function() {
var config = [{id:"1",type:"test",wires:[]},{id:"2",type:"test",bar:"b",wires:[["1"]]},{id:"3",type:"test",foo:"a",wires:[]}];
var newConfig = clone(config);
newConfig[0].credentials = {};
var originalConfig = flowUtil.parseConfig(config);
var changedConfig = flowUtil.parseConfig(newConfig);
originalConfig.missingTypes.should.have.length(0);
var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
diffResult.added.should.have.length(0);
diffResult.changed.should.eql(["1"]);
diffResult.removed.should.have.length(0);
diffResult.rewired.should.have.length(0);
diffResult.linked.should.eql(["2"]);
});
it('identifies nodes with changed wiring', function() {
var config = [{id:"1",type:"test",foo:"a",wires:[]},{id:"2",type:"test",bar:"b",wires:[["1"]]},{id:"3",type:"test",foo:"a",wires:[]}];
var newConfig = clone(config);
newConfig[1].wires[0][0] = "3";
var originalConfig = flowUtil.parseConfig(config);
var changedConfig = flowUtil.parseConfig(newConfig);
originalConfig.missingTypes.should.have.length(0);
var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
diffResult.added.should.have.length(0);
diffResult.changed.should.have.length(0);
diffResult.removed.should.have.length(0);
diffResult.rewired.should.eql(["2"]);
diffResult.linked.sort().should.eql(["1","3"]);
});
it('identifies nodes with changed wiring - second connection added', function() {
var config = [{id:"1",type:"test",foo:"a",wires:[]},{id:"2",type:"test",bar:"b",wires:[["1"]]},{id:"3",type:"test",foo:"a",wires:[]}];
var newConfig = clone(config);
newConfig[1].wires[0].push("1");
var originalConfig = flowUtil.parseConfig(config);
var changedConfig = flowUtil.parseConfig(newConfig);
originalConfig.missingTypes.should.have.length(0);
var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
diffResult.added.should.have.length(0);
diffResult.changed.should.have.length(0);
diffResult.removed.should.have.length(0);
diffResult.rewired.should.eql(["2"]);
diffResult.linked.sort().should.eql(["1"]);
});
it('identifies nodes with changed wiring - node connected', function() {
var config = [{id:"1",type:"test",foo:"a",wires:[["2"]]},{id:"2",type:"test",bar:"b",wires:[[]]},{id:"3",type:"test",foo:"a",wires:[]}];
var newConfig = clone(config);
newConfig[1].wires.push("3");
var originalConfig = flowUtil.parseConfig(config);
var changedConfig = flowUtil.parseConfig(newConfig);
originalConfig.missingTypes.should.have.length(0);
var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
diffResult.added.should.have.length(0);
diffResult.changed.should.have.length(0);
diffResult.removed.should.have.length(0);
diffResult.rewired.should.eql(["2"]);
diffResult.linked.sort().should.eql(["1","3"]);
});
it('identifies new nodes', function() {
var config = [{id:"1",type:"test",foo:"a",wires:[]},{id:"3",type:"test",foo:"a",wires:[]}];
var newConfig = clone(config);
newConfig.push({id:"2",type:"test",bar:"b",wires:[["1"]]});
var originalConfig = flowUtil.parseConfig(config);
var changedConfig = flowUtil.parseConfig(newConfig);
originalConfig.missingTypes.should.have.length(0);
var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
diffResult.added.should.eql(["2"]);
diffResult.changed.should.have.length(0);
diffResult.removed.should.have.length(0);
diffResult.rewired.should.have.length(0);
diffResult.linked.sort().should.eql(["1"]);
});
it('identifies deleted nodes', function() {
var config = [{id:"1",type:"test",foo:"a",wires:[["2"]]},{id:"2",type:"test",bar:"b",wires:[["3"]]},{id:"3",type:"test",foo:"a",wires:[]}];
var newConfig = clone(config);
newConfig.splice(1,1);
newConfig[0].wires = [];
var originalConfig = flowUtil.parseConfig(config);
var changedConfig = flowUtil.parseConfig(newConfig);
originalConfig.missingTypes.should.have.length(0);
var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
diffResult.added.should.have.length(0);
diffResult.changed.should.have.length(0);
diffResult.removed.should.eql(["2"]);
diffResult.rewired.should.eql(["1"]);
diffResult.linked.sort().should.eql(["3"]);
});
it('identifies config nodes changes', function() {
var config = [
{id:"1",type:"test",foo:"configNode",wires:[["2"]]},
{id:"2",type:"test",bar:"b",wires:[["3"]]},
{id:"3",type:"test",foo:"a",wires:[]},
{id:"configNode",type:"testConfig"}
];
var newConfig = clone(config);
newConfig[3].foo = "bar";
var originalConfig = flowUtil.parseConfig(config);
var changedConfig = flowUtil.parseConfig(newConfig);
originalConfig.missingTypes.should.have.length(0);
var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
diffResult.added.should.have.length(0);
diffResult.changed.sort().should.eql(["1","configNode"]);
diffResult.removed.should.have.length(0);
diffResult.rewired.should.have.length(0);
diffResult.linked.sort().should.eql(["2","3"]);
});
it('marks a parent subflow as changed for an internal property change', function() {
var config = [
{id:"1",type:"test",wires:[["2"]]},
{id:"2",type:"subflow:sf1",wires:[["3"]]},
{id:"3",type:"test",wires:[]},
{id:"sf1",type:"subflow"},
{id:"sf1-1",z:"sf1",type:"test",foo:"a",wires:[]},
{id:"4",type:"subflow:sf1",wires:[]}
];
var newConfig = clone(config);
newConfig[4].foo = "b";
var originalConfig = flowUtil.parseConfig(config);
var changedConfig = flowUtil.parseConfig(newConfig);
originalConfig.missingTypes.should.have.length(0);
var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
diffResult.added.should.have.length(0);
diffResult.changed.sort().should.eql(['2', '4', 'sf1']);
diffResult.removed.should.have.length(0);
diffResult.rewired.should.have.length(0);
diffResult.linked.sort().should.eql(["1","3"]);
});
it('marks a parent subflow as changed for an internal wiring change', function() {
var config = [
{id:"1",type:"test",wires:[["2"]]},
{id:"2",type:"subflow:sf1",wires:[["3"]]},
{id:"3",type:"test",wires:[]},
{id:"sf1",type:"subflow"},
{id:"sf1-1",z:"sf1",type:"test",wires:[]},
{id:"sf1-2",z:"sf1",type:"test",wires:[]}
];
var newConfig = clone(config);
newConfig[4].wires = [["sf1-2"]];
var originalConfig = flowUtil.parseConfig(config);
var changedConfig = flowUtil.parseConfig(newConfig);
originalConfig.missingTypes.should.have.length(0);
var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
diffResult.added.should.have.length(0);
diffResult.changed.sort().should.eql(['2', 'sf1']);
diffResult.removed.should.have.length(0);
diffResult.rewired.should.have.length(0);
diffResult.linked.sort().should.eql(["1","3"]);
});
it('marks a parent subflow as changed for an internal node add', function() {
var config = [
{id:"1",type:"test",wires:[["2"]]},
{id:"2",type:"subflow:sf1",wires:[["3"]]},
{id:"3",type:"test",wires:[]},
{id:"sf1",type:"subflow"},
{id:"sf1-1",z:"sf1",type:"test",wires:[]},
{id:"sf1-2",z:"sf1",type:"test",wires:[]}
];
var newConfig = clone(config);
newConfig.push({id:"sf1-3",z:"sf1",type:"test",wires:[]});
var originalConfig = flowUtil.parseConfig(config);
var changedConfig = flowUtil.parseConfig(newConfig);
originalConfig.missingTypes.should.have.length(0);
var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
diffResult.added.should.have.length(0);
diffResult.changed.sort().should.eql(['2', 'sf1']);
diffResult.removed.should.have.length(0);
diffResult.rewired.should.have.length(0);
diffResult.linked.sort().should.eql(["1","3"]);
});
it('marks a parent subflow as changed for an internal node delete', function() {
var config = [
{id:"1",type:"test",wires:[["2"]]},
{id:"2",type:"subflow:sf1",wires:[["3"]]},
{id:"3",type:"test",wires:[]},
{id:"sf1",type:"subflow"},
{id:"sf1-1",z:"sf1",type:"test",wires:[]},
{id:"sf1-2",z:"sf1",type:"test",wires:[]}
];
var newConfig = clone(config);
newConfig.splice(5,1);
var originalConfig = flowUtil.parseConfig(config);
var changedConfig = flowUtil.parseConfig(newConfig);
originalConfig.missingTypes.should.have.length(0);
var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
diffResult.added.should.have.length(0);
diffResult.changed.sort().should.eql(['2', 'sf1']);
diffResult.removed.should.have.length(0);
diffResult.rewired.should.have.length(0);
diffResult.linked.sort().should.eql(["1","3"]);
});
it('marks a parent subflow as changed for an internal subflow wiring change - input removed', function() {
var config = [
{id:"1",type:"test",wires:[["2"]]},
{id:"2",type:"subflow:sf1",wires:[["3"]]},
{id:"3",type:"test",wires:[]},
{id:"sf1",type:"subflow","in": [{"wires": [{"id": "sf1-1"}]}],"out": [{"wires": [{"id": "sf1-2","port": 0}]}]},
{id:"sf1-1",z:"sf1",type:"test",wires:[]},
{id:"sf1-2",z:"sf1",type:"test",wires:[]}
];
var newConfig = clone(config);
newConfig[3].in[0].wires = [];
var originalConfig = flowUtil.parseConfig(config);
var changedConfig = flowUtil.parseConfig(newConfig);
originalConfig.missingTypes.should.have.length(0);
var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
diffResult.added.should.have.length(0);
diffResult.changed.sort().should.eql(['2', 'sf1']);
diffResult.removed.should.have.length(0);
diffResult.rewired.should.have.length(0);
diffResult.linked.sort().should.eql(["1","3"]);
});
it('marks a parent subflow as changed for an internal subflow wiring change - input added', function() {
var config = [
{id:"1",type:"test",wires:[["2"]]},
{id:"2",type:"subflow:sf1",wires:[["3"]]},
{id:"3",type:"test",wires:[]},
{id:"sf1",type:"subflow","in": [{"wires": [{"id": "sf1-1"}]}],"out": [{"wires": [{"id": "sf1-2","port": 0}]}]},
{id:"sf1-1",z:"sf1",type:"test",wires:[]},
{id:"sf1-2",z:"sf1",type:"test",wires:[]}
];
var newConfig = clone(config);
newConfig[3].in[0].wires.push({"id":"sf1-2"});
var originalConfig = flowUtil.parseConfig(config);
var changedConfig = flowUtil.parseConfig(newConfig);
originalConfig.missingTypes.should.have.length(0);
var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
diffResult.added.should.have.length(0);
diffResult.changed.sort().should.eql(['2', 'sf1']);
diffResult.removed.should.have.length(0);
diffResult.rewired.should.have.length(0);
diffResult.linked.sort().should.eql(["1","3"]);
});
it('marks a parent subflow as changed for an internal subflow wiring change - output added', function() {
var config = [
{id:"1",type:"test",wires:[["2"]]},
{id:"2",type:"subflow:sf1",wires:[["3"]]},
{id:"3",type:"test",wires:[]},
{id:"sf1",type:"subflow","in": [{"wires": [{"id": "sf1-1"}]}],"out": [{"wires": [{"id": "sf1-2","port": 0}]}]},
{id:"sf1-1",z:"sf1",type:"test",wires:[]},
{id:"sf1-2",z:"sf1",type:"test",wires:[]}
];
var newConfig = clone(config);
newConfig[3].out[0].wires.push({"id":"sf1-2","port":0});
var originalConfig = flowUtil.parseConfig(config);
var changedConfig = flowUtil.parseConfig(newConfig);
originalConfig.missingTypes.should.have.length(0);
var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
diffResult.added.should.have.length(0);
diffResult.changed.sort().should.eql(['2', 'sf1']);
diffResult.removed.should.have.length(0);
diffResult.rewired.should.have.length(0);
diffResult.linked.sort().should.eql(["1","3"]);
});
it('marks a parent subflow as changed for an internal subflow wiring change - output removed', function() {
var config = [
{id:"1",type:"test",wires:[["2"]]},
{id:"2",type:"subflow:sf1",wires:[["3"]]},
{id:"3",type:"test",wires:[]},
{id:"sf1",type:"subflow","in": [{"wires": [{"id": "sf1-1"}]}],"out": [{"wires": [{"id": "sf1-2","port": 0}]}]},
{id:"sf1-1",z:"sf1",type:"test",wires:[]},
{id:"sf1-2",z:"sf1",type:"test",wires:[]}
];
var newConfig = clone(config);
newConfig[3].out[0].wires = [];
var originalConfig = flowUtil.parseConfig(config);
var changedConfig = flowUtil.parseConfig(newConfig);
originalConfig.missingTypes.should.have.length(0);
var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
diffResult.added.should.have.length(0);
diffResult.changed.sort().should.eql(['2', 'sf1']);
diffResult.removed.should.have.length(0);
diffResult.rewired.should.have.length(0);
diffResult.linked.sort().should.eql(["1","3"]);
});
it('marks a parent subflow as changed for a global config node change', function() {
var config = [
{id:"1",type:"test",wires:[["2"]]},
{id:"2",type:"subflow:sf1",wires:[["3"]]},
{id:"3",type:"test",wires:[]},
{id:"sf1",type:"subflow"},
{id:"sf1-1",z:"sf1",prop:"configNode",type:"test",wires:[]},
{id:"sf1-2",z:"sf1",type:"test",wires:[]},
{id:"configNode",a:"foo",type:"test",wires:[]}
];
var newConfig = clone(config);
newConfig[6].a = "bar";
var originalConfig = flowUtil.parseConfig(config);
var changedConfig = flowUtil.parseConfig(newConfig);
originalConfig.missingTypes.should.have.length(0);
var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
diffResult.added.should.have.length(0);
diffResult.changed.sort().should.eql(['2', "configNode", 'sf1']);
diffResult.removed.should.have.length(0);
diffResult.rewired.should.have.length(0);
diffResult.linked.sort().should.eql(["1","3"]);
});
it('marks a parent subflow as changed for an internal subflow instance change', function() {
var config = [
{id:"1",type:"test",wires:[["2"]]},
{id:"2",type:"subflow:sf1",wires:[["3"]]},
{id:"3",type:"test",wires:[]},
{id:"sf1",type:"subflow"},
{id:"sf2",type:"subflow"},
{id:"sf1-1",z:"sf1",type:"test",wires:[]},
{id:"sf1-2",z:"sf1",type:"subflow:sf2",wires:[]},
{id:"sf2-1",z:"sf2",type:"test",wires:[]},
{id:"sf2-2",z:"sf2",type:"test",wires:[]},
];
var newConfig = clone(config);
newConfig[8].a = "bar";
var originalConfig = flowUtil.parseConfig(config);
var changedConfig = flowUtil.parseConfig(newConfig);
originalConfig.missingTypes.should.have.length(0);
var diffResult = flowUtil.diffConfigs(originalConfig,changedConfig);
diffResult.added.should.have.length(0);
diffResult.changed.sort().should.eql(['2', 'sf1', 'sf2']);
diffResult.removed.should.have.length(0);
diffResult.rewired.should.have.length(0);
diffResult.linked.sort().should.eql(["1","3"]);
});
});
});

View File

@@ -0,0 +1,281 @@
/**
* Copyright 2014 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var should = require("should");
var fs = require('fs-extra');
var path = require('path');
var when = require("when");
var sinon = require('sinon');
var index = require("../../../../red/runtime/nodes/index");
var flows = require("../../../../red/runtime/nodes/flows");
var registry = require("../../../../red/runtime/nodes/registry");
describe("red/nodes/index", function() {
before(function() {
sinon.stub(flows,"startFlows");
process.env.NODE_RED_HOME = path.resolve(path.join(__dirname,"..","..","..",".."))
});
after(function() {
flows.startFlows.restore();
delete process.env.NODE_RED_HOME;
});
afterEach(function() {
index.clearRegistry();
});
var testFlows = [{"type":"test","id":"tab1","label":"Sheet 1"}];
var storage = {
getFlows: function() {
return when(testFlows);
},
getCredentials: function() {
return when({"tab1":{"b":1,"c":2}});
},
saveFlows: function(conf) {
should.deepEqual(testFlows, conf);
return when();
},
saveCredentials: function(creds) {
return when(true);
}
};
var settings = {
available: function() { return false }
};
function TestNode(n) {
index.createNode(this, n);
var node = this;
this.on("log", function() {
// do nothing
});
}
it('nodes are initialised with credentials',function(done) {
index.init(settings, storage);
index.registerType('test', TestNode);
index.loadFlows().then(function() {
var testnode = new TestNode({id:'tab1',type:'test',name:'barney'});
testnode.credentials.should.have.property('b',1);
testnode.credentials.should.have.property('c',2);
done();
}).otherwise(function(err) {
done(err);
});
});
it('flows should be initialised',function(done) {
index.init(settings, storage);
index.loadFlows().then(function() {
should.deepEqual(testFlows, index.getFlows());
done();
}).otherwise(function(err) {
done(err);
});
});
describe("registerType should register credentials definition", function() {
var http = require('http');
var express = require('express');
var app = express();
var runtime = require("../../../../red/runtime");
var credentials = require("../../../../red/runtime/nodes/credentials");
var localfilesystem = require("../../../../red/runtime/storage/localfilesystem");
var RED = require("../../../../red/red.js");
var userDir = path.join(__dirname,".testUserHome");
before(function(done) {
fs.remove(userDir,function(err) {
fs.mkdir(userDir,function() {
sinon.stub(index, 'load', function() {
return when.promise(function(resolve,reject){
resolve([]);
});
});
sinon.stub(localfilesystem, 'getCredentials', function() {
return when.promise(function(resolve,reject) {
resolve({"tab1":{"b":1,"c":2}});
});
}) ;
RED.init(http.createServer(function(req,res){app(req,res)}),
{userDir: userDir});
runtime.start().then(function () {
done();
});
});
});
});
after(function(done) {
fs.remove(userDir,done);
runtime.stop();
index.load.restore();
localfilesystem.getCredentials.restore();
});
it(': definition defined',function(done) {
index.registerType('test', TestNode, {
credentials: {
foo: {type:"test"}
}
});
var testnode = new TestNode({id:'tab1',type:'test',name:'barney', '_alias':'tab1'});
index.getCredentialDefinition("test").should.have.property('foo');
done();
});
});
describe('allows nodes to be added/removed/enabled/disabled from the registry', function() {
var registry = require("../../../../red/runtime/nodes/registry");
var randomNodeInfo = {id:"5678",types:["random"]};
beforeEach(function() {
sinon.stub(registry,"getNodeInfo",function(id) {
if (id == "test") {
return {id:"1234",types:["test"]};
} else if (id == "doesnotexist") {
return null;
} else {
return randomNodeInfo;
}
});
sinon.stub(registry,"disableNode",function(id) {
return randomNodeInfo;
});
});
afterEach(function() {
registry.getNodeInfo.restore();
registry.disableNode.restore();
});
it(': allows an unused node type to be disabled',function(done) {
index.init(settings, storage);
index.registerType('test', TestNode);
index.loadFlows().then(function() {
var info = index.disableNode("5678");
registry.disableNode.calledOnce.should.be.true;
registry.disableNode.calledWith("5678").should.be.true;
info.should.eql(randomNodeInfo);
done();
}).otherwise(function(err) {
done(err);
});
});
it(': prevents disabling a node type that is in use',function(done) {
index.init(settings, storage);
index.registerType('test', TestNode);
index.loadFlows().then(function() {
/*jshint immed: false */
(function() {
index.disabledNode("test");
}).should.throw();
done();
}).otherwise(function(err) {
done(err);
});
});
it(': prevents disabling a node type that is unknown',function(done) {
index.init(settings, storage);
index.registerType('test', TestNode);
index.loadFlows().then(function() {
/*jshint immed: false */
(function() {
index.disableNode("doesnotexist");
}).should.throw();
done();
}).otherwise(function(err) {
done(err);
});
});
});
describe('allows modules to be removed from the registry', function() {
var registry = require("../../../../red/runtime/nodes/registry");
var randomNodeInfo = {id:"5678",types:["random"]};
var randomModuleInfo = {
name:"random",
nodes: [randomNodeInfo]
};
before(function() {
sinon.stub(registry,"getNodeInfo",function(id) {
if (id == "node-red/foo") {
return {id:"1234",types:["test"]};
} else if (id == "doesnotexist") {
return null;
} else {
return randomNodeInfo;
}
});
sinon.stub(registry,"getModuleInfo",function(module) {
if (module == "node-red") {
return {nodes:[{name:"foo"}]};
} else if (module == "doesnotexist") {
return null;
} else {
return randomModuleInfo;
}
});
sinon.stub(registry,"removeModule",function(id) {
return randomModuleInfo;
});
});
after(function() {
registry.getNodeInfo.restore();
registry.getModuleInfo.restore();
registry.removeModule.restore();
});
it(': prevents removing a module that is in use',function(done) {
index.init(settings, storage);
index.registerType('test', TestNode);
index.loadFlows().then(function() {
/*jshint immed: false */
(function() {
index.removeModule("node-red");
}).should.throw();
done();
}).otherwise(function(err) {
done(err);
});
});
it(': prevents removing a module that is unknown',function(done) {
index.init(settings, storage);
index.registerType('test', TestNode);
index.loadFlows().then(function() {
/*jshint immed: false */
(function() {
index.removeModule("doesnotexist");
}).should.throw();
done();
}).otherwise(function(err) {
done(err);
});
});
});
});

View File

@@ -0,0 +1,28 @@
/**
* Copyright 2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var should = require("should");
var deprecated = require("../../../../../red/runtime/nodes/registry/deprecated.js");
describe('deprecated', function() {
it('should return info on a node',function() {
deprecated.get("irc in").should.eql({module:"node-red-node-irc"});
});
it('should return null for non-deprecated node',function() {
should.not.exist(deprecated.get("foo"));
});
});

View File

@@ -0,0 +1,965 @@
/**
* Copyright 2014 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var should = require("should");
var sinon = require("sinon");
var path = require("path");
var when = require("when");
var RedNodes = require("../../../../../red/runtime/nodes");
var RedNode = require("../../../../../red/runtime/nodes/Node");
var typeRegistry = require("../../../../../red/runtime/nodes/registry");
var events = require("../../../../../red/runtime/events");
afterEach(function() {
typeRegistry.clear();
});
describe('red/nodes/registry/index', function() {
var resourcesDir = path.join(__dirname,"..","resources",path.sep);
function stubSettings(s,available,initialConfig) {
s.available = function() {return available;};
s.set = function(s,v) { return when.resolve();};
s.get = function(s) { return initialConfig;};
return s;
}
var settings = stubSettings({},false,null);
var settingsWithStorage = stubSettings({},true,null);
it('handles nodes that export a function', function(done) {
typeRegistry.init(settings);
typeRegistry.load(resourcesDir + "TestNode1",true).then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
list[0].should.have.property("id","node-red/TestNode1");
list[0].should.have.property("name","TestNode1");
list[0].should.have.property("module","node-red");
list[0].should.have.property("types",["test-node-1"]);
list[0].should.have.property("enabled",true);
list[0].should.not.have.property("err");
var nodeConstructor = typeRegistry.get("test-node-1");
nodeConstructor.should.be.type("function");
done();
}).catch(function(e) {
done(e);
});
});
it('handles nodes that export a function returning a resolving promise', function(done) {
typeRegistry.init(settings);
typeRegistry.load(resourcesDir + "TestNode2",true).then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
list[0].should.have.property("id","node-red/TestNode2");
list[0].should.have.property("name","TestNode2");
list[0].should.have.property("module","node-red");
list[0].should.have.property("types",["test-node-2"]);
list[0].should.have.property("enabled",true);
list[0].should.not.have.property("err");
var nodeConstructor = typeRegistry.get("test-node-2");
nodeConstructor.should.be.type("function");
done();
}).catch(function(e) {
done(e);
});
});
it('handles nodes that export a function returning a rejecting promise', function(done) {
typeRegistry.init(settings);
typeRegistry.load(resourcesDir + "TestNode3",true).then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
list[0].should.have.property("id","node-red/TestNode3");
list[0].should.have.property("name","TestNode3");
list[0].should.have.property("module","node-red");
list[0].should.have.property("types",["test-node-3"]);
list[0].should.have.property("enabled",true);
list[0].should.have.property("err","fail");
var nodeConstructor = typeRegistry.get("test-node-3");
(nodeConstructor === null).should.be.true;
done();
}).catch(function(e) {
done(e);
});
});
it('handles files containing multiple nodes', function(done) {
typeRegistry.init(settings);
typeRegistry.load(resourcesDir + "MultipleNodes1",true).then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
list[0].should.have.property("id","node-red/MultipleNodes1");
list[0].should.have.property("name","MultipleNodes1");
list[0].should.have.property("module","node-red");
list[0].should.have.property("types",["test-node-multiple-1a","test-node-multiple-1b"]);
list[0].should.have.property("enabled",true);
list[0].should.not.have.property("err");
var nodeConstructor = typeRegistry.get("test-node-multiple-1a");
nodeConstructor.should.be.type("function");
nodeConstructor = typeRegistry.get("test-node-multiple-1b");
nodeConstructor.should.be.type("function");
done();
}).catch(function(e) {
done(e);
});
});
it('handles nested directories', function(done) {
typeRegistry.init(settings);
typeRegistry.load(resourcesDir + "NestedDirectoryNode",true).then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
list[0].should.have.property("id","node-red/NestedNode");
list[0].should.have.property("name","NestedNode");
list[0].should.have.property("module","node-red");
list[0].should.have.property("types",["nested-node-1"]);
list[0].should.have.property("enabled",true);
list[0].should.not.have.property("err");
done();
}).catch(function(e) {
done(e);
});
});
it('emits type-registered and node-icon-dir events', function(done) {
var eventEmitSpy = sinon.spy(events,"emit");
typeRegistry.init(settings);
typeRegistry.load(resourcesDir + "NestedDirectoryNode",true).then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
list[0].should.have.property("id","node-red/NestedNode");
list[0].should.have.property("name","NestedNode");
list[0].should.have.property("module","node-red");
list[0].should.have.property("types",["nested-node-1"]);
list[0].should.have.property("enabled",true);
list[0].should.not.have.property("err");
eventEmitSpy.callCount.should.equal(3);
eventEmitSpy.firstCall.args[0].should.be.equal("node-icon-dir");
eventEmitSpy.firstCall.args[1].should.be.equal(
resourcesDir + "NestedDirectoryNode" + path.sep + "NestedNode" + path.sep + "icons");
eventEmitSpy.secondCall.args[0].should.be.equal("node-locales-dir");
eventEmitSpy.thirdCall.args[0].should.be.equal("type-registered");
eventEmitSpy.thirdCall.args[1].should.be.equal("nested-node-1");
done();
}).catch(function(e) {
done(e);
}).finally(function() {
eventEmitSpy.restore();
});
});
it('rejects a duplicate node type registration during load', function(done) {
typeRegistry.init(stubSettings({
nodesDir:[resourcesDir + "TestNode1",resourcesDir + "DuplicateTestNode"]
},false));
typeRegistry.load("wontexist",true).then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
list[0].should.have.property("id","node-red/TestNode1");
list[0].should.have.property("name","TestNode1");
list[0].should.have.property("types",["test-node-1"]);
list[0].should.have.property("enabled",true);
list[0].should.not.have.property("err");
done();
}).catch(function(e) {
done(e);
});
});
it('rejects a duplicate node type registration', function(done) {
typeRegistry.init(stubSettings({
nodesDir:[resourcesDir + "TestNode1"]
},false));
typeRegistry.load("wontexist",true).then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
/*jshint immed: false */
(function(){
typeRegistry.registerType("test-node-1",{});
}).should.throw();
done();
}).catch(function(e) {
done(e);
});
});
it('handles nodesDir as a string', function(done) {
typeRegistry.init(stubSettings({
nodesDir :resourcesDir + "TestNode1"
},false));
typeRegistry.load("wontexist",true).then(function(){
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
list[0].should.have.property("types",["test-node-1"]);
done();
}).catch(function(e) {
done("Loading of non-existing nodesDir should succeed");
});
});
it('handles invalid nodesDir',function(done) {
typeRegistry.init(stubSettings({
nodesDir : "wontexist"
},false));
typeRegistry.load("wontexist",true).then(function(){
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.be.empty;
done();
}).catch(function(e) {
done("Loading of non-existing nodesDir should succeed");
});
});
it('returns nothing for an unregistered type config', function(done) {
typeRegistry.init(settings);
typeRegistry.load("wontexist",true).then(function(){
var config = typeRegistry.getNodeConfig("imaginary-shark");
(config === null).should.be.true;
done();
}).catch(function(e) {
done(e);
});
});
it('excludes node files listed in nodesExcludes',function(done) {
typeRegistry.init(stubSettings({
nodesExcludes: [ "TestNode1.js" ],
nodesDir:[resourcesDir + "TestNode1",resourcesDir + "TestNode2"]
},false));
typeRegistry.load("wontexist",true).then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
list[0].should.have.property("types",["test-node-2"]);
done();
}).catch(function(e) {
done(e);
});
});
it('returns the node configurations', function(done) {
typeRegistry.init(stubSettings({
nodesDir:[resourcesDir + "TestNode1",resourcesDir + "TestNode2"]
},false));
typeRegistry.load("wontexist",true).then(function() {
var list = typeRegistry.getNodeList();
var nodeConfigs = typeRegistry.getNodeConfigs();
// TODO: this is brittle...
nodeConfigs.should.equal("<script type=\"text/x-red\" data-template-name=\"test-node-1\"></script>\n\n<script type=\"text/javascript\">RED.nodes.registerType('test-node-1',{});</script>\n<style></style>\n<p>this should be filtered out</p>\n<script type=\"text/x-red\" data-help-name=\"test-node-1\"></script><script type=\"text/x-red\" data-template-name=\"test-node-2\"></script>\n\n<script type=\"text/javascript\">RED.nodes.registerType('test-node-2',{});</script>\n<style></style>\n<script type=\"text/x-red\" data-help-name=\"test-node-2\"></script>");
var nodeId = list[0].id;
var nodeConfig = typeRegistry.getNodeConfig(nodeId);
nodeConfig.should.equal("<script type=\"text/x-red\" data-template-name=\"test-node-1\"></script>\n\n<script type=\"text/javascript\">RED.nodes.registerType('test-node-1',{});</script>\n<style></style>\n<p>this should be filtered out</p>\n<script type=\"text/x-red\" data-help-name=\"test-node-1\"></script>");
done();
}).catch(function(e) {
done(e);
});
});
it('stores the node list', function(done) {
var settings = {
nodesDir:[resourcesDir + "TestNode1",resourcesDir + "TestNode2",resourcesDir + "TestNode3"],
available: function() { return true; },
set: function(s,v) { return when.resolve(); },
get: function(s) { return null; }
};
var settingsSave = sinon.spy(settings,"set");
typeRegistry.init(settings);
typeRegistry.load("wontexist",true).then(function() {
var nodeList = typeRegistry.getNodeList();
var moduleList = typeRegistry.getModuleList();
Object.keys(moduleList).should.have.length(1);
moduleList.should.have.a.property("node-red");
Object.keys(moduleList["node-red"].nodes).should.have.length(3);
nodeList.should.be.Array.and.have.length(3);
settingsSave.callCount.should.equal(1);
settingsSave.firstCall.args[0].should.be.equal("nodes");
var savedList = settingsSave.firstCall.args[1];
moduleList['node-red'].nodes['TestNode1'].should.have.a.property("id","node-red/TestNode1");
moduleList['node-red'].nodes['TestNode1'].should.have.a.property("name","TestNode1");
moduleList['node-red'].nodes['TestNode1'].should.have.a.property("module","node-red");
moduleList['node-red'].nodes['TestNode1'].should.have.a.property("file");
moduleList['node-red'].nodes['TestNode1'].should.have.a.property("enabled",true);
moduleList['node-red'].nodes['TestNode1'].should.have.a.property("types");
moduleList['node-red'].nodes['TestNode1'].should.have.a.property("config");
moduleList['node-red'].nodes['TestNode1'].should.have.a.property("template");
savedList['node-red'].nodes['TestNode1'].should.not.have.a.property("id");
savedList['node-red'].nodes['TestNode1'].should.have.a.property("name",moduleList['node-red'].nodes['TestNode1'].name);
savedList['node-red'].nodes['TestNode1'].should.have.a.property("module",moduleList['node-red'].nodes['TestNode1'].module);
savedList['node-red'].nodes['TestNode1'].should.have.a.property("file",moduleList['node-red'].nodes['TestNode1'].file);
savedList['node-red'].nodes['TestNode1'].should.have.a.property("enabled",moduleList['node-red'].nodes['TestNode1'].enabled);
savedList['node-red'].nodes['TestNode1'].should.have.a.property("types",moduleList['node-red'].nodes['TestNode1'].types);
savedList['node-red'].nodes['TestNode1'].should.not.have.a.property("config");
savedList['node-red'].nodes['TestNode1'].should.not.have.a.property("template");
done();
}).catch(function(e) {
done(e);
}).finally(function() {
settingsSave.restore();
});
});
it('returns node info by type or id', function(done) {
typeRegistry.init(settings);
typeRegistry.load(resourcesDir + "TestNode1",true).then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
list[0].should.have.property("id","node-red/TestNode1");
list[0].should.have.property("name","TestNode1");
list[0].should.have.property("module","node-red");
list[0].should.have.property("types",["test-node-1"]);
list[0].should.have.property("enabled",true);
list[0].should.not.have.property("err");
var id = "node-red/TestNode1";
var type = "test-node-1";
var info = typeRegistry.getNodeInfo(id);
info.should.have.property("loaded");
delete info.loaded;
list[0].should.eql(info);
var info2 = typeRegistry.getNodeInfo(type);
info2.should.have.property("loaded");
delete info2.loaded;
list[0].should.eql(info2);
done();
}).catch(function(e) {
done(e);
});
});
it('returns null node info for unrecognised id', function(done) {
typeRegistry.init(settings);
typeRegistry.load(resourcesDir + "TestNode1",true).then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
should.not.exist(typeRegistry.getNodeInfo("does-not-exist"));
done();
}).catch(function(e) {
done(e);
});
});
it('returns modules list', function(done) {
var fs = require("fs");
var path = require("path");
var pathJoin = (function() {
var _join = path.join;
return sinon.stub(path,"join",function() {
if (arguments.length == 3 && arguments[2] == "package.json") {
return _join(resourcesDir,"TestNodeModule" + path.sep + "node_modules" + path.sep,arguments[1],arguments[2]);
}
if (arguments.length == 2 && arguments[1] == "TestNodeModule") {
return _join(resourcesDir,"TestNodeModule" + path.sep + "node_modules" + path.sep,arguments[1]);
}
return _join.apply(this,arguments);
});
})();
var readdirSync = (function() {
var originalReaddirSync = fs.readdirSync;
var callCount = 0;
return sinon.stub(fs,"readdirSync",function(dir) {
var result = [];
if (callCount == 1) {
result = originalReaddirSync(resourcesDir + "TestNodeModule" + path.sep + "node_modules");
}
callCount++;
return result;
});
})();
typeRegistry.init(settingsWithStorage);
typeRegistry.load("wontexist",true).then(function(){
typeRegistry.addModule("TestNodeModule").then(function() {
var list = typeRegistry.getModuleList();
Object.keys(list).should.have.length(1);
list.should.have.a.property("TestNodeModule");
Object.keys(list["TestNodeModule"].nodes).should.have.length(2);
list["TestNodeModule"].nodes["TestNodeMod1"].should.have.property("name", "TestNodeMod1");
list["TestNodeModule"].nodes["TestNodeMod2"].should.have.property("name", "TestNodeMod2");
done();
}).catch(function(e) {
done(e);
});
}).catch(function(e) {
done(e);
}).finally(function() {
readdirSync.restore();
pathJoin.restore();
});
});
it('returns module info', function(done) {
var fs = require("fs");
var path = require("path");
var pathJoin = (function() {
var _join = path.join;
return sinon.stub(path,"join",function() {
if (arguments.length == 3 && arguments[2] == "package.json") {
return _join(resourcesDir,"TestNodeModule" + path.sep + "node_modules" + path.sep,arguments[1],arguments[2]);
}
if (arguments.length == 2 && arguments[1] == "TestNodeModule") {
return _join(resourcesDir,"TestNodeModule" + path.sep + "node_modules" + path.sep,arguments[1]);
}
return _join.apply(this,arguments);
});
})();
var readdirSync = (function() {
var originalReaddirSync = fs.readdirSync;
var callCount = 0;
return sinon.stub(fs,"readdirSync",function(dir) {
var result = [];
if (callCount == 1) {
result = originalReaddirSync(resourcesDir + "TestNodeModule" + path.sep + "node_modules");
}
callCount++;
return result;
});
})();
typeRegistry.init(settingsWithStorage);
typeRegistry.load("wontexist",true).then(function(){
typeRegistry.addModule("TestNodeModule").then(function(modInfo) {
var info = typeRegistry.getModuleInfo("TestNodeModule");
modInfo.should.eql(info);
should.not.exist(typeRegistry.getModuleInfo("does-not-exist"));
done();
}).catch(function(e) {
done(e);
});
}).catch(function(e) {
done(e);
}).finally(function() {
readdirSync.restore();
pathJoin.restore();
});
});
it('scans the node_modules path for node files', function(done) {
var fs = require("fs");
var path = require("path");
var eventEmitSpy = sinon.spy(events,"emit");
var pathJoin = (function() {
var _join = path.join;
return sinon.stub(path,"join",function() {
if (arguments.length == 3 && arguments[2] == "package.json") {
return _join(resourcesDir,"TestNodeModule" + path.sep + "node_modules" + path.sep,arguments[1],arguments[2]);
}
if (arguments.length == 2 && arguments[1] == "TestNodeModule") {
return _join(resourcesDir,"TestNodeModule" + path.sep + "node_modules" + path.sep,arguments[1]);
}
return _join.apply(this,arguments);
});
})();
var readdirSync = (function() {
var originalReaddirSync = fs.readdirSync;
var callCount = 0;
return sinon.stub(fs,"readdirSync",function(dir) {
var result = [];
if (callCount == 1) {
result = originalReaddirSync(resourcesDir + "TestNodeModule" + path.sep + "node_modules");
}
callCount++;
return result;
});
})();
typeRegistry.init(settings);
typeRegistry.load("wontexist",false).then(function(){
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(2);
list[0].should.have.property("id","TestNodeModule/TestNodeMod1");
list[0].should.have.property("name","TestNodeMod1");
list[0].should.have.property("module","TestNodeModule");
list[0].should.have.property("types",["test-node-mod-1"]);
list[0].should.have.property("enabled",true);
list[0].should.not.have.property("err");
list[1].should.have.property("id","TestNodeModule/TestNodeMod2");
list[1].should.have.property("name","TestNodeMod2");
list[1].should.have.property("module","TestNodeModule");
list[1].should.have.property("types",["test-node-mod-2"]);
list[1].should.have.property("enabled",true);
list[1].should.have.property("err");
eventEmitSpy.callCount.should.equal(3);
eventEmitSpy.firstCall.args[0].should.be.equal("node-locales-dir");
eventEmitSpy.secondCall.args[0].should.be.equal("node-icon-dir");
eventEmitSpy.secondCall.args[1].should.be.equal(
resourcesDir + "TestNodeModule" + path.sep+ "node_modules" + path.sep + "TestNodeModule" + path.sep + "icons");
eventEmitSpy.thirdCall.args[0].should.be.equal("type-registered");
eventEmitSpy.thirdCall.args[1].should.be.equal("test-node-mod-1");
done();
}).catch(function(e) {
done(e);
}).finally(function() {
readdirSync.restore();
pathJoin.restore();
eventEmitSpy.restore();
});
});
it('allows nodes to be added by module name', function(done) {
var fs = require("fs");
var path = require("path");
var pathJoin = (function() {
var _join = path.join;
return sinon.stub(path,"join",function() {
if (arguments.length == 3 && arguments[2] == "package.json") {
return _join(resourcesDir,"TestNodeModule" + path.sep + "node_modules" + path.sep,arguments[1],arguments[2]);
}
if (arguments.length == 2 && arguments[1] == "TestNodeModule") {
return _join(resourcesDir,"TestNodeModule" + path.sep + "node_modules" + path.sep,arguments[1]);
}
return _join.apply(this,arguments);
});
})();
var readdirSync = (function() {
var originalReaddirSync = fs.readdirSync;
var callCount = 0;
return sinon.stub(fs,"readdirSync",function(dir) {
var result = [];
if (callCount == 1) {
result = originalReaddirSync(resourcesDir + "TestNodeModule" + path.sep + "node_modules");
}
callCount++;
return result;
});
})();
typeRegistry.init(settingsWithStorage);
typeRegistry.load("wontexist",true).then(function(){
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.be.empty;
typeRegistry.addModule("TestNodeModule").then(function(modInfo) {
list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(2);
list[0].should.have.property("id","TestNodeModule/TestNodeMod1");
list[0].should.have.property("name","TestNodeMod1");
list[0].should.have.property("module","TestNodeModule");
list[0].should.have.property("types",["test-node-mod-1"]);
list[0].should.have.property("enabled",true);
list[0].should.not.have.property("err");
list[1].should.have.property("id","TestNodeModule/TestNodeMod2");
list[1].should.have.property("name","TestNodeMod2");
list[1].should.have.property("module","TestNodeModule");
list[1].should.have.property("types",["test-node-mod-2"]);
list[1].should.have.property("enabled",true);
list[1].should.have.property("err");
done();
}).catch(function(e) {
done(e);
});
}).catch(function(e) {
done(e);
}).finally(function() {
readdirSync.restore();
pathJoin.restore();
});
});
it('adds module with version number', function(done) {
var fs = require("fs");
var path = require("path");
var pathJoin = (function() {
var _join = path.join;
return sinon.stub(path,"join",function() {
if (arguments.length == 3 && arguments[2] == "package.json") {
return _join(resourcesDir,"TestNodeModule" + path.sep + "node_modules" + path.sep,arguments[1],arguments[2]);
}
if (arguments.length == 2 && arguments[1] == "TestNodeModule") {
return _join(resourcesDir,"TestNodeModule" + path.sep + "node_modules" + path.sep,arguments[1]);
}
return _join.apply(this,arguments);
});
})();
var readdirSync = (function() {
var originalReaddirSync = fs.readdirSync;
var callCount = 0;
return sinon.stub(fs,"readdirSync",function(dir) {
var result = [];
if (callCount == 1) {
result = originalReaddirSync(resourcesDir + "TestNodeModule" + path.sep + "node_modules");
}
callCount++;
return result;
});
})();
typeRegistry.init(settingsWithStorage);
typeRegistry.load("wontexist",true).then(function(){
typeRegistry.addModule("TestNodeModule","0.0.1").then(function(node) {
var module = typeRegistry.getModuleInfo("TestNodeModule");
module.should.have.property("name","TestNodeModule");
module.should.have.property("version","0.0.1");
var modules = typeRegistry.getModuleList();
modules.should.have.property("TestNodeModule");
modules["TestNodeModule"].should.have.property("version","0.0.1");
done();
}).catch(function(e) {
done(e);
});
}).catch(function(e) {
done(e);
}).finally(function() {
readdirSync.restore();
pathJoin.restore();
});
});
it('rejects adding duplicate node modules', function(done) {
var fs = require("fs");
var path = require("path");
var pathJoin = (function() {
var _join = path.join;
return sinon.stub(path,"join",function() {
if (arguments.length == 3 && arguments[2] == "package.json") {
return _join(resourcesDir,"TestNodeModule" + path.sep + "node_modules" + path.sep,arguments[1],arguments[2]);
}
if (arguments.length == 2 && arguments[1] == "TestNodeModule") {
return _join(resourcesDir,"TestNodeModule" + path.sep + "node_modules" + path.sep,arguments[1]);
}
return _join.apply(this,arguments);
});
})();
var readdirSync = (function() {
var originalReaddirSync = fs.readdirSync;
var callCount = 0;
return sinon.stub(fs,"readdirSync",function(dir) {
var result = [];
if (callCount == 1) {
result = originalReaddirSync(resourcesDir + "TestNodeModule" + path.sep + "node_modules");
}
callCount++;
return result;
});
})();
typeRegistry.init(settingsWithStorage);
typeRegistry.load('wontexist',false).then(function(){
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(2);
typeRegistry.addModule("TestNodeModule").then(function(node) {
done(new Error("addModule resolved"));
}).otherwise(function(err) {
done();
});
}).catch(function(e) {
done(e);
}).finally(function() {
readdirSync.restore();
pathJoin.restore();
});
});
it('fails to add non-existent module name', function(done) {
typeRegistry.init(settingsWithStorage);
typeRegistry.load("wontexist",true).then(function(){
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.be.empty;
typeRegistry.addModule("DoesNotExistModule").then(function(node) {
done(new Error("ENOENT not thrown"));
}).otherwise(function(e) {
e.code.should.eql("MODULE_NOT_FOUND");
done();
});
}).catch(function(e) {
done(e);
});
});
it('removes nodes from the registry by module', function(done) {
var fs = require("fs");
var path = require("path");
var pathJoin = (function() {
var _join = path.join;
return sinon.stub(path,"join",function() {
if (arguments.length == 3 && arguments[2] == "package.json") {
return _join(resourcesDir,"TestNodeModule" + path.sep + "node_modules" + path.sep,arguments[1],arguments[2]);
}
if (arguments.length == 2 && arguments[1] == "TestNodeModule") {
return _join(resourcesDir,"TestNodeModule" + path.sep + "node_modules" + path.sep,arguments[1]);
}
return _join.apply(this,arguments);
});
})();
var readdirSync = (function() {
var originalReaddirSync = fs.readdirSync;
var callCount = 0;
return sinon.stub(fs,"readdirSync",function(dir) {
var result = [];
if (callCount == 1) {
result = originalReaddirSync(resourcesDir + "TestNodeModule" + path.sep + "node_modules");
}
callCount++;
return result;
});
})();
typeRegistry.init(settingsWithStorage);
typeRegistry.load('wontexist',false).then(function(){
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(2);
var res = typeRegistry.removeModule("TestNodeModule");
res.should.be.an.Array.and.have.lengthOf(2);
res[0].should.have.a.property("id",list[0].id);
res[1].should.have.a.property("id",list[1].id);
list = typeRegistry.getNodeList();
list.should.be.an.Array.and.be.empty;
done();
}).catch(function(e) {
done(e);
}).finally(function() {
readdirSync.restore();
pathJoin.restore();
});
});
it('fails to remove non-existent module name', function(done) {
typeRegistry.init(settingsWithStorage);
typeRegistry.load("wontexist",true).then(function(){
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.be.empty;
/*jshint immed: false */
(function() {
typeRegistry.removeModule("DoesNotExistModule");
}).should.throw("Unrecognised module: DoesNotExistModule");
done();
}).catch(function(e) {
done(e);
});
});
it('allows nodes to be enabled and disabled by id', function(done) {
typeRegistry.init(settingsWithStorage);
typeRegistry.load(resourcesDir+path.sep+"TestNode1",true).then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
list[0].should.have.property("id","node-red/TestNode1");
list[0].should.have.property("name","TestNode1");
list[0].should.have.property("module","node-red");
list[0].should.have.property("enabled",true);
var nodeConfig = typeRegistry.getNodeConfigs();
nodeConfig.length.should.be.greaterThan(0);
typeRegistry.disableNode(list[0].id).then(function(info) {
info.should.have.property("id",list[0].id);
info.should.have.property("enabled",false);
var list2 = typeRegistry.getNodeList();
list2.should.be.an.Array.and.have.lengthOf(1);
list2[0].should.have.property("enabled",false);
typeRegistry.getNodeConfigs().length.should.equal(0);
typeRegistry.enableNode(list[0].id).then(function(info2) {
info2.should.have.property("id",list[0].id);
info2.should.have.property("enabled",true);
var list3 = typeRegistry.getNodeList();
list3.should.be.an.Array.and.have.lengthOf(1);
list3[0].should.have.property("enabled",true);
var nodeConfig2 = typeRegistry.getNodeConfigs();
nodeConfig2.should.eql(nodeConfig);
done();
});
});
}).catch(function(e) {
done(e);
});
});
it('allows nodes to be enabled and disabled by node-type', function(done) {
typeRegistry.init(settingsWithStorage);
typeRegistry.load(resourcesDir+path.sep+"TestNode1",true).then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.have.lengthOf(1);
list[0].should.have.property("id","node-red/TestNode1");
list[0].should.have.property("name","TestNode1");
list[0].should.have.property("module","node-red");
list[0].should.have.property("types",["test-node-1"]);
list[0].should.have.property("enabled",true);
var nodeConfig = typeRegistry.getNodeConfigs();
nodeConfig.length.should.be.greaterThan(0);
typeRegistry.disableNode(list[0].types[0]).then(function(info) {;
info.should.have.property("id",list[0].id);
info.should.have.property("types",list[0].types);
info.should.have.property("enabled",false);
var list2 = typeRegistry.getNodeList();
list2.should.be.an.Array.and.have.lengthOf(1);
list2[0].should.have.property("enabled",false);
typeRegistry.getNodeConfigs().length.should.equal(0);
typeRegistry.enableNode(list[0].types[0]).then(function(info2) {
info2.should.have.property("id",list[0].id);
info2.should.have.property("types",list[0].types);
info2.should.have.property("enabled",true);
var list3 = typeRegistry.getNodeList();
list3.should.be.an.Array.and.have.lengthOf(1);
list3[0].should.have.property("enabled",true);
var nodeConfig2 = typeRegistry.getNodeConfigs();
nodeConfig2.should.eql(nodeConfig);
done();
});
});
}).catch(function(e) {
done(e);
});
});
it('fails to enable/disable non-existent nodes', function(done) {
typeRegistry.init(settingsWithStorage);
typeRegistry.load("wontexist",true).then(function() {
var list = typeRegistry.getNodeList();
list.should.be.an.Array.and.be.empty;
/*jshint immed: false */
(function() {
typeRegistry.disableNode("123");
}).should.throw();
/*jshint immed: false */
(function() {
typeRegistry.enableNode("123");
}).should.throw();
done();
}).catch(function(e) {
done(e);
});
});
it("handles unavailable settings", function(done) {
typeRegistry.init(settings);
/*jshint immed: false */
(function() {
typeRegistry.enableNode("123");
}).should.throw("Settings unavailable");
/*jshint immed: false */
(function() {
typeRegistry.disableNode("123");
}).should.throw("Settings unavailable");
/*jshint immed: false */
(function() {
typeRegistry.addModule("123");
}).should.throw("Settings unavailable");
/*jshint immed: false */
(function() {
typeRegistry.removeModule("123");
}).should.throw("Settings unavailable");
done();
});
});

View File

@@ -0,0 +1,168 @@
/**
* Copyright 2014, 2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var should = require("should");
var sinon = require("sinon");
var when = require("when");
var path = require("path");
var child_process = require('child_process');
var installer = require("../../../../../red/runtime/nodes/registry/installer");
var registry = require("../../../../../red/runtime/nodes/registry/index");
var typeRegistry = require("../../../../../red/runtime/nodes/registry/registry");
describe('nodes/registry/installer', function() {
before(function() {
installer.init({});
});
afterEach(function() {
if (child_process.execFile.restore) {
child_process.execFile.restore();
}
})
describe("installs module", function() {
it("rejects when npm returns a 404", function(done) {
sinon.stub(child_process,"execFile",function(cmd,args,opt,cb) {
cb(new Error(),""," 404 this_wont_exist");
});
installer.installModule("this_wont_exist").otherwise(function(err) {
err.code.should.be.eql(404);
done();
});
});
it("rejects with generic error", function(done) {
sinon.stub(child_process,"execFile",function(cmd,args,opt,cb) {
cb(new Error("test_error"),"","");
});
installer.installModule("this_wont_exist").then(function() {
done(new Error("Unexpected success"));
}).otherwise(function(err) {
done();
});
});
it("succeeds when module is found", function(done) {
var nodeInfo = {nodes:{module:"foo",types:["a"]}};
sinon.stub(child_process,"execFile",function(cmd,args,opt,cb) {
cb(null,"","");
});
var addModule = sinon.stub(registry,"addModule",function(md) {
return when.resolve(nodeInfo);
});
installer.installModule("this_wont_exist").then(function(info) {
info.should.eql(nodeInfo);
// commsMessages.should.have.length(1);
// commsMessages[0].topic.should.equal("node/added");
// commsMessages[0].msg.should.eql(nodeInfo.nodes);
done();
}).otherwise(function(err) {
done(err);
}).finally(function() {
addModule.restore();
});
});
it("rejects when non-existant path is provided", function(done) {
var resourcesDir = path.resolve(path.join(__dirname,"..","resources","TestNodeModule","node_modules","NonExistant"));
installer.installModule(resourcesDir).then(function() {
done(new Error("Unexpected success"));
}).otherwise(function(err) {
err.code.should.eql(404);
done();
});
});
it("succeeds when path is valid node-red module", function(done) {
var nodeInfo = {nodes:{module:"foo",types:["a"]}};
var addModule = sinon.stub(registry,"addModule",function(md) {
return when.resolve(nodeInfo);
});
var resourcesDir = path.resolve(path.join(__dirname,"..","resources","TestNodeModule","node_modules","TestNodeModule"));
sinon.stub(child_process,"execFile",function(cmd,args,opt,cb) {
cb(null,"","");
});
installer.installModule(resourcesDir).then(function(info) {
info.should.eql(nodeInfo);
done();
}).otherwise(function(err) {
done(err);
}).finally(function() {
addModule.restore();
});
});
});
describe("uninstalls module", function() {
it("rejects invalid module names", function(done) {
var promises = [];
promises.push(installer.uninstallModule("this_wont_exist "));
promises.push(installer.uninstallModule("this_wont_exist;no_it_really_wont"));
when.settle(promises).then(function(results) {
results[0].state.should.be.eql("rejected");
results[1].state.should.be.eql("rejected");
done();
});
});
it("rejects with generic error", function(done) {
var nodeInfo = [{module:"foo",types:["a"]}];
var removeModule = sinon.stub(registry,"removeModule",function(md) {
return when.resolve(nodeInfo);
});
sinon.stub(child_process,"execFile",function(cmd,args,opt,cb) {
cb(new Error("test_error"),"","");
});
installer.uninstallModule("this_wont_exist").then(function() {
done(new Error("Unexpected success"));
}).otherwise(function(err) {
done();
}).finally(function() {
removeModule.restore();
});
});
it("succeeds when module is found", function(done) {
var nodeInfo = [{module:"foo",types:["a"]}];
var removeModule = sinon.stub(typeRegistry,"removeModule",function(md) {
return nodeInfo;
});
var getModuleInfo = sinon.stub(registry,"getModuleInfo",function(md) {
return {nodes:[]};
});
sinon.stub(child_process,"execFile",function(cmd,args,opt,cb) {
cb(null,"","");
});
var exists = sinon.stub(require('fs'),"existsSync", function(fn) { return true; });
installer.uninstallModule("this_wont_exist").then(function(info) {
info.should.eql(nodeInfo);
// commsMessages.should.have.length(1);
// commsMessages[0].topic.should.equal("node/removed");
// commsMessages[0].msg.should.eql(nodeInfo);
done();
}).otherwise(function(err) {
done(err);
}).finally(function() {
removeModule.restore();
exists.restore();
getModuleInfo.restore();
});
});
});
});

View File

@@ -0,0 +1,218 @@
/**
* Copyright 2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var should = require("should");
var when = require("when");
var sinon = require("sinon");
var typeRegistry = require("../../../../../red/runtime/nodes/registry/registry");
describe("red/nodes/registry/registry",function() {
beforeEach(function() {
typeRegistry.clear();
});
function stubSettings(s,available,initialConfig) {
s.available = function() {return available;};
s.set = function(s,v) { return when.resolve();};
s.get = function(s) { return initialConfig;};
return s;
}
var settings = stubSettings({},false,null);
var settingsWithStorageAndInitialConfig = stubSettings({},true,{"node-red":{module:"testModule",name:"testName",version:"testVersion",nodes:{"node":{id:"node-red/testName",name:"test",types:["a","b"],enabled:true}}}});
var testNodeSet1 = {
id: "test-module/test-name",
module: "test-module",
name: "test-name",
enabled: true,
loaded: false,
types: [ "test-a","test-b"]
};
var testNodeSet2 = {
id: "test-module/test-name-2",
module: "test-module",
name: "test-name-2",
enabled: true,
loaded: false,
types: [ "test-c","test-d"]
};
var testNodeSet2WithError = {
id: "test-module/test-name-2",
module: "test-module",
name: "test-name-2",
enabled: true,
loaded: false,
err: "I have an error",
types: [ "test-c","test-d"]
};
describe('#init', function() {
it('loads initial config', function(done) {
typeRegistry.init(settingsWithStorageAndInitialConfig);
typeRegistry.getNodeList().should.have.lengthOf(1);
done();
});
it('migrates legacy format', function(done) {
var legacySettings = {
available: function() { return true; },
set: sinon.stub().returns(when.resolve()),
get: function() { return {
"123": {
"name": "72-sentiment.js",
"types": [
"sentiment"
],
"enabled": true
},
"456": {
"name": "20-inject.js",
"types": [
"inject"
],
"enabled": true
},
"789": {
"name": "testModule:a-module.js",
"types": [
"example"
],
"enabled":true,
"module":"testModule"
}
}}
};
var expected = JSON.parse('{"node-red":{"name":"node-red","nodes":{"sentiment":{"name":"sentiment","types":["sentiment"],"enabled":true,"module":"node-red"},"inject":{"name":"inject","types":["inject"],"enabled":true,"module":"node-red"}}},"testModule":{"name":"testModule","nodes":{"a-module.js":{"name":"a-module.js","types":["example"],"enabled":true,"module":"testModule"}}}}');
typeRegistry.init(legacySettings);
legacySettings.set.calledOnce.should.be.true;
legacySettings.set.args[0][1].should.eql(expected);
done();
});
});
describe('#addNodeSet', function() {
it('adds a node set for an unknown module', function() {
typeRegistry.init(settings);
typeRegistry.getNodeList().should.have.lengthOf(0);
typeRegistry.getModuleList().should.eql({});
typeRegistry.addNodeSet("test-module/test-name",testNodeSet1, "0.0.1");
typeRegistry.getNodeList().should.have.lengthOf(1);
var moduleList = typeRegistry.getModuleList();
moduleList.should.have.a.property("test-module");
moduleList["test-module"].should.have.a.property("name","test-module");
moduleList["test-module"].should.have.a.property("version","0.0.1");
moduleList["test-module"].should.have.a.property("nodes");
moduleList["test-module"].nodes.should.have.a.property("test-name");
moduleList["test-module"].nodes["test-name"].should.eql({
id: 'test-module/test-name',
module: 'test-module',
name: 'test-name',
enabled: true,
loaded: false,
types: [ 'test-a', 'test-b' ]
});
});
it('adds a node set to an existing module', function() {
typeRegistry.init(settings);
typeRegistry.getNodeList().should.have.lengthOf(0);
typeRegistry.getModuleList().should.eql({});
typeRegistry.addNodeSet("test-module/test-name",testNodeSet1, "0.0.1");
typeRegistry.getNodeList().should.have.lengthOf(1);
var moduleList = typeRegistry.getModuleList();
Object.keys(moduleList).should.have.a.lengthOf(1);
moduleList.should.have.a.property("test-module");
moduleList["test-module"].should.have.a.property("name","test-module");
moduleList["test-module"].should.have.a.property("version","0.0.1");
moduleList["test-module"].should.have.a.property("nodes");
Object.keys(moduleList["test-module"].nodes).should.have.a.lengthOf(1);
moduleList["test-module"].nodes.should.have.a.property("test-name");
typeRegistry.addNodeSet("test-module/test-name-2",testNodeSet2);
typeRegistry.getNodeList().should.have.lengthOf(2);
moduleList = typeRegistry.getModuleList();
Object.keys(moduleList).should.have.a.lengthOf(1);
Object.keys(moduleList["test-module"].nodes).should.have.a.lengthOf(2);
moduleList["test-module"].nodes.should.have.a.property("test-name");
moduleList["test-module"].nodes.should.have.a.property("test-name-2");
});
it('doesnt add node set types if node set has an error', function() {
typeRegistry.init(settings);
typeRegistry.getNodeList().should.have.lengthOf(0);
typeRegistry.getModuleList().should.eql({});
typeRegistry.addNodeSet("test-module/test-name",testNodeSet1, "0.0.1");
typeRegistry.getTypeId("test-a").should.eql("test-module/test-name");
should.not.exist(typeRegistry.getTypeId("test-c"));
typeRegistry.addNodeSet("test-module/test-name-2",testNodeSet2WithError, "0.0.1");
should.not.exist(typeRegistry.getTypeId("test-c"));
});
});
describe("#enableNodeSet", function() {
it('throws error if settings unavailable', function() {
typeRegistry.init(settings);
/*jshint immed: false */
(function(){
typeRegistry.enableNodeSet("test-module/test-name");
}).should.throw("Settings unavailable");
});
it('throws error if module unknown', function() {
typeRegistry.init(settingsWithStorageAndInitialConfig);
/*jshint immed: false */
(function(){
typeRegistry.enableNodeSet("test-module/unknown");
}).should.throw("Unrecognised id: test-module/unknown");
});
});
describe('#getNodeConfig', function() {
it('returns nothing for an unregistered type config', function(done) {
typeRegistry.init(settings);
var config = typeRegistry.getNodeConfig("imaginary-shark");
(config === null).should.be.true;
done();
});
});
});

View File

@@ -0,0 +1,3 @@
<script type="text/x-red" data-template-name="test-node-1"></script>
<script type="text/x-red" data-help-name="test-node-1"></script>
<script type="text/javascript">RED.nodes.registerType('test-node-1',{});</script>

View File

@@ -0,0 +1,5 @@
// A test node that exports a function
module.exports = function(RED) {
function DuplicateTestNode(n) {}
RED.nodes.registerType("test-node-1",DuplicateTestNode);
}

View File

@@ -0,0 +1,6 @@
<script type="text/x-red" data-template-name="test-node-multiple-1a"></script>
<script type="text/x-red" data-help-name="test-node-multiple-1a"></script>
<script type="text/javascript">RED.nodes.registerType('test-node-multiple-1a',{});</script>
<script type="text/x-red" data-template-name="test-node-multiple-1b"></script>
<script type="text/x-red" data-help-name="test-node-multiple-1b"></script>
<script type="text/javascript">RED.nodes.registerType('test-node-multiple-1b',{});</script>

View File

@@ -0,0 +1,7 @@
// A test node that exports a function
module.exports = function(RED) {
function TestNode1(n) {}
RED.nodes.registerType("test-node-multiple-1a",TestNode1);
function TestNode2(n) {}
RED.nodes.registerType("test-node-multiple-1b",TestNode2);
}

View File

@@ -0,0 +1,4 @@
<script type="text/x-red" data-template-name="nested-node-1"></script>
<script type="text/x-red" data-help-name="nested-node-1"></script>
<script type="text/javascript">RED.nodes.registerType('nested-node-1',{});</script>
<style></style>

View File

@@ -0,0 +1,5 @@
// A test node that exports a function
module.exports = function(RED) {
function TestNode(n) {}
RED.nodes.registerType("nested-node-1",TestNode);
}

View File

@@ -0,0 +1,3 @@
This file exists just to ensure the 'icons' directory is in the repository.
TODO: a future test needs to ensure the right icon files are loaded - this
directory can be used for that

View File

@@ -0,0 +1,4 @@
<script type="text/x-red" data-template-name="should-not-load-1"></script>
<script type="text/x-red" data-help-name="should-not-load-1"></script>
<script type="text/javascript">RED.nodes.registerType('should-not-load-1',{});</script>
<style></style>

View File

@@ -0,0 +1,5 @@
// A test node that exports a function
module.exports = function(RED) {
function TestNode(n) {}
RED.nodes.registerType("should-not-load-1",TestNode);
}

View File

@@ -0,0 +1,4 @@
<script type="text/x-red" data-template-name="should-not-load-3"></script>
<script type="text/x-red" data-help-name="should-not-load-3"></script>
<script type="text/javascript">RED.nodes.registerType('should-not-load-3',{});</script>
<style></style>

View File

@@ -0,0 +1,5 @@
// A test node that exports a function
module.exports = function(RED) {
function TestNode(n) {}
RED.nodes.registerType("should-not-load-3",TestNode);
}

View File

@@ -0,0 +1,5 @@
<script type="text/x-red" data-template-name="test-node-1"></script>
<script type="text/x-red" data-help-name="test-node-1"></script>
<script type="text/javascript">RED.nodes.registerType('test-node-1',{});</script>
<style></style>
<p>this should be filtered out</p>

View File

@@ -0,0 +1,5 @@
// A test node that exports a function
module.exports = function(RED) {
function TestNode(n) {}
RED.nodes.registerType("test-node-1",TestNode);
}

View File

@@ -0,0 +1,4 @@
<script type="text/x-red" data-template-name="test-node-2"></script>
<script type="text/x-red" data-help-name="test-node-2"></script>
<script type="text/javascript">RED.nodes.registerType('test-node-2',{});</script>
<style></style>

View File

@@ -0,0 +1,10 @@
// A test node that exports a function which returns a resolving promise
var when = require("when");
module.exports = function(RED) {
return when.promise(function(resolve,reject) {
function TestNode(n) {}
RED.nodes.registerType("test-node-2",TestNode);
resolve();
});
}

View File

@@ -0,0 +1,3 @@
<script type="text/x-red" data-template-name="test-node-3"></script>
<script type="text/x-red" data-help-name="test-node-3"></script>
<script type="text/javascript">RED.nodes.registerType('test-node-3',{});</script>

View File

@@ -0,0 +1,8 @@
// A test node that exports a function which returns a rejecting promise
var when = require("when");
module.exports = function(RED) {
return when.promise(function(resolve,reject) {
reject("fail");
});
}

View File

@@ -0,0 +1,141 @@
/**
* Copyright 2014 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var should = require("should");
var when = require("when");
var settings = require("../../../red/runtime/settings");
describe("red/settings", function() {
afterEach(function() {
settings.reset();
});
it('wraps the user settings as read-only properties', function() {
var userSettings = {
a: 123,
b: "test",
c: [1,2,3]
}
settings.init(userSettings);
settings.available().should.be.false;
settings.a.should.equal(123);
settings.b.should.equal("test");
settings.c.should.be.an.Array.with.lengthOf(3);
settings.get("a").should.equal(123);
settings.get("b").should.equal("test");
settings.get("c").should.be.an.Array.with.lengthOf(3);
/*jshint immed: false */
(function() {
settings.a = 456;
}).should.throw();
settings.c.push(5);
settings.c.should.be.an.Array.with.lengthOf(4);
/*jshint immed: false */
(function() {
settings.set("a",456);
}).should.throw();
/*jshint immed: false */
(function() {
settings.set("a",456);
}).should.throw();
/*jshint immed: false */
(function() {
settings.get("unknown");
}).should.throw();
/*jshint immed: false */
(function() {
settings.set("unknown",456);
}).should.throw();
});
it('loads global settings from storage', function(done) {
var userSettings = {
a: 123,
b: "test",
c: [1,2,3]
}
var savedSettings = null;
var saveCount = 0;
var storage = {
getSettings: function() {
return when.resolve({globalA:789});
},
saveSettings: function(settings) {
saveCount++;
savedSettings = settings;
return when.resolve();
}
}
settings.init(userSettings);
settings.available().should.be.false;
/*jshint immed: false */
(function() {
settings.get("unknown");
}).should.throw();
settings.load(storage).then(function() {
settings.available().should.be.true;
settings.get("globalA").should.equal(789);
settings.set("globalA","abc").then(function() {
savedSettings.globalA.should.equal("abc");
saveCount.should.equal(1);
settings.set("globalA","abc").then(function() {
savedSettings.globalA.should.equal("abc");
// setting to existing value should not trigger save
saveCount.should.equal(1);
done();
});
});
}).otherwise(function(err) {
done(err);
});
});
it('removes persistent settings when reset', function() {
var userSettings = {
a: 123,
b: "test",
c: [1,2,3]
}
settings.init(userSettings);
settings.available().should.be.false;
settings.should.have.property("a",123);
settings.should.have.property("b","test");
settings.c.should.be.an.Array.with.lengthOf(3);
settings.reset();
settings.should.not.have.property("a");
settings.should.not.have.property("d");
settings.should.not.have.property("c");
});
});

View File

@@ -0,0 +1,250 @@
/**
* Copyright 2014, 2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var when = require("when");
var should = require("should");
var storage = require("../../../../red/runtime/storage/index");
describe("red/storage/index", function() {
it('rejects the promise when settings suggest loading a bad module', function(done) {
var wrongModule = {
storageModule : "thisaintloading"
};
storage.init(wrongModule).then( function() {
var one = 1;
var zero = 0;
try {
zero.should.equal(one, "The initialization promise should never get resolved");
} catch(err) {
done(err);
}
}).catch(function(e) {
done(); //successfully rejected promise
});
});
it('non-string storage module', function(done) {
var initSetsMeToTrue = false;
var moduleWithBooleanSettingInit = {
init : function() {
initSetsMeToTrue = true;
}
};
var setsBooleanModule = {
storageModule : moduleWithBooleanSettingInit
};
storage.init(setsBooleanModule);
initSetsMeToTrue.should.be.true;
done();
});
it('respects storage interface', function() {
var calledFlagGetFlows = false;
var calledFlagGetCredentials = false;
var calledFlagGetAllFlows = false;
var calledInit = false;
var calledFlagGetSettings = false;
var calledFlagGetSessions = false;
var interfaceCheckerModule = {
init : function (settings) {
settings.should.be.an.Object;
calledInit = true;
},
getFlows : function() {
calledFlagGetFlows = true;
},
saveFlows : function (flows) {
flows.should.be.true;
},
getCredentials : function() {
calledFlagGetCredentials = true;
},
saveCredentials : function(credentials) {
credentials.should.be.true;
},
getSettings : function() {
calledFlagGetSettings = true;
},
saveSettings : function(settings) {
settings.should.be.true;
},
getSessions : function() {
calledFlagGetSessions = true;
},
saveSessions : function(sessions) {
sessions.should.be.true;
},
getAllFlows : function() {
calledFlagGetAllFlows = true;
},
getFlow : function(fn) {
fn.should.equal("name");
},
saveFlow : function(fn, data) {
fn.should.equal("name");
data.should.be.true;
},
getLibraryEntry : function(type, path) {
type.should.be.true;
path.should.equal("name");
},
saveLibraryEntry : function(type, path, meta, body) {
type.should.be.true;
path.should.equal("name");
meta.should.be.true;
body.should.be.true;
}
};
var moduleToLoad = {
storageModule : interfaceCheckerModule
};
storage.init(moduleToLoad);
storage.getFlows();
storage.saveFlows(true);
storage.getCredentials();
storage.saveCredentials(true);
storage.getSettings();
storage.saveSettings(true);
storage.getSessions();
storage.saveSessions(true);
storage.getAllFlows();
storage.getFlow("name");
storage.saveFlow("name", true);
storage.getLibraryEntry(true, "name");
storage.saveLibraryEntry(true, "name", true, true);
calledInit.should.be.true;
calledFlagGetFlows.should.be.true;
calledFlagGetCredentials.should.be.true;
calledFlagGetAllFlows.should.be.true;
});
describe('respects deprecated flow library functions', function() {
var savePath;
var saveContent;
var saveMeta;
var saveType;
var interfaceCheckerModule = {
init : function (settings) {
settings.should.be.an.Object;
},
getLibraryEntry : function(type, path) {
if (type === "flows") {
if (path == "/") {
return when.resolve(["a",{fn:"test.json"}]);
} else if (path == "/a") {
return when.resolve([{fn:"test2.json"}]);
} else if (path == "/a/test2.json") {
return when.resolve("test content");
}
}
},
saveLibraryEntry : function(type, path, meta, body) {
saveType = type;
savePath = path;
saveContent = body;
saveMeta = meta;
return when.resolve();
}
};
var moduleToLoad = {
storageModule : interfaceCheckerModule
};
before(function() {
storage.init(moduleToLoad);
});
it('getAllFlows',function(done) {
storage.getAllFlows().then(function (res) {
try {
res.should.eql({ d: { a: { f: ['test2'] } }, f: [ 'test' ] });
done();
} catch(err) {
done(err);
}
});
});
it('getFlow',function(done) {
storage.getFlow("/a/test2.json").then(function(res) {
try {
res.should.eql("test content");
done();
} catch(err) {
done(err);
}
});
});
it ('saveFlow', function (done) {
storage.saveFlow("/a/test2.json","new content").then(function(res) {
try {
savePath.should.eql("/a/test2.json");
saveContent.should.eql("new content");
saveMeta.should.eql({});
saveType.should.eql("flows");
done();
} catch(err) {
done(err);
}
});
});
});
describe('handles missing settings/sessions interface', function() {
before(function() {
var interfaceCheckerModule = {
init : function () {}
};
storage.init({storageModule: interfaceCheckerModule});
});
it('defaults missing getSettings',function(done) {
storage.getSettings().then(function(settings) {
should.not.exist(settings);
done();
});
});
it('defaults missing saveSettings',function(done) {
storage.saveSettings({}).then(function() {
done();
});
});
it('defaults missing getSessions',function(done) {
storage.getSessions().then(function(settings) {
should.not.exist(settings);
done();
});
});
it('defaults missing saveSessions',function(done) {
storage.saveSessions({}).then(function() {
done();
});
});
});
});

View File

@@ -0,0 +1,561 @@
/**
* Copyright 2013, 2014 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var should = require("should");
var fs = require('fs-extra');
var path = require('path');
var localfilesystem = require("../../../../red/runtime/storage/localfilesystem");
describe('LocalFileSystem', function() {
var userDir = path.join(__dirname,".testUserHome");
var testFlow = [{"type":"tab","id":"d8be2a6d.2741d8","label":"Sheet 1"}];
beforeEach(function(done) {
fs.remove(userDir,function(err) {
fs.mkdir(userDir,done);
});
});
afterEach(function(done) {
fs.remove(userDir,done);
});
it('should initialise the user directory',function(done) {
localfilesystem.init({userDir:userDir}).then(function() {
fs.existsSync(path.join(userDir,"lib")).should.be.true;
fs.existsSync(path.join(userDir,"lib",'flows')).should.be.true;
done();
}).otherwise(function(err) {
done(err);
});
});
it('should set userDir to NRH is .config.json present',function(done) {
var oldNRH = process.env.NODE_RED_HOME;
process.env.NODE_RED_HOME = path.join(userDir,"NRH");
fs.mkdirSync(process.env.NODE_RED_HOME);
fs.writeFileSync(path.join(process.env.NODE_RED_HOME,".config.json"),"{}","utf8");
var settings = {};
localfilesystem.init(settings).then(function() {
try {
fs.existsSync(path.join(process.env.NODE_RED_HOME,"lib")).should.be.true;
fs.existsSync(path.join(process.env.NODE_RED_HOME,"lib",'flows')).should.be.true;
settings.userDir.should.equal(process.env.NODE_RED_HOME);
done();
} catch(err) {
done(err);
} finally {
process.env.NODE_RED_HOME = oldNRH;
}
}).otherwise(function(err) {
done(err);
});
});
it('should set userDir to HOME/.node-red',function(done) {
var oldNRH = process.env.NODE_RED_HOME;
process.env.NODE_RED_HOME = path.join(userDir,"NRH");
var oldHOME = process.env.HOME;
process.env.HOME = path.join(userDir,"HOME");
fs.mkdirSync(process.env.HOME);
var settings = {};
localfilesystem.init(settings).then(function() {
try {
fs.existsSync(path.join(process.env.HOME,".node-red","lib")).should.be.true;
fs.existsSync(path.join(process.env.HOME,".node-red","lib",'flows')).should.be.true;
settings.userDir.should.equal(path.join(process.env.HOME,".node-red"));
done();
} catch(err) {
done(err);
} finally {
process.env.NODE_RED_HOME = oldNRH;
process.env.HOME = oldHOME;
}
}).otherwise(function(err) {
done(err);
});
});
it('should handle missing flow file',function(done) {
localfilesystem.init({userDir:userDir}).then(function() {
var flowFile = 'flows_'+require('os').hostname()+'.json';
var flowFilePath = path.join(userDir,flowFile);
fs.existsSync(flowFilePath).should.be.false;
localfilesystem.getFlows().then(function(flows) {
flows.should.eql([]);
done();
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
});
it('should save flows to the default file',function(done) {
localfilesystem.init({userDir:userDir}).then(function() {
var flowFile = 'flows_'+require('os').hostname()+'.json';
var flowFilePath = path.join(userDir,flowFile);
var flowFileBackupPath = path.join(userDir,"."+flowFile+".backup");
fs.existsSync(flowFilePath).should.be.false;
fs.existsSync(flowFileBackupPath).should.be.false;
localfilesystem.saveFlows(testFlow).then(function() {
fs.existsSync(flowFilePath).should.be.true;
fs.existsSync(flowFileBackupPath).should.be.false;
localfilesystem.getFlows().then(function(flows) {
flows.should.eql(testFlow);
done();
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
});
it('should save flows to the specified file',function(done) {
var defaultFlowFile = 'flows_'+require('os').hostname()+'.json';
var defaultFlowFilePath = path.join(userDir,defaultFlowFile);
var flowFile = 'test.json';
var flowFilePath = path.join(userDir,flowFile);
localfilesystem.init({userDir:userDir, flowFile:flowFilePath}).then(function() {
fs.existsSync(defaultFlowFilePath).should.be.false;
fs.existsSync(flowFilePath).should.be.false;
localfilesystem.saveFlows(testFlow).then(function() {
fs.existsSync(defaultFlowFilePath).should.be.false;
fs.existsSync(flowFilePath).should.be.true;
localfilesystem.getFlows().then(function(flows) {
flows.should.eql(testFlow);
done();
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
});
it('should format the flows file when flowFilePretty specified',function(done) {
var flowFile = 'test.json';
var flowFilePath = path.join(userDir,flowFile);
localfilesystem.init({userDir:userDir, flowFile:flowFilePath,flowFilePretty:true}).then(function() {
localfilesystem.saveFlows(testFlow).then(function() {
var content = fs.readFileSync(flowFilePath,"utf8");
content.split("\n").length.should.be.above(1);
localfilesystem.getFlows().then(function(flows) {
flows.should.eql(testFlow);
done();
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
});
it('should backup the flows file', function(done) {
var defaultFlowFile = 'flows_'+require('os').hostname()+'.json';
var defaultFlowFilePath = path.join(userDir,defaultFlowFile);
var flowFile = 'test.json';
var flowFilePath = path.join(userDir,flowFile);
var flowFileBackupPath = path.join(userDir,"."+flowFile+".backup");
localfilesystem.init({userDir:userDir, flowFile:flowFilePath}).then(function() {
fs.existsSync(defaultFlowFilePath).should.be.false;
fs.existsSync(flowFilePath).should.be.false;
fs.existsSync(flowFileBackupPath).should.be.false;
localfilesystem.saveFlows(testFlow).then(function() {
fs.existsSync(flowFileBackupPath).should.be.false;
fs.existsSync(defaultFlowFilePath).should.be.false;
fs.existsSync(flowFilePath).should.be.true;
var content = fs.readFileSync(flowFilePath,'utf8');
var testFlow2 = [{"type":"tab","id":"bc5672ad.2741d8","label":"Sheet 2"}];
localfilesystem.saveFlows(testFlow2).then(function() {
fs.existsSync(flowFileBackupPath).should.be.true;
fs.existsSync(defaultFlowFilePath).should.be.false;
fs.existsSync(flowFilePath).should.be.true;
var backupContent = fs.readFileSync(flowFileBackupPath,'utf8');
content.should.equal(backupContent);
var content2 = fs.readFileSync(flowFilePath,'utf8');
content2.should.not.equal(backupContent);
done();
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
});
it('should handle missing credentials', function(done) {
var flowFile = 'test.json';
var flowFilePath = path.join(userDir,flowFile);
var credFile = path.join(userDir,"test_cred.json");
localfilesystem.init({userDir:userDir, flowFile:flowFilePath}).then(function() {
fs.existsSync(credFile).should.be.false;
localfilesystem.getCredentials().then(function(creds) {
creds.should.eql({});
done();
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
});
it('should handle credentials', function(done) {
var flowFile = 'test.json';
var flowFilePath = path.join(userDir,flowFile);
var credFile = path.join(userDir,"test_cred.json");
localfilesystem.init({userDir:userDir, flowFile:flowFilePath}).then(function() {
fs.existsSync(credFile).should.be.false;
var credentials = {"abc":{"type":"creds"}};
localfilesystem.saveCredentials(credentials).then(function() {
fs.existsSync(credFile).should.be.true;
localfilesystem.getCredentials().then(function(creds) {
creds.should.eql(credentials);
done();
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
});
it('should backup existing credentials', function(done) {
var flowFile = 'test.json';
var flowFilePath = path.join(userDir,flowFile);
var credFile = path.join(userDir,"test_cred.json");
var credFileBackup = path.join(userDir,".test_cred.json.backup");
localfilesystem.init({userDir:userDir, flowFile:flowFilePath}).then(function() {
fs.writeFileSync(credFile,"{}","utf8");
fs.existsSync(credFile).should.be.true;
fs.existsSync(credFileBackup).should.be.false;
var credentials = {"abc":{"type":"creds"}};
localfilesystem.saveCredentials(credentials).then(function() {
fs.existsSync(credFile).should.be.true;
fs.existsSync(credFileBackup).should.be.true;
done();
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
});
it('should format the creds file when flowFilePretty specified',function(done) {
var flowFile = 'test.json';
var flowFilePath = path.join(userDir,flowFile);
var credFile = path.join(userDir,"test_cred.json");
localfilesystem.init({userDir:userDir, flowFile:flowFilePath, flowFilePretty:true}).then(function() {
fs.existsSync(credFile).should.be.false;
var credentials = {"abc":{"type":"creds"}};
localfilesystem.saveCredentials(credentials).then(function() {
fs.existsSync(credFile).should.be.true;
var content = fs.readFileSync(credFile,"utf8");
content.split("\n").length.should.be.above(1);
localfilesystem.getCredentials().then(function(creds) {
creds.should.eql(credentials);
done();
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
});
it('should handle non-existent settings', function(done) {
var settingsFile = path.join(userDir,".settings.json");
localfilesystem.init({userDir:userDir}).then(function() {
fs.existsSync(settingsFile).should.be.false;
localfilesystem.getSettings().then(function(settings) {
settings.should.eql({});
done();
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
});
it('should handle corrupt settings', function(done) {
var settingsFile = path.join(userDir,".config.json");
fs.writeFileSync(settingsFile,"[This is not json","utf8");
localfilesystem.init({userDir:userDir}).then(function() {
fs.existsSync(settingsFile).should.be.true;
localfilesystem.getSettings().then(function(settings) {
settings.should.eql({});
done();
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
});
it('should handle settings', function(done) {
var settingsFile = path.join(userDir,".config.json");
localfilesystem.init({userDir:userDir}).then(function() {
fs.existsSync(settingsFile).should.be.false;
var settings = {"abc":{"type":"creds"}};
localfilesystem.saveSettings(settings).then(function() {
fs.existsSync(settingsFile).should.be.true;
localfilesystem.getSettings().then(function(_settings) {
_settings.should.eql(settings);
done();
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
});
it('should handle non-existent sessions', function(done) {
var sessionsFile = path.join(userDir,".sessions.json");
localfilesystem.init({userDir:userDir}).then(function() {
fs.existsSync(sessionsFile).should.be.false;
localfilesystem.getSessions().then(function(sessions) {
sessions.should.eql({});
done();
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
});
it('should handle corrupt sessions', function(done) {
var sessionsFile = path.join(userDir,".sessions.json");
fs.writeFileSync(sessionsFile,"[This is not json","utf8");
localfilesystem.init({userDir:userDir}).then(function() {
fs.existsSync(sessionsFile).should.be.true;
localfilesystem.getSessions().then(function(sessions) {
sessions.should.eql({});
done();
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
});
it('should handle sessions', function(done) {
var sessionsFile = path.join(userDir,".sessions.json");
localfilesystem.init({userDir:userDir}).then(function() {
fs.existsSync(sessionsFile).should.be.false;
var sessions = {"abc":{"type":"creds"}};
localfilesystem.saveSessions(sessions).then(function() {
fs.existsSync(sessionsFile).should.be.true;
localfilesystem.getSessions().then(function(_sessions) {
_sessions.should.eql(sessions);
done();
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
});
it('should return an empty list of library objects',function(done) {
localfilesystem.init({userDir:userDir}).then(function() {
localfilesystem.getLibraryEntry('object','').then(function(flows) {
flows.should.eql([]);
done();
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
});
it('should return an error for a non-existent library object',function(done) {
localfilesystem.init({userDir:userDir}).then(function() {
localfilesystem.getLibraryEntry('object','A/B').then(function(flows) {
should.fail(null,null,"non-existent flow");
}).otherwise(function(err) {
should.exist(err);
done();
});
}).otherwise(function(err) {
done(err);
});
});
function createObjectLibrary(type) {
type = type ||"object";
var objLib = path.join(userDir,"lib",type);
try {
fs.mkdirSync(objLib);
} catch(err) {
}
fs.mkdirSync(path.join(objLib,"A"));
fs.mkdirSync(path.join(objLib,"B"));
fs.mkdirSync(path.join(objLib,"B","C"));
fs.writeFileSync(path.join(objLib,"file1.js"),"// abc: def\n// not a metaline \n\n Hi",'utf8');
fs.writeFileSync(path.join(objLib,"B","file2.js"),"// ghi: jkl\n// not a metaline \n\n Hi",'utf8');
fs.writeFileSync(path.join(objLib,"B","flow.json"),"Hi",'utf8');
}
it('should return a directory listing of library objects',function(done) {
localfilesystem.init({userDir:userDir}).then(function() {
createObjectLibrary();
localfilesystem.getLibraryEntry('object','').then(function(flows) {
flows.should.eql([ 'A', 'B', { abc: 'def', fn: 'file1.js' } ]);
localfilesystem.getLibraryEntry('object','B').then(function(flows) {
flows.should.eql([ 'C', { ghi: 'jkl', fn: 'file2.js' }, { fn: 'flow.json' } ]);
localfilesystem.getLibraryEntry('object','B/C').then(function(flows) {
flows.should.eql([]);
done();
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
});
it('should load a flow library object with .json unspecified', function(done) {
localfilesystem.init({userDir:userDir}).then(function() {
createObjectLibrary("flows");
localfilesystem.getLibraryEntry('flows','B/flow').then(function(flows) {
flows.should.eql("Hi");
done();
}).otherwise(function(err) {
done(err);
});
});
});
it('should return a library object',function(done) {
localfilesystem.init({userDir:userDir}).then(function() {
createObjectLibrary();
localfilesystem.getLibraryEntry('object','B/file2.js').then(function(body) {
body.should.eql("// not a metaline \n\n Hi");
done();
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
});
it('should return a newly saved library object',function(done) {
localfilesystem.init({userDir:userDir}).then(function() {
createObjectLibrary();
localfilesystem.getLibraryEntry('object','B').then(function(flows) {
flows.should.eql([ 'C', { ghi: 'jkl', fn: 'file2.js' }, {fn:'flow.json'} ]);
localfilesystem.saveLibraryEntry('object','B/D/file3.js',{mno:'pqr'},"// another non meta line\n\n Hi There").then(function() {
localfilesystem.getLibraryEntry('object','B/D').then(function(flows) {
flows.should.eql([ { mno: 'pqr', fn: 'file3.js' } ]);
localfilesystem.getLibraryEntry('object','B/D/file3.js').then(function(body) {
body.should.eql("// another non meta line\n\n Hi There");
done();
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
}).otherwise(function(err) {
done(err);
});
});
});

View File

@@ -0,0 +1,115 @@
/**
* Copyright 2014, 2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var should = require("should");
var util = require("../../../red/runtime/util");
describe("red/util", function() {
describe('generateId', function() {
it('generates an id', function() {
var id = util.generateId();
var id2 = util.generateId();
id.should.not.eql(id2);
});
});
describe('compareObjects', function() {
it('unequal arrays are unequal', function() {
util.compareObjects(["a"],"a").should.equal(false);
});
it('unequal key lengths are unequal', function() {
util.compareObjects({"a":1},{"a":1,"b":1}).should.equal(false);
});
});
describe('ensureString', function() {
it('strings are preserved', function() {
util.ensureString('string').should.equal('string');
});
it('Buffer is converted', function() {
var s = util.ensureString(new Buffer('foo'));
s.should.equal('foo');
(typeof s).should.equal('string');
});
it('Object is converted to JSON', function() {
var s = util.ensureString({foo: "bar"});
(typeof s).should.equal('string');
should.deepEqual(JSON.parse(s), {foo:"bar"});
});
it('stringifies other things', function() {
var s = util.ensureString(123);
(typeof s).should.equal('string');
s.should.equal('123');
});
});
describe('ensureBuffer', function() {
it('Buffers are preserved', function() {
var b = new Buffer('');
util.ensureBuffer(b).should.equal(b);
});
it('string is converted', function() {
var b = util.ensureBuffer('foo');
var expected = new Buffer('foo');
for (var i = 0; i < expected.length; i++) {
b[i].should.equal(expected[i]);
}
Buffer.isBuffer(b).should.equal(true);
});
it('Object is converted to JSON', function() {
var obj = {foo: "bar"}
var b = util.ensureBuffer(obj);
Buffer.isBuffer(b).should.equal(true);
should.deepEqual(JSON.parse(b), obj);
});
it('stringifies other things', function() {
var b = util.ensureBuffer(123);
Buffer.isBuffer(b).should.equal(true);
var expected = new Buffer('123');
for (var i = 0; i < expected.length; i++) {
b[i].should.equal(expected[i]);
}
});
});
describe('cloneMessage', function() {
it('clones a simple message', function() {
var msg = {string:"hi",array:[1,2,3],object:{a:1,subobject:{b:2}}};
var cloned = util.cloneMessage(msg);
cloned.should.eql(msg);
cloned.should.not.equal(msg);
cloned.array.should.not.equal(msg.string);
cloned.object.should.not.equal(msg.object);
cloned.object.subobject.should.not.equal(msg.object.subobject);
cloned.should.not.have.property("req");
cloned.should.not.have.property("res");
});
it('does not clone http req/res properties', function() {
var msg = {req:{a:1},res:{b:2}};
var cloned = util.cloneMessage(msg);
cloned.should.eql(msg);
cloned.should.not.equal(msg);
cloned.req.should.equal(msg.req);
cloned.res.should.equal(msg.res);
});
});
});