forked from webdriverio-boneyard/wdio-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
694 lines (605 loc) · 22.5 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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
import Future from 'fibers/future'
import assign from 'object.assign'
const Fiber = require('fibers') // ToDo fix unit test to work with imports
const SYNC_COMMANDS = ['domain', '_events', '_maxListeners', 'setMaxListeners', 'emit',
'addListener', 'on', 'once', 'removeListener', 'removeAllListeners', 'listeners',
'getMaxListeners', 'listenerCount', 'getPrototype']
const STACKTRACE_FILTER = /((wdio-sync\/)*(build\/index.js|node_modules\/fibers)|- - - - -)/g
const STACKTRACE_FILTER_FN = (e) => !e.match(STACKTRACE_FILTER)
let commandIsRunning = false
let forcePromises = false
/**
* helpers
*/
const isAsync = function () {
if (!global.browser || !global.browser.options) {
return true
}
return global.browser.options.sync === false
}
const isElements = function (result) {
return (
typeof result.selector === 'string' &&
Array.isArray(result.value) && result.value.length &&
typeof result.value[0].ELEMENT !== 'undefined'
)
}
const is$$ = function (result) {
return Array.isArray(result) && !!result.length && !!result[0] && result[0].ELEMENT !== undefined
}
const sanitizeErrorMessage = function (e) {
let stack = e.stack.split(/\n/g)
let errorMsg = stack.shift()
let cwd = process.cwd()
/**
* filter out stack traces to wdio-sync and fibers
* and transform absolute path to relative
*/
stack = stack.filter(STACKTRACE_FILTER_FN)
stack = stack.map((e) => ' ' + e.replace(cwd + '/', '').trim())
/**
* error stack can be empty when test execution is aborted and
* the application is not running
*/
let errorLine = 'unknown error line'
if (stack && stack.length) {
errorLine = stack.shift().trim()
}
/**
* correct error occurence
*/
let lineToFix = stack[stack.length - 1]
if (lineToFix && lineToFix.indexOf('index.js') > -1) {
stack[stack.length - 1] = lineToFix.slice(0, lineToFix.indexOf('index.js')) + errorLine
} else {
stack.unshift(' ' + errorLine)
}
/**
* add back error message
*/
stack.unshift(errorMsg)
return stack.join('\n')
}
// filter out arguments passed to specFn & hookFn, don't allow callbacks
// as there is no need for user to call e.g. `done()`
const filterSpecArgs = function (args) {
return args.filter((arg) => typeof arg !== 'function')
}
/**
* Helper method to execute a row of hooks with certain parameters.
* It will return with a reject promise due to a design decision to not let hooks/service intefer the
* actual test process.
*
* @param {Function|Function[]} hooks list of hooks
* @param {Object[]} args list of parameter for hook functions
* @return {Promise} promise that gets resolved once all hooks finished running
*/
const executeHooksWithArgs = (hooks = [], args) => {
/**
* make sure hooks are an array of functions
*/
if (typeof hooks === 'function') {
hooks = [hooks]
}
/**
* make sure args is an array since we are calling apply
*/
if (!Array.isArray(args)) {
args = [args]
}
hooks = hooks.map((hook) => new Promise((resolve) => {
let _commandIsRunning = commandIsRunning
let result
const execHook = () => {
commandIsRunning = true
try {
result = hook.apply(null, args)
} catch (e) {
console.error(e.stack)
return resolve(e)
} finally {
commandIsRunning = _commandIsRunning
}
if (result && typeof result.then === 'function') {
return result.then(resolve, (e) => {
console.error(e.stack)
resolve(e)
})
}
resolve(result)
}
/**
* no need for fiber wrap in async mode
*/
if (isAsync()) {
return execHook()
}
/**
* after command hooks require additional Fiber environment
*/
return Fiber(execHook).run()
}))
return Promise.all(hooks)
}
/**
* global function to wrap callbacks into Fiber context
* @param {Function} fn function to wrap around
* @return {Function} wrapped around function
*/
const wdioSync = global.wdioSync = function (fn, done) {
return function (...args) {
return Fiber(() => {
const result = fn.apply(this, args)
if (typeof done === 'function') {
done(result)
}
}).run()
}
}
/**
* wraps a function into a Fiber ready context to enable sync execution and hooks
* @param {Function} fn function to be executed
* @param {String} commandName name of that function
* @param {Function[]} beforeCommand method to be executed before calling the actual function
* @param {Function[]} afterCommand method to be executed after calling the actual function
* @return {Function} actual wrapped function
*/
const wrapCommand = function (fn, commandName, beforeCommand, afterCommand) {
if (isAsync()) {
/**
* async command wrap
*/
return function (...commandArgs) {
return fn.apply(this, commandArgs)
}
}
/**
* sync command wrap
*/
return function (...commandArgs) {
let future = new Future()
let futureFailed = false
if (forcePromises) {
return fn.apply(this, commandArgs)
}
/**
* don't execute [before/after]Command hook if a command was executed
* in these hooks (otherwise we will get into an endless loop)
*/
if (commandIsRunning) {
let commandPromise = fn.apply(this, commandArgs)
/**
* if commandPromise is actually not a promise just return result
*/
if (typeof commandPromise.then !== 'function') {
return commandPromise
}
/**
* Try to execute with Fibers and fall back if can't.
* This part is executed when we want to set a fiber context within a command (e.g. in waitUntil).
*/
try {
commandPromise.then((commandResult) => {
/**
* extend protoype of result so people can call browser.element(...).click()
*/
future.return(applyPrototype.call(this, commandResult))
}, future.throw.bind(future))
return future.wait()
} catch (e) {
if (e.message === "Can't wait without a fiber") {
return commandPromise
}
throw e
}
}
/**
* commands that get executed during waitUntil and debug (repl mode) should always
* handled synchronously, therefor prevent propagating lastResults between single calls
*/
if (commandName !== 'waitUntil' && commandName !== 'debug') {
commandIsRunning = true
}
let newInstance = this
let lastCommandResult = this.lastResult
let commandResult, commandError
executeHooksWithArgs(beforeCommand, [commandName, commandArgs]).then(() => {
/**
* actual function was already executed in desired catch block
*/
if (futureFailed) {
return
}
newInstance = fn.apply(this, commandArgs)
return newInstance.then((result) => {
commandResult = result
return executeHooksWithArgs(afterCommand, [commandName, commandArgs, result])
}, (e) => {
commandError = e
return executeHooksWithArgs(afterCommand, [commandName, commandArgs, null, e])
}).then(() => {
commandIsRunning = false
if (commandError) {
return future.throw(commandError)
}
wrapCommands(newInstance, beforeCommand, afterCommand)
/**
* don't modify call result prototype
*/
if (commandName === 'call' || commandName === 'reload') {
return future.return(commandResult)
}
/**
* reset lastResult for all element calls within waitUntil/waitFor commands
*/
if (commandName.match(/^(waitUntil|waitFor)/i)) {
this.lastResult = lastCommandResult
}
return future.return(applyPrototype.call(newInstance, commandResult))
})
})
/**
* try to execute with Fibers and fall back if can't
*/
try {
return future.wait()
} catch (e) {
if (e.message === "Can't wait without a fiber") {
futureFailed = true
return fn.apply(this, commandArgs)
}
e.stack = sanitizeErrorMessage(e)
throw e
}
}
}
/**
* enhance result with instance prototype to enable command chaining
* @param {Object} result command result
* @param {Object} helperScope instance scope with prototype of already wrapped commands
* @return {Object} command result with enhanced prototype
*/
const applyPrototype = function (result, helperScope) {
/**
* don't overload result for none objects, arrays and buffer
*/
if (!result || typeof result !== 'object' || (Array.isArray(result) && !isElements(result) && !(is$$(result))) || Buffer.isBuffer(result)) {
return result
}
const mapPrototype = (el) => {
let newInstance = Object.setPrototypeOf(Object.create(el), Object.getPrototypeOf(this))
return applyPrototype.call(newInstance, el, this)
}
/**
* overload elements results
*/
if (isElements(result)) {
result.value = result.value.map((el, i) => {
el.selector = result.selector
el.value = { ELEMENT: el.ELEMENT }
el.index = i
return el
}).map(mapPrototype)
}
/**
* overload $$ result
*/
if (is$$(result)) {
return result.map(mapPrototype)
}
let prototype = {}
let hasExtendedPrototype = false
for (let commandName of Object.keys(Object.getPrototypeOf(this))) {
if (result[commandName] || SYNC_COMMANDS.indexOf(commandName) > -1) {
continue
}
this.lastResult = result
/**
* Prefer the helperScope if given which is only the case when we overload elements result.
* We can't use the `this` prototype because its methods are not wrapped and command results
* wouldn't be fiberised
*/
prototype[commandName] = { value: (helperScope || this)[commandName].bind(this) }
hasExtendedPrototype = true
}
if (hasExtendedPrototype) {
let newResult = Object.create(result, prototype)
/**
* since status is a command we need to rename the property
*/
if (typeof result.status !== 'undefined') {
result._status = result.status
delete result.status
}
result = assign(newResult, result)
}
return result
}
/**
* wraps all WebdriverIO commands
* @param {Object} instance WebdriverIO client instance (browser)
* @param {Function[]} beforeCommand before command hook
* @param {Function[]} afterCommand after command hook
*/
const wrapCommands = function (instance, beforeCommand, afterCommand) {
const addCommand = instance.addCommand
/**
* if instance is a multibrowser instance make sure to wrap commands
* of its instances too
*/
if (instance.isMultiremote) {
instance.getInstances().forEach((browserName) => {
wrapCommands(global[browserName], beforeCommand, afterCommand)
})
}
Object.keys(Object.getPrototypeOf(instance)).forEach((commandName) => {
if (SYNC_COMMANDS.indexOf(commandName) > -1) {
return
}
let origFn = instance[commandName]
instance[commandName] = wrapCommand.call(instance, origFn, commandName, beforeCommand, afterCommand)
})
/**
* no need to overwrite addCommand in async mode
*/
if (isAsync()) {
return
}
/**
* Adding a command within fiber context doesn't require a special routine
* since everything runs sync. There is no need to promisify the command.
*/
instance.addCommand = function (fnName, fn, forceOverwrite) {
let commandGroup = instance.getPrototype()
let commandName = fnName
let namespace
if (typeof fn === 'string') {
namespace = arguments[0]
fnName = arguments[1]
fn = arguments[2]
forceOverwrite = arguments[3]
switch (typeof commandGroup[namespace]) {
case 'function':
throw new Error(`Command namespace "${namespace}" is used internally, and can't be overwritten!`)
case 'undefined':
commandGroup[namespace] = {}
break
}
commandName = `${namespace}.${fnName}`
commandGroup = commandGroup[namespace]
}
if (commandGroup[fnName] && !forceOverwrite) {
throw new Error(`Command ${fnName} is already defined!`)
}
/**
* If method name is async the user specifies that he wants to use bare promises to handle asynchronicity.
* First use native addCommand in order to be able to chain with other native commands, then wrap new
* command again to run it synchronous in the test method.
* This will allow us to run async custom commands within sync custom commands in a sync way.
*/
if (fn.name === 'async') {
addCommand(fnName, function (...args) {
const state = forcePromises
forcePromises = true
let res = fn.apply(instance, args)
forcePromises = state
return res
}, forceOverwrite)
commandGroup[fnName] = wrapCommand.call(commandGroup, commandGroup[fnName], fnName, beforeCommand, afterCommand)
return
}
/**
* for all other cases we internally return a promise that is
* finished once the Fiber wrapped custom function has finished
* #functionalProgrammingWTF!
*/
commandGroup[fnName] = function (...args) {
return new Promise((resolve) => {
const state = forcePromises
forcePromises = false
wdioSync(fn, resolve).apply(this, args)
forcePromises = state
})
}
instance[fnName] = wrapCommand.call(commandGroup, commandGroup[fnName], commandName, beforeCommand, afterCommand)
}
}
/**
* execute test or hook synchronously
* @param {Function} fn spec or hook method
* @param {Number} repeatTest number of retries
* @return {Promise} that gets resolved once test/hook is done or was retried enough
*/
const executeSync = function (fn, repeatTest = 0, args = []) {
/**
* if a new hook gets executed we can assume that all commands should have finised
* with exception of timeouts where `commandIsRunning` will never be reset but here
*/
commandIsRunning = false
return new Promise((resolve, reject) => {
try {
const res = fn.apply(this, args)
resolve(res)
} catch (e) {
if (repeatTest) {
return resolve(executeSync(fn, --repeatTest, args))
}
/**
* no need to modify stack if no stack available
*/
if (!e.stack) {
return reject(e)
}
e.stack = e.stack.split('\n').filter(STACKTRACE_FILTER_FN).join('\n')
reject(e)
}
})
}
/**
* execute test or hook asynchronously
* @param {Function} fn spec or hook method
* @param {Number} repeatTest number of retries
* @return {Promise} that gets resolved once test/hook is done or was retried enough
*/
const executeAsync = function (fn, repeatTest = 0, args = []) {
let result, error
/**
* if a new hook gets executed we can assume that all commands should have finised
* with exception of timeouts where `commandIsRunning` will never be reset but here
*/
commandIsRunning = false
try {
result = fn.apply(this, args)
} catch (e) {
error = e
}
/**
* handle errors that get thrown directly and are not cause by
* rejected promises
*/
if (error) {
if (repeatTest) {
return executeAsync(fn, --repeatTest, args)
}
return new Promise((resolve, reject) => reject(error))
}
/**
* if we don't retry just return result
*/
if (repeatTest === 0 || !result || typeof result.catch !== 'function') {
return new Promise(resolve => resolve(result))
}
/**
* handle promise response
*/
return result.catch((e) => {
if (repeatTest) {
return executeAsync(fn, --repeatTest, args)
}
e.stack = e.stack.split('\n').filter(STACKTRACE_FILTER_FN).join('\n')
return Promise.reject(e)
})
}
/**
* runs a hook within fibers context (if function name is not async)
* it also executes before/after hook hook
*
* @param {Function} hookFn function that was passed to the framework hook
* @param {Function} origFn original framework hook function
* @param {Function} before before hook hook
* @param {Function} after after hook hook
* @param {Number} repeatTest number of retries if hook fails
* @return {Function} wrapped framework hook function
*/
const runHook = function (hookFn, origFn, before, after, repeatTest = 0) {
const hookError = (hookName) => (e) => console.error(`Error in ${hookName}: ${e.stack}`)
return origFn(function (...hookArgs) {
// Print errors encountered in beforeHook and afterHook to console, but
// don't propagate them to avoid failing the test. However, errors in
// framework hook functions should fail the test, so propagate those.
return executeHooksWithArgs(before).catch(hookError('beforeHook')).then(() => {
/**
* user wants handle async command using promises, no need to wrap in fiber context
*/
if (isAsync() || hookFn.name === 'async') {
return executeAsync.call(this, hookFn, repeatTest, filterSpecArgs(hookArgs))
}
return new Promise(runSync.call(this, hookFn, repeatTest, filterSpecArgs(hookArgs)))
}).then(() => {
return executeHooksWithArgs(after).catch(hookError('afterHook'))
})
})
}
/**
* runs a spec function (test function) within the fibers context
* @param {string} specTitle test description
* @param {Function} specFn test function that got passed in from the user
* @param {Function} origFn original framework test function
* @param {Number} repeatTest number of retries if test fails
* @return {Function} wrapped test function
*/
const runSpec = function (specTitle, specFn, origFn, repeatTest = 0) {
/**
* user wants handle async command using promises, no need to wrap in fiber context
*/
if (isAsync() || specFn.name === 'async') {
return origFn(specTitle, function async (...specArgs) {
return executeAsync.call(this, specFn, repeatTest, filterSpecArgs(specArgs))
})
}
return origFn(specTitle, function (...specArgs) {
return new Promise(runSync.call(this, specFn, repeatTest, filterSpecArgs(specArgs)))
})
}
/**
* run hook or spec via executeSync
*/
function runSync (fn, repeatTest = 0, args = []) {
return (resolve, reject) =>
Fiber(() => executeSync.call(this, fn, repeatTest, args).then(() => resolve(), reject)).run()
}
/**
* wraps hooks and test function of a framework within a fiber context
* @param {Function} origFn original framework function
* @param {string[]} testInterfaceFnNames actual test functions for that framework
* @return {Function} wrapped test/hook function
*/
const wrapTestFunction = function (fnName, origFn, testInterfaceFnNames, before, after) {
return function (...specArguments) {
/**
* Variadic arguments:
* [title, fn], [title], [fn]
* [title, fn, retryCnt], [title, retryCnt], [fn, retryCnt]
*/
let retryCnt = typeof specArguments[specArguments.length - 1] === 'number' ? specArguments.pop() : 0
const specFn = typeof specArguments[0] === 'function' ? specArguments.shift()
: (typeof specArguments[1] === 'function' ? specArguments.pop() : undefined)
const specTitle = specArguments[0]
if (testInterfaceFnNames.indexOf(fnName) > -1) {
if (specFn) return runSpec(specTitle, specFn, origFn, retryCnt)
/**
* if specFn is undefined we are dealing with a pending function
*/
return origFn(specTitle)
}
return runHook(specFn, origFn, before, after, retryCnt)
}
}
/**
* Wraps global test function like `it` so that commands can run synchronouse
*
* The scope parameter is used in the qunit framework since all functions are bound to global.QUnit instead of global
*
* @param {String[]} testInterfaceFnNames command that runs specs
* @param {Function} before before hook hook
* @param {Function} after after hook hook
* @param {String} fnName test interface command to wrap
* @param {Object} scope the scope to run command from, defaults to global
*/
const runInFiberContext = function (testInterfaceFnNames, before, after, fnName, scope = global) {
const origFn = scope[fnName]
scope[fnName] = wrapTestFunction(fnName, origFn, testInterfaceFnNames, before, after)
/**
* support it.skip for the Mocha framework
*/
if (typeof origFn.skip === 'function') {
scope[fnName].skip = origFn.skip
}
/**
* wrap it.only for the Mocha framework
*/
if (typeof origFn.only === 'function') {
const origOnlyFn = origFn.only
scope[fnName].only = wrapTestFunction(fnName + '.only', origOnlyFn, testInterfaceFnNames, before, after)
}
}
export {
wrapCommand,
wrapCommands,
runInFiberContext,
executeHooksWithArgs,
executeSync,
executeAsync,
wdioSync,
is$$
}