-
Notifications
You must be signed in to change notification settings - Fork 42
/
index.js
466 lines (418 loc) · 16.4 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
/**
* 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.
**/
'use strict';
const path = require("path");
const process = require("process")
const sinon = require("sinon");
const should = require('should');
const fs = require('fs');
require('should-sinon');
const request = require('supertest');
var bodyParser = require("body-parser");
const express = require("express");
const http = require('http');
const stoppable = require('stoppable');
const semver = require('semver');
const EventEmitter = require('events').EventEmitter;
const PROXY_METHODS = ['log', 'status', 'warn', 'error', 'debug', 'trace', 'send'];
// Find the nearest package.json
function findPackageJson(dir) {
dir = path.resolve(dir || process.cwd())
const { root } = path.parse(dir)
if (dir === root) {
return null
}
const packagePath = path.join(dir, 'package.json')
if (fs.existsSync(packagePath)) {
return {
path: packagePath,
packageJson: JSON.parse(fs.readFileSync(packagePath, 'utf-8'))
}
} else {
return findPackageJson(path.resolve(path.join(dir, '..')))
}
}
/**
* Finds the NR runtime path by inspecting environment
*/
function findRuntimePath() {
const upPkg = findPackageJson()
// case 1: we're in NR itself
if (upPkg.packageJson.name === 'node-red') {
if (checkSemver(upPkg.packageJson.version,"<0.20.0")) {
return path.join(path.dirname(upPkg.path), upPkg.packageJson.main);
} else {
return path.join(path.dirname(upPkg.path),"packages","node_modules","node-red");
}
}
// case 2: NR is resolvable from here
try {
return require.resolve('node-red');
} catch (ignored) {}
// case 3: NR is installed alongside node-red-node-test-helper
if ((upPkg.packageJson.dependencies && upPkg.packageJson.dependencies['node-red']) ||
(upPkg.packageJson.devDependencies && upPkg.packageJson.devDependencies['node-red'])) {
const dirpath = path.join(path.dirname(upPkg.path), 'node_modules', 'node-red');
try {
const pkg = require(path.join(dirpath, 'package.json'));
return path.join(dirpath, pkg.main);
} catch (ignored) {}
}
// case 4: NR & NRNTH are git repos sat alongside each other
try {
const nrpkg = require("../node-red/package.json");
return "../node-red/packages/node_modules/node-red"
} catch(ignored) {}
}
// As we have prerelease tags in development version, they need stripping off
// before semver will do a sensible comparison with a range.
function checkSemver(localVersion,testRange) {
var parts = localVersion.split("-");
return semver.satisfies(parts[0],testRange);
}
class NodeTestHelper extends EventEmitter {
constructor() {
super();
this._sandbox = sinon.createSandbox();
this._address = '127.0.0.1';
this._listenPort = 0; // ephemeral
this.init();
}
_initRuntime(requirePath) {
try {
const RED = this._RED = require(requirePath);
// public runtime API
this._log = RED.log;
// access internal Node-RED runtime methods
let prefix = path.dirname(requirePath);
if (checkSemver(RED.version(),"<0.20.0")) {
this._settings = RED.settings;
this._events = RED.events;
this._redNodes = RED.nodes;
this._context = require(path.join(prefix, 'runtime', 'nodes', 'context'));
this._comms = require(path.join(prefix, 'api', 'editor', 'comms'));
this.credentials = require(path.join(prefix, 'runtime', 'nodes', 'credentials'));
// proxy the methods on Node.prototype to both be Sinon spies and asynchronously emit
// information about the latest call
this._NodePrototype = require(path.join(prefix, 'runtime', 'nodes', 'Node')).prototype;
} else {
if (!fs.existsSync(path.join(prefix, '@node-red/runtime/lib/nodes'))) {
// Not in the NR source tree, need to go hunting for the modules....
if (fs.existsSync(path.join(prefix,'..','node_modules','@node-red/runtime/lib/nodes'))) {
// path/to/node_modules/node-red/lib
// path/to/node_modules/node-red/node_modules/@node-red
prefix = path.resolve(path.join(prefix,"..","node_modules"));
} else if (fs.existsSync(path.join(prefix,'..','..','@node-red/runtime/lib/nodes'))) {
// path/to/node_modules/node-red/lib
// path/to/node_modules/@node-red
prefix = path.resolve(path.join(prefix,"..",".."));
} else {
throw new Error("Cannot find the NR source tree. Path: '"+prefix+"'. Please raise an issue against node-red/node-red-node-test-helper with full details.");
}
}
this._redNodes = require(path.join(prefix, '@node-red/runtime/lib/nodes'));
this._context = require(path.join(prefix, '@node-red/runtime/lib/nodes/context'));
this._comms = require(path.join(prefix, '@node-red/editor-api/lib/editor/comms'));
this._registryUtil = require(path.join(prefix, '@node-red/registry/lib/util'));
this.credentials = require(path.join(prefix, '@node-red/runtime/lib/nodes/credentials'));
// proxy the methods on Node.prototype to both be Sinon spies and asynchronously emit
// information about the latest call
this._NodePrototype = require(path.join(prefix, '@node-red/runtime/lib/nodes/Node')).prototype;
this._settings = RED.settings;
this._events = RED.runtime.events;
this._nodeModules = {
'catch': require(path.join(prefix, '@node-red/nodes/core/common/25-catch.js')),
'status': require(path.join(prefix, '@node-red/nodes/core/common/25-status.js')),
'complete': require(path.join(prefix, '@node-red/nodes/core/common/24-complete.js'))
}
}
} catch (ignored) {
console.log(ignored);
// ignore, assume init will be called again by a test script supplying the runtime path
}
}
init(runtimePath, userSettings) {
runtimePath = runtimePath || findRuntimePath();
if (runtimePath) {
this._initRuntime(runtimePath);
if (userSettings) {
this.settings(userSettings);
}
}
}
/**
* Merges any userSettings with the defaults returned by `RED.settings`. Each
* invocation of this method will overwrite the previous userSettings to prevent
* unexpected problems in your tests.
*
* This will enable you to replicate your production environment within your tests,
* for example where you're using the `functionGlobalContext` to enable extra node
* modules within your functions.
* @example
* helper.settings({ functionGlobalContext: { os:require('os') } });
* @param {Object} userSettings - an object containing the runtime settings
* @return {Object} custom userSettings merged with default RED.settings
*/
settings(userSettings) {
if (userSettings) {
// to prevent unexpected problems, always merge with the default RED.settings
this._settings = Object.assign({}, this._RED.settings, userSettings);
}
return this._settings;
}
async load(testNode, testFlow, testCredentials, cb) {
const log = this._log;
const logSpy = this._logSpy = this._sandbox.spy(log, 'log');
logSpy.FATAL = log.FATAL;
logSpy.ERROR = log.ERROR;
logSpy.WARN = log.WARN;
logSpy.INFO = log.INFO;
logSpy.DEBUG = log.DEBUG;
logSpy.TRACE = log.TRACE;
logSpy.METRIC = log.METRIC;
const self = this;
PROXY_METHODS.forEach(methodName => {
const spy = this._sandbox.spy(self._NodePrototype, methodName);
self._NodePrototype[methodName] = new Proxy(spy, {
apply: (target, thisArg, args) => {
const retval = Reflect.apply(target, thisArg, args);
process.nextTick(function(call) { return () => {
self._NodePrototype.emit.call(thisArg, `call:${methodName}`, call);
}}(spy.lastCall));
return retval;
}
});
});
if (typeof testCredentials === 'function') {
cb = testCredentials;
testCredentials = {};
}
const conf = {flows:testFlow,credentials:testCredentials|| {}}
const storage = {
conf: conf,
getFlows: function () {
return Promise.resolve(conf);
},
saveFlows: function(conf) {
storage.conf = conf;
return Promise.resolve();
}
};
// mock out the runtime plugins api
const plugins = {
registerPlugin () {
return;
},
getPlugin () {
return;
},
getPluginsByType () {
return [];
}
}
// this._settings.logging = {console:{level:'off'}};
this._settings.available = function() { return false; }
const redNodes = this._redNodes;
this._httpAdmin = express();
this._httpAdmin.use(bodyParser.json({limit:'5mb'}));
this._httpAdmin.use(bodyParser.urlencoded({limit:'5mb',extended:true}));
const mockRuntime = {
nodes: redNodes,
events: this._events,
util: this._RED.util,
settings: this._settings,
storage: storage,
plugins: plugins,
log: this._log,
nodeApp: express(),
adminApp: this._httpAdmin,
library: {register: function() {}},
get server() { return self._server }
}
redNodes.init(mockRuntime);
redNodes.registerType("helper", function (n) {
redNodes.createNode(this, n);
});
var red;
if (this._registryUtil) {
this._registryUtil.init(mockRuntime);
red = this._registryUtil.createNodeApi({});
red._ = v=>v;
red.settings = this._settings;
} else {
red = {
_: v => v
};
Object.keys(this._RED).filter(prop => !/^(init|start|stop)$/.test(prop))
.forEach(prop => {
const propDescriptor = Object.getOwnPropertyDescriptor(this._RED, prop);
Object.defineProperty(red, prop, propDescriptor);
});
}
const initPromises = []
let preloadedCoreModules = new Set();
testFlow.forEach(n => {
if (this._nodeModules.hasOwnProperty(n.type)) {
// Go find the 'real' core node module and load it...
const result = this._nodeModules[n.type](red);
if (result?.then) {
initPromises.push(result)
}
preloadedCoreModules.add(this._nodeModules[n.type]);
}
})
if (!Array.isArray(testNode)) {
testNode = [testNode];
}
testNode.forEach(fn => {
if (!preloadedCoreModules.has(fn)) {
const result = fn(red);
if (result?.then) {
initPromises.push(result)
}
}
});
try {
await Promise.all(initPromises);
await redNodes.loadFlows();
await redNodes.startFlows();
should.deepEqual(testFlow, redNodes.getFlows().flows);
if (cb) cb();
} catch (error) {
if (cb) cb(error);
else throw error;
}
}
unload() {
// TODO: any other state to remove between tests?
this._redNodes.clearRegistry();
this._logSpy && this._logSpy.restore();
this._sandbox.restore();
// internal API
this._context.clean({allNodes:[]});
return this._redNodes.stopFlows()
}
/**
* Returns a Node by id.
* @param {string} id - Node ID
* @returns {Node}
*/
getNode(id) {
return this._redNodes.getNode(id);
}
clearFlows() {
return this._redNodes.stopFlows();
}
/**
* Update flows
* @param {object|object[]} testFlow Flow data to test a node
* @param {"full"|"flows"|"nodes"} type The type of deploy mode "full", "flows" or "nodes" (defaults to "full")
* @param {object} [testCredentials] Optional node credentials
* @param {function} [cb] Optional callback (not required when called with await)
* @returns {Promise}
*/
async setFlows(testFlow, type, testCredentials, cb) {
const helper = this;
if (typeof testCredentials === 'string' ) {
cb = testCredentials;
testCredentials = {};
}
if(!type || typeof type != "string") {
type = "full"
}
async function waitStarted() {
return new Promise((resolve, reject) => {
let timeover = setTimeout(() => {
if (timeover) {
timeover = null
reject(Error("timeout waiting event"))
}
}, 300);
function hander() {
clearTimeout(timeover)
helper._events.off('flows:started', hander)
if (timeover) {
timeover = null
resolve()
}
}
helper._events.on('flows:started', hander); // call resolve when its done
});
}
try {
await this._redNodes.setFlows(testFlow, testCredentials || {}, type);
await waitStarted();
if (cb) cb();
} catch (error) {
if (cb) cb(error);
else throw error;
}
}
request() {
return request(this._httpAdmin);
}
async startServer(cb) {
try {
await new Promise((resolve, reject) => {
this._app = express();
const server = stoppable(
http.createServer((req, res) => this._app(req, res)),
0
);
this._RED.init(server, {
logging: { console: { level: 'off' } },
});
server.listen(this._listenPort, this._address);
server.on('listening', () => {
this._port = server.address().port;
this._comms.start();
this._server = server;
resolve();
});
server.on('error', reject);
});
if (cb) cb();
} catch (error) {
if (cb) cb(error);
else throw error;
}
}
async stopServer(cb) {
try {
if (this._server) {
await new Promise((resolve, reject) => {
this._comms.stop();
this._server.stop((error) => {
if (error) reject(error);
else resolve();
});
});
}
if (cb) cb();
} catch (error) {
if (cb) cb(error);
else throw error;
}
}
url() {
return `http://${this._address}:${this._port}`;
}
log() {
return this._logSpy;
}
}
module.exports = new NodeTestHelper();
module.exports.NodeTestHelper = NodeTestHelper;