Reorganise red/api layout to better componentise

This commit is contained in:
Nick O'Leary
2017-08-22 22:26:29 +01:00
parent 96a0dbea2d
commit 41af5187aa
39 changed files with 1004 additions and 331 deletions

View File

@@ -0,0 +1,528 @@
/**
* Copyright JS Foundation and other contributors, http://js.foundation
*
* 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/api/editor/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("api/editor/comms", function() {
describe("with default keepalive", function() {
var server;
var url;
var port;
before(function(done) {
sinon.stub(Users,"default",function() { return when.resolve(null);});
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {
settings:{},
log:{warn:function(){},_:function(){},trace:function(){},audit:function(){}},
events:{on:function(){},removeListener:function(){}}
});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/comms';
comms.start();
done();
});
});
after(function() {
Users.default.restore();
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
it.skip('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();
});
});
it.skip('listens for node/status events');
});
describe("disabled editor", function() {
var server;
var url;
var port;
before(function(done) {
sinon.stub(Users,"default",function() { return when.resolve(null);});
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {
settings:{disableEditor:true},
log:{warn:function(){},_:function(){},trace:function(){},audit:function(){}},
events:{on:function(){},removeListener:function(){}}
});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/comms';
comms.start();
done();
});
});
after(function() {
Users.default.restore();
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) {
sinon.stub(Users,"default",function() { return when.resolve(null);});
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {
settings:{httpAdminRoot:"/adminPath"},
log:{warn:function(){},_:function(){},trace:function(){},audit:function(){}},
events:{on:function(){},removeListener:function(){}}
});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/adminPath/comms';
comms.start();
done();
});
});
after(function() {
Users.default.restore();
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) {
sinon.stub(Users,"default",function() { return when.resolve(null);});
server = http.createServer(function(req,res){app(req,res)});
comms.init(server,{
settings:{httpAdminRoot:"/adminPath"},
log:{warn:function(){},_:function(){},trace:function(){},audit:function(){}},
events:{on:function(){},removeListener:function(){}}
});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/adminPath/comms';
comms.start();
done();
});
});
after(function() {
Users.default.restore();
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) {
sinon.stub(Users,"default",function() { return when.resolve(null);});
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {
settings:{httpAdminRoot:"adminPath"},
log:{warn:function(){},_:function(){},trace:function(){},audit:function(){}},
events:{on:function(){},removeListener:function(){}}
});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/adminPath/comms';
comms.start();
done();
});
});
after(function() {
Users.default.restore();
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) {
sinon.stub(Users,"default",function() { return when.resolve(null);});
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {
settings:{webSocketKeepAliveTime: 100},
log:{warn:function(){},_:function(){},trace:function(){},audit:function(){}},
events:{on:function(){},removeListener:function(){}}
});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/comms';
comms.start();
done();
});
});
after(function() {
Users.default.restore();
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,{
settings:{adminAuth:{}},
log:{warn:function(){},_:function(){},trace:function(){},audit:function(){}},
events:{on:function(){},removeListener:function(){}}
});
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, {
settings:{adminAuth:{}},
log:{warn:function(){},_:function(){},trace:function(){},audit:function(){}},
events:{on:function(){},removeListener:function(){}}
});
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,106 @@
/**
* Copyright JS Foundation and other contributors, http://js.foundation
*
* 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 request = require('supertest');
var express = require('express');
var sinon = require('sinon');
var when = require('when');
var credentials = require("../../../../red/api/editor/credentials");
describe('api/editor/credentials', function() {
var app;
before(function() {
app = express();
app.get('/credentials/:type/:id',credentials.get);
credentials.init({
log:{audit:function(){}},
nodes:{
getCredentials: function(id) {
if (id === "n1") {
return {user1:"abc",password1:"123"};
} else {
return null;
}
},
getCredentialDefinition:function(type) {
if (type === "known-type") {
return {user1:{type:"text"},password1:{type:"password"}};
} else {
return null;
}
}
}
});
});
it('returns empty credentials if unknown type',function(done) {
request(app)
.get("/credentials/unknown-type/n1")
.expect(200)
.expect("Content-Type",/json/)
.end(function(err,res) {
if (err) {
done(err);
} else {
try {
res.body.should.eql({});
done();
} catch(e) {
done(e);
}
}
})
});
it('returns empty credentials if none are stored',function(done) {
request(app)
.get("/credentials/known-type/n2")
.expect("Content-Type",/json/)
.end(function(err,res) {
if (err) {
done(err);
} else {
try {
res.body.should.eql({});
done();
} catch(e) {
done(e);
}
}
})
});
it('returns stored credentials',function(done) {
request(app)
.get("/credentials/known-type/n1")
.expect("Content-Type",/json/)
.end(function(err,res) {
if (err) {
done(err);
} else {
try {
res.body.should.have.a.property("user1","abc");
res.body.should.not.have.a.property("password1");
res.body.should.have.a.property("has_password1",true);
done();
} catch(e) {
done(e);
}
}
})
});
});

View File

@@ -0,0 +1,109 @@
/**
* Copyright JS Foundation and other contributors, http://js.foundation
*
* 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 request = require("supertest");
var express = require("express");
var editorApi = require("../../../../red/api/editor");
var comms = require("../../../../red/api/editor/comms");
describe("api/editor/index", function() {
var app;
describe("disabled the editor", function() {
beforeEach(function() {
sinon.stub(comms,'init', function(){});
});
afterEach(function() {
comms.init.restore();
});
it("disables the editor", function() {
var editorApp = editorApi.init({},{
settings:{disableEditor:true}
});
should.not.exist(editorApp);
comms.init.called.should.be.false();
});
});
describe("enables the editor", function() {
var mockList = [
'library','theme','locales','credentials','comms'
]
var isStarted = true;
var errors = [];
before(function() {
mockList.forEach(function(m) {
sinon.stub(require("../../../../red/api/editor/"+m),"init",function(){});
});
sinon.stub(require("../../../../red/api/editor/theme"),"app",function(){ return express()});
});
after(function() {
mockList.forEach(function(m) {
require("../../../../red/api/editor/"+m).init.restore();
})
require("../../../../red/api/editor/theme").app.restore();
});
before(function() {
app = editorApi.init({},{
log:{audit:function(){},error:function(msg){errors.push(msg)}},
settings:{httpNodeRoot:true, httpAdminRoot: true,disableEditor:false},
events:{on:function(){},removeListener:function(){}},
isStarted: function() { return isStarted; }
});
});
it('serves the editor', function(done) {
request(app)
.get("/")
.expect(200)
.end(function(err,res) {
if (err) {
return done(err);
}
// Index page should probably mention Node-RED somewhere
res.text.indexOf("Node-RED").should.not.eql(-1);
done();
});
});
it('serves icons', function(done) {
request(app)
.get("/icons/inject.png")
.expect("Content-Type", /image\/png/)
.expect(200,done)
});
it('handles page not there', function(done) {
request(app)
.get("/foo")
.expect(404,done)
});
it('warns if runtime not started', function(done) {
isStarted = false;
request(app)
.get("/")
.expect(503)
.end(function(err,res) {
if (err) {
return done(err);
}
res.text.should.eql("Not started");
errors.should.have.lengthOf(1);
errors[0].should.eql("Node-RED runtime not started");
done();
});
});
});
});

View File

@@ -0,0 +1,302 @@
/**
* Copyright JS Foundation and other contributors, http://js.foundation
*
* 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 request = require('supertest');
var express = require('express');
var bodyParser = require('body-parser');
var when = require('when');
var app;
var library = require("../../../../red/api/editor/library");
var auth = require("../../../../red/api/auth");
describe("api/editor/library", function() {
function initLibrary(_flows,_libraryEntries,_examples) {
var flows = _flows;
var libraryEntries = _libraryEntries;
library.init(app,{
log:{audit:function(){},_:function(){},warn:function(){}},
storage: {
init: function() {
return when.resolve();
},
getAllFlows: function() {
return when.resolve(flows);
},
getFlow: function(fn) {
if (flows[fn]) {
return when.resolve(flows[fn]);
} else if (fn.indexOf("..")!==-1) {
var err = new Error();
err.code = 'forbidden';
return when.reject(err);
} else {
return when.reject();
}
},
saveFlow: function(fn,data) {
if (fn.indexOf("..")!==-1) {
var err = new Error();
err.code = 'forbidden';
return when.reject(err);
}
flows[fn] = data;
return when.resolve();
},
getLibraryEntry: function(type,path) {
if (path.indexOf("..")!==-1) {
var err = new Error();
err.code = 'forbidden';
return when.reject(err);
}
if (libraryEntries[type] && libraryEntries[type][path]) {
return when.resolve(libraryEntries[type][path]);
} else {
return when.reject();
}
},
saveLibraryEntry: function(type,path,meta,body) {
if (path.indexOf("..")!==-1) {
var err = new Error();
err.code = 'forbidden';
return when.reject(err);
}
libraryEntries[type][path] = body;
return when.resolve();
}
},
events: {
on: function(){},
removeListener: function(){}
},
nodes: {
getNodeExampleFlows: function() {
return _examples;
}
}
});
}
describe("flows", function() {
before(function() {
app = express();
app.use(bodyParser.json());
app.get("/library/flows",library.getAll);
app.post(new RegExp("/library/flows\/(.*)"),library.post);
app.get(new RegExp("/library/flows\/(.*)"),library.get);
});
it('returns empty result', function(done) {
initLibrary({},{flows:{}});
request(app)
.get('/library/flows')
.expect(200)
.end(function(err,res) {
if (err) {
throw err;
}
res.body.should.not.have.property('f');
res.body.should.not.have.property('d');
done();
});
});
it('returns 404 for non-existent entry', function(done) {
initLibrary({},{flows:{}});
request(app)
.get('/library/flows/foo')
.expect(404)
.end(done);
});
it('can store and retrieve item', function(done) {
initLibrary({},{flows:{}});
var flow = '[]';
request(app)
.post('/library/flows/foo')
.set('Content-Type', 'application/json')
.send(flow)
.expect(204).end(function (err, res) {
if (err) {
throw err;
}
request(app)
.get('/library/flows/foo')
.expect(200)
.end(function(err,res) {
if (err) {
throw err;
}
res.text.should.equal(flow);
done();
});
});
});
it('lists a stored item', function(done) {
initLibrary({f:["bar"]});
request(app)
.get('/library/flows')
.expect(200)
.end(function(err,res) {
if (err) {
throw err;
}
res.body.should.have.property('f');
should.deepEqual(res.body.f,['bar']);
done();
});
});
it('returns 403 for malicious get attempt', function(done) {
initLibrary({});
// without the userDir override the malicious url would be
// http://127.0.0.1:1880/library/flows/../../package to
// obtain package.json from the node-red root.
request(app)
.get('/library/flows/../../../../../package')
.expect(403)
.end(done);
});
it('returns 403 for malicious post attempt', function(done) {
initLibrary({});
// without the userDir override the malicious url would be
// http://127.0.0.1:1880/library/flows/../../package to
// obtain package.json from the node-red root.
request(app)
.post('/library/flows/../../../../../package')
.expect(403)
.end(done);
});
it('includes examples flows if set', function(done) {
var examples = {"d":{"node-module":{"f":["example-one"]}}};
initLibrary({},{},examples);
request(app)
.get('/library/flows')
.expect(200)
.end(function(err,res) {
if (err) {
throw err;
}
res.body.should.have.property('d');
res.body.d.should.have.property('_examples_');
should.deepEqual(res.body.d._examples_,examples);
done();
});
});
});
describe("type", function() {
before(function() {
app = express();
app.use(bodyParser.json());
initLibrary({},{});
auth.init({settings:{}});
library.register("test");
});
it('returns empty result', function(done) {
initLibrary({},{'test':{"":[]}});
request(app)
.get('/library/test')
.expect(200)
.end(function(err,res) {
if (err) {
throw err;
}
res.body.should.not.have.property('f');
done();
});
});
it('returns 404 for non-existent entry', function(done) {
initLibrary({},{});
request(app)
.get('/library/test/foo')
.expect(404)
.end(done);
});
it('can store and retrieve item', function(done) {
initLibrary({},{'test':{}});
var flow = {text:"test content"};
request(app)
.post('/library/test/foo')
.set('Content-Type', 'application/json')
.send(flow)
.expect(204).end(function (err, res) {
if (err) {
throw err;
}
request(app)
.get('/library/test/foo')
.expect(200)
.end(function(err,res) {
if (err) {
throw err;
}
res.text.should.equal(flow.text);
done();
});
});
});
it('lists a stored item', function(done) {
initLibrary({},{'test':{'a':['abc','def']}});
request(app)
.get('/library/test/a')
.expect(200)
.end(function(err,res) {
if (err) {
throw err;
}
// This response isn't strictly accurate - but it
// verifies the api returns what storage gave it
should.deepEqual(res.body,['abc','def']);
done();
});
});
it('returns 403 for malicious access attempt', function(done) {
request(app)
.get('/library/test/../../../../../../../../../../etc/passwd')
.expect(403)
.end(done);
});
it('returns 403 for malicious access attempt', function(done) {
request(app)
.get('/library/test/..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\etc\\passwd')
.expect(403)
.end(done);
});
it('returns 403 for malicious access attempt', function(done) {
request(app)
.post('/library/test/../../../../../../../../../../etc/passwd')
.set('Content-Type', 'text/plain')
.send('root:x:0:0:root:/root:/usr/bin/tclsh')
.expect(403)
.end(done);
});
});
});

View File

@@ -0,0 +1,122 @@
/**
* Copyright JS Foundation and other contributors, http://js.foundation
*
* 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 request = require('supertest');
var express = require('express');
var sinon = require('sinon');
var locales = require("../../../../red/api/editor/locales");
describe("api/editor/locales", function() {
beforeEach(function() {
})
afterEach(function() {
})
describe('get named resource catalog',function() {
var app;
before(function() {
// bit of a mess of internal workings
locales.init({
i18n: {
i: {
lng: function() { return 'en-US'},
setLng: function(lang,callback) {
if (callback) {
callback();
}
}
},
catalog: function(namespace, lang) {
return {namespace:namespace, lang:lang};
}
}
});
app = express();
app.get(/locales\/(.+)\/?$/,locales.get);
});
it('returns with default language', function(done) {
request(app)
.get("/locales/message-catalog")
.expect(200)
.end(function(err,res) {
if (err) {
return done(err);
}
res.body.should.have.property('namespace','message-catalog');
done();
});
});
it('returns with selected language', function(done) {
request(app)
.get("/locales/message-catalog?lng=fr-FR")
.expect(200)
.end(function(err,res) {
if (err) {
return done(err);
}
res.body.should.have.property('namespace','message-catalog');
res.body.should.have.property('lang','fr-FR');
done();
});
});
});
describe('get all node resource catalogs',function() {
var app;
before(function() {
// bit of a mess of internal workings
locales.init({
i18n: {
catalog: function(namespace, lang) {
return {
"node-red": "should not return",
"test-module-a-id": "test-module-a-catalog",
"test-module-b-id": "test-module-b-catalog",
"test-module-c-id": "test-module-c-catalog"
}[namespace]
}
},
nodes: {
getNodeList: function() {
return [
{module:"node-red",id:"node-red-id"},
{module:"test-module-a",id:"test-module-a-id"},
{module:"test-module-b",id:"test-module-b-id"}
];
}
}
});
app = express();
app.get("/locales/nodes",locales.getAllNodes);
});
it('returns with the node catalogs', function(done) {
request(app)
.get("/locales/nodes")
.expect(200)
.end(function(err,res) {
if (err) {
return done(err);
}
res.body.should.eql({
'test-module-a-id': 'test-module-a-catalog',
'test-module-b-id': 'test-module-b-catalog'
});
done();
});
});
});
});

View File

@@ -0,0 +1,111 @@
/**
* Copyright JS Foundation and other contributors, http://js.foundation
*
* 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 express = require('express');
var sinon = require('sinon');
var when = require('when');
var fs = require("fs");
var app = express();
var theme = require("../../../../red/api/editor/theme");
describe("api/editor/theme", function() {
beforeEach(function() {
sinon.stub(fs,"statSync",function() { return true; });
});
afterEach(function() {
theme.init({settings:{}});
fs.statSync.restore();
});
it("applies the default theme", function() {
var result = theme.init({settings:{},version:function() { return '123.456'}});
should.not.exist(result);
var context = theme.context();
context.should.have.a.property("page");
context.page.should.have.a.property("title","Node-RED");
context.page.should.have.a.property("favicon","favicon.ico");
context.should.have.a.property("header");
context.header.should.have.a.property("title","Node-RED");
context.header.should.have.a.property("image","red/images/node-red.png");
context.should.have.a.property("version","123.456");
should.not.exist(theme.settings());
});
it("picks up custom theme", function() {
theme.init({settings:{
editorTheme: {
page: {
title: "Test Page Title",
favicon: "/absolute/path/to/theme/icon",
css: "/absolute/path/to/custom/css/file.css",
scripts: "/absolute/path/to/script.js"
},
header: {
title: "Test Header Title",
image: "/absolute/path/to/header/image" // or null to remove image
},
deployButton: {
type:"simple",
label:"Save",
icon: "/absolute/path/to/deploy/button/image" // or null to remove image
},
menu: { // Hide unwanted menu items by id. see editor/js/main.js:loadEditor for complete list
"menu-item-import-library": false,
"menu-item-export-library": false,
"menu-item-keyboard-shortcuts": false,
"menu-item-help": {
label: "Alternative Help Link Text",
url: "http://example.com"
}
},
userMenu: false, // Hide the user-menu even if adminAuth is enabled
login: {
image: "/absolute/path/to/login/page/big/image" // a 256x256 image
}
}
}});
theme.app();
var context = theme.context();
context.should.have.a.property("page");
context.page.should.have.a.property("title","Test Page Title");
context.should.have.a.property("header");
context.header.should.have.a.property("title","Test Header Title");
context.page.should.have.a.property("css");
context.page.css.should.have.lengthOf(1);
context.page.css[0].should.eql('theme/css/file.css');
context.page.should.have.a.property("scripts");
context.page.scripts.should.have.lengthOf(1);
context.page.scripts[0].should.eql('theme/scripts/script.js');
var settings = theme.settings();
settings.should.have.a.property("deployButton");
settings.should.have.a.property("userMenu");
settings.should.have.a.property("menu");
});
});

View File

@@ -0,0 +1,149 @@
/**
* Copyright JS Foundation and other contributors, http://js.foundation
*
* 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 request = require("supertest");
var express = require("express");
var fs = require("fs");
var path = require("path");
var EventEmitter = require('events').EventEmitter;
var events = new EventEmitter();
var ui = require("../../../../red/api/editor/ui");
describe("api/editor/ui", function() {
var app;
before(function() {
ui.init({
events:events,
nodes: {
getNodeIconPath: function(module,icon) {
return path.resolve(__dirname+'/../../../../public/icons/arrow-in.png');
}
}
});
});
describe("slash handler", function() {
before(function() {
app = express();
app.get("/foo",ui.ensureSlash,function(req,res) { res.sendStatus(200);});
});
it('redirects if the path does not end in a slash',function(done) {
request(app)
.get('/foo')
.expect(301,done);
});
it('redirects if the path, with query string, does not end in a slash',function(done) {
request(app)
.get('/foo?abc=def')
.expect(301)
.end(function(err,res) {
if (err) {
return done(err);
}
res.header['location'].should.equal("/foo/?abc=def");
done();
});
});
it('does not redirect if the path ends in a slash',function(done) {
request(app)
.get('/foo/')
.expect(200,done);
});
});
describe("icon handler", function() {
before(function() {
app = express();
app.get("/icons/:module/:icon",ui.icon);
});
function binaryParser(res, callback) {
res.setEncoding('binary');
res.data = '';
res.on('data', function (chunk) {
res.data += chunk;
});
res.on('end', function () {
callback(null, new Buffer(res.data, 'binary'));
});
}
function compareBuffers(b1,b2) {
b1.length.should.equal(b2.length);
for (var i=0;i<b1.length;i++) {
b1[i].should.equal(b2[i]);
}
}
it('returns the requested icon', function(done) {
var defaultIcon = fs.readFileSync(path.resolve(__dirname+'/../../../../public/icons/arrow-in.png'));
request(app)
.get("/icons/module/icon.png")
.expect("Content-Type", /image\/png/)
.expect(200)
.parse(binaryParser)
.end(function(err,res) {
if (err){
return done(err);
}
Buffer.isBuffer(res.body).should.be.true();
compareBuffers(res.body,defaultIcon);
done();
});
});
});
describe("editor ui handler", function() {
before(function() {
app = express();
app.use("/",ui.editor);
});
it('serves the editor', function(done) {
request(app)
.get("/")
.expect(200)
.end(function(err,res) {
if (err) {
return done(err);
}
// Index page should probably mention Node-RED somewhere
res.text.indexOf("Node-RED").should.not.eql(-1);
done();
});
});
});
describe("editor ui resource handler", function() {
before(function() {
app = express();
app.use("/",ui.editorResources);
});
it('serves the editor resources', function(done) {
request(app)
.get("/favicon.ico")
.expect(200)
.end(function(err,res) {
if (err) {
return done(err);
}
done();
});
});
});
});