forked from codeceptjs/CodeceptJS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecorder.js
262 lines (227 loc) · 5.33 KB
/
recorder.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
const promiseRetry = require('promise-retry');
const log = require('./output').log;
const debug = require('debug')('codeceptjs');
let promise;
let running = false;
let errFn;
let queueId = 0;
let sessionId = null;
let asyncErr = null;
let tasks = [];
let oldPromises = [];
const defaultRetryOptions = {
retries: 0,
minTimeout: 150,
maxTimeout: 10000,
};
/**
* Singleton object to record all test steps as promises and run them in chain.
*/
module.exports = {
/**
* @var retries Array[object]
*/
retries: [],
/**
* Start recording promises
*
* @api
*/
start() {
running = true;
asyncErr = null;
errFn = null;
this.reset();
},
isRunning() {
return running;
},
startUnlessRunning() {
if (!this.isRunning()) {
this.start();
}
},
/**
* Add error handler to catch rejected promises
*
* @api
* @param {*} fn
*/
errHandler(fn) {
errFn = fn;
},
/**
* Stops current promise chain, calls `catch`.
* Resets recorder to initial state.
*
* @api
*/
reset() {
if (promise && running) this.catch();
queueId++;
sessionId = null;
asyncErr = null;
log(`${currentQueue()}Starting recording promises`);
promise = Promise.resolve();
oldPromises = [];
tasks = [];
this.session.running = false;
this.retries = [];
},
session: {
running: false,
start(name) {
log(`${currentQueue()}Starting <${name}> session`);
tasks.push('--->');
oldPromises.push(promise);
this.running = true;
sessionId = name;
promise = Promise.resolve();
},
restore(name) {
tasks.push('<---');
log(`${currentQueue()}Finalize <${name}> session`);
this.running = false;
sessionId = null;
this.catch(errFn);
promise = promise.then(() => oldPromises.pop());
},
catch(fn) {
promise = promise.catch(fn);
},
},
/**
* Adds a promise to a chain.
* Promise description should be passed as first parameter.
*
* @param {*} taskName
* @param {*} fn
* @param {*} force
* @param {boolean} retry -
* true: it will retries if `retryOpts` set.
* false: ignore `retryOpts` and won't retry.
*/
add(taskName, fn = undefined, force = false, retry = true) {
if (typeof taskName === 'function') {
fn = taskName;
taskName = fn.toString();
}
if (!running && !force) {
return;
}
tasks.push(taskName);
debug(`${currentQueue()}Queued | ${taskName}`);
return promise = Promise.resolve(promise).then((res) => {
const retryOpts = this.retries.slice(-1).pop();
// no retries or unnamed tasks
if (!retryOpts || !taskName || !retry) {
return Promise.resolve(res).then(fn);
}
return promiseRetry(Object.assign(defaultRetryOptions, retryOpts), (retry, number) => {
if (number > 1) log(`${currentQueue()}Retrying... Attempt #${number}`);
const retryRules = this.retries.reverse();
return Promise.resolve(res).then(fn).catch((err) => {
for (const retryObj of retryRules) {
if (!retryObj.when) return retry(err);
if (retryObj.when && retryObj.when(err)) return retry(err);
}
throw err;
});
});
});
},
retry(opts) {
if (!promise) return;
if (opts === null) {
opts = {};
}
if (Number.isInteger(opts)) {
opts = { retries: opts };
}
return this.add(() => this.retries.push(opts));
},
catch(customErrFn) {
return promise = promise.catch((err) => {
log(`${currentQueue()}Error | ${err}`);
if (!(err instanceof Error)) { // strange things may happen
err = new Error(`[Wrapped Error] ${JSON.stringify(err)}`); // we should be prepared for them
}
if (customErrFn) {
customErrFn(err);
} else if (errFn) {
errFn(err);
}
this.stop();
});
},
catchWithoutStop(customErrFn) {
return promise = promise.catch((err) => {
log(`${currentQueue()}Error | ${err}`);
if (!(err instanceof Error)) { // strange things may happen
err = new Error(`[Wrapped Error] ${JSON.stringify(err)}`); // we should be prepared for them
}
if (customErrFn) {
customErrFn(err);
} else if (errFn) {
errFn(err);
}
});
},
/**
* Adds a promise which throws an error into a chain
*
* @api
* @param {*} err
*/
throw(err) {
return this.add(`throw error ${err}`, () => {
throw err;
});
},
saveFirstAsyncError(err) {
if (asyncErr === null) {
asyncErr = err;
}
},
getAsyncErr() {
return asyncErr;
},
cleanAsyncErr() {
asyncErr = null;
},
/**
* Stops recording promises
* @api
*/
stop() {
debug(this.toString());
log(`${currentQueue()}Stopping recording promises`);
const err = new Error();
running = false;
},
/**
* Get latest promise in chain.
*
* @api
*/
promise() {
return promise;
},
/**
* Get a list of all chained tasks
*/
scheduled() {
return tasks.join('\n');
},
/**
* Get a state of current queue and tasks
*/
toString() {
return `Queue: ${currentQueue()}\n\nTasks: ${this.scheduled()}`;
},
};
function currentQueue() {
let session = '';
if (sessionId) session = `<${sessionId}> `;
return `[${queueId}] ${session}`;
}