forked from codeceptjs/CodeceptJS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontainer.js
428 lines (390 loc) · 11.6 KB
/
container.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
const glob = require('glob');
const path = require('path');
const { MetaStep } = require('./step');
const { fileExists, isFunction, isAsyncFunction } = require('./utils');
const Translation = require('./translation');
const MochaFactory = require('./mochaFactory');
const recorder = require('./recorder');
const event = require('./event');
const WorkerStorage = require('./workerStorage');
let container = {
helpers: {},
support: {},
plugins: {},
/**
* @type {Mocha | {}}
* @ignore
*/
mocha: {},
translation: {},
};
/**
* Dependency Injection Container
*/
class Container {
/**
* Create container with all required helpers and support objects
*
* @api
* @param {*} config
* @param {*} opts
*/
static create(config, opts) {
const mochaConfig = config.mocha || {};
if (config.grep && !opts.grep) {
mochaConfig.grep = config.grep;
}
this.createMocha = () => {
container.mocha = MochaFactory.create(mochaConfig, opts || {});
};
this.createMocha();
container.helpers = createHelpers(config.helpers || {});
container.translation = loadTranslation(config.translation || null);
container.support = createSupportObjects(config.include || {});
container.plugins = createPlugins(config.plugins || {}, opts);
if (config.gherkin) loadGherkinSteps(config.gherkin.steps || []);
}
/**
* Get all plugins
*
* @api
* @param {string} [name]
* @returns { * }
*/
static plugins(name) {
if (!name) {
return container.plugins;
}
return container.plugins[name];
}
/**
* Get all support objects or get support object by name
*
* @api
* @param {string} [name]
* @returns { * }
*/
static support(name) {
if (!name) {
return container.support;
}
return container.support[name];
}
/**
* Get all helpers or get a helper by name
*
* @api
* @param {string} [name]
* @returns { * }
*/
static helpers(name) {
if (!name) {
return container.helpers;
}
return container.helpers[name];
}
/**
* Get translation
*
* @api
*/
static translation() {
return container.translation;
}
/**
* Get Mocha instance
*
* @api
* @returns { * }
*/
static mocha() {
return container.mocha;
}
/**
* Append new services to container
*
* @api
* @param {Object<string, *>} newContainer
*/
static append(newContainer) {
const deepMerge = require('./utils').deepMerge;
container = deepMerge(container, newContainer);
}
/**
* Clear container
*
* @param {Object<string, *>} newHelpers
* @param {Object<string, *>} newSupport
* @param {Object<string, *>} newPlugins
*/
static clear(newHelpers, newSupport, newPlugins) {
container.helpers = newHelpers || {};
container.support = newSupport || {};
container.plugins = newPlugins || {};
container.translation = loadTranslation();
}
/**
* Share data across worker threads
*
* @param {Object} data
* @param {Object} options - set {local: true} to not share among workers
*/
static share(data, options = {}) {
Container.append({ support: data });
if (!options.local) {
WorkerStorage.share(data);
}
}
}
module.exports = Container;
function createHelpers(config) {
const helpers = {};
let moduleName;
for (const helperName in config) {
try {
if (config[helperName].require) {
if (config[helperName].require.startsWith('.')) {
moduleName = path.resolve(global.codecept_dir, config[helperName].require); // custom helper
} else {
moduleName = config[helperName].require; // plugin helper
}
} else {
moduleName = `./helper/${helperName}`; // built-in helper
}
const HelperClass = require(moduleName);
if (HelperClass._checkRequirements) {
const requirements = HelperClass._checkRequirements();
if (requirements) {
let install;
if (require('./utils').installedLocally()) {
install = `npm install --save-dev ${requirements.join(' ')}`;
} else {
console.log('WARNING: CodeceptJS is not installed locally. It is recommended to switch to local installation');
install = `[sudo] npm install -g ${requirements.join(' ')}`;
}
throw new Error(`Required modules are not installed.\n\nRUN: ${install}`);
}
}
helpers[helperName] = new HelperClass(config[helperName]);
} catch (err) {
throw new Error(`Could not load helper ${helperName} from module '${moduleName}':\n${err.message}\n${err.stack}`);
}
}
for (const name in helpers) {
if (helpers[name]._init) helpers[name]._init();
}
return helpers;
}
function createSupportObjects(config) {
const objects = {};
for (const name in config) {
objects[name] = {}; // placeholders
}
if (!config.I) {
objects.I = require('./actor')();
if (container.translation.I !== 'I') {
objects[container.translation.I] = objects.I;
}
}
container.support = objects;
function lazyLoad(name) {
let newObj = getSupportObject(config, name);
try {
if (typeof newObj === 'function') {
newObj = newObj();
} else if (newObj._init) {
newObj._init();
}
} catch (err) {
throw new Error(`Initialization failed for ${name}: ${newObj}\n${err.message}`);
}
return newObj;
}
const asyncWrapper = function (f) {
return function () {
return f.apply(this, arguments).catch((e) => {
recorder.saveFirstAsyncError(e);
throw e;
});
};
};
Object.keys(objects).forEach((object) => {
const currentObject = objects[object];
Object.keys(currentObject).forEach((method) => {
const currentMethod = currentObject[method];
if (currentMethod[Symbol.toStringTag] === 'AsyncFunction') {
objects[object][method] = asyncWrapper(currentMethod);
}
});
});
return new Proxy({}, {
has(target, key) {
return key in config;
},
ownKeys() {
return Reflect.ownKeys(config);
},
get(target, key) {
// configured but not in support object, yet: load the module
if (key in objects && !(key in target)) {
// load default I
if (key in objects && !(key in config)) {
return target[key] = objects[key];
}
// load new object
const object = lazyLoad(key);
// check that object is a real object and not an array
if (Object.prototype.toString.call(object) === '[object Object]') {
return target[key] = Object.assign(objects[key], object);
}
target[key] = object;
}
return target[key];
},
});
}
function createPlugins(config, options = {}) {
const plugins = {};
const enabledPluginsByOptions = (options.plugins || '').split(',');
for (const pluginName in config) {
if (!config[pluginName]) config[pluginName] = {};
if (!config[pluginName].enabled && (enabledPluginsByOptions.indexOf(pluginName) < 0)) {
continue; // plugin is disabled
}
let module;
try {
if (config[pluginName].require) {
module = config[pluginName].require;
if (module.startsWith('.')) { // local
module = path.resolve(global.codecept_dir, module); // custom plugin
}
} else {
module = `./plugin/${pluginName}`;
}
plugins[pluginName] = require(module)(config[pluginName]);
} catch (err) {
throw new Error(`Could not load plugin ${pluginName} from module '${module}':\n${err.message}`);
}
}
return plugins;
}
function getSupportObject(config, name) {
const module = config[name];
if (typeof module === 'string') {
return loadSupportObject(module, name);
}
return module;
}
function loadGherkinSteps(paths) {
global.Before = fn => event.dispatcher.on(event.test.started, fn);
global.After = fn => event.dispatcher.on(event.test.finished, fn);
global.Fail = fn => event.dispatcher.on(event.test.failed, fn);
// If gherkin.steps is string, then this will iterate through that folder and send all step def js files to loadSupportObject
// If gherkin.steps is Array, it will go the old way
// This is done so that we need not enter all Step Definition files under config.gherkin.steps
if (Array.isArray(paths)) {
for (const path of paths) {
loadSupportObject(path, `Step Definition from ${path}`);
}
} else {
const folderPath = paths.startsWith('.') ? path.join(global.codecept_dir, paths) : '';
if (folderPath !== '') {
glob.sync(folderPath).forEach((file) => {
loadSupportObject(file, `Step Definition from ${file}`);
});
}
}
delete global.Before;
delete global.After;
delete global.Fail;
}
function loadSupportObject(modulePath, supportObjectName) {
if (modulePath.charAt(0) === '.') {
modulePath = path.join(global.codecept_dir, modulePath);
}
try {
const obj = require(modulePath);
if (typeof obj === 'function') {
const fobj = obj();
if (fobj.constructor.name === 'Actor') {
const methods = getObjectMethods(fobj);
Object.keys(methods)
.forEach(key => {
fobj[key] = methods[key];
});
return methods;
}
}
if (typeof obj !== 'function'
&& Object.getPrototypeOf(obj) !== Object.prototype
&& !Array.isArray(obj)
) {
const methods = getObjectMethods(obj);
Object.keys(methods)
.filter(key => !key.startsWith('_'))
.forEach(key => {
const currentMethod = methods[key];
if (isFunction(currentMethod) || isAsyncFunction(currentMethod)) {
const ms = new MetaStep(supportObjectName, key);
ms.setContext(methods);
methods[key] = ms.run.bind(ms, currentMethod);
}
});
return methods;
}
if (!Array.isArray(obj)) {
Object.keys(obj)
.filter(key => !key.startsWith('_'))
.forEach(key => {
const currentMethod = obj[key];
if (isFunction(currentMethod) || isAsyncFunction(currentMethod)) {
const ms = new MetaStep(supportObjectName, key);
ms.setContext(obj);
obj[key] = ms.run.bind(ms, currentMethod);
}
});
}
return obj;
} catch (err) {
throw new Error(`Could not include object ${supportObjectName} from module '${modulePath}'\n${err.message}`);
}
}
/**
* Method collect own property and prototype
*/
function getObjectMethods(obj) {
const methodsSet = new Set();
let protoObj = Reflect.getPrototypeOf(obj);
do {
if (protoObj.constructor.prototype !== Object.prototype) {
const keys = Reflect.ownKeys(protoObj);
keys.forEach(k => methodsSet.add(k));
}
} while (protoObj = Reflect.getPrototypeOf(protoObj));
Reflect.ownKeys(obj).forEach(k => methodsSet.add(k));
const methods = {};
for (const key of methodsSet.keys()) {
if (key !== 'constructor') methods[key] = obj[key];
}
return methods;
}
function loadTranslation(translation) {
if (!translation) {
return new Translation({
I: 'I',
actions: {},
}, false);
}
let vocabulary;
// check if it is a known translation
if (require('../translations')[translation]) {
vocabulary = require('../translations')[translation];
return new Translation(vocabulary);
} if (fileExists(path.join(global.codecept_dir, translation))) {
// get from a provided file instead
vocabulary = require(path.join(global.codecept_dir, translation));
} else {
throw new Error(`Translation option is set in config, but ${translation} is not a translated locale or filename`);
}
return new Translation(vocabulary);
}