/
chutzpahRunner.js
310 lines (240 loc) · 9.65 KB
/
chutzpahRunner.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
var module = module || {};
module.exports = module.exports || {};
const timers = require("timers");
module.exports.runner = async (onInitialized, onPageLoaded, isFrameworkLoaded, onFrameworkLoaded, isTestingDone) => {
const chutzpahCommon = require('../chutzpahFunctions.js');
const chutzpahFunctions = chutzpahCommon.getCommonFunctions(process.exit, updateEventTime);
var testFrameworkLoaded = false,
attemptingToSetupTestFramework = false,
testFile = null,
testMode = null,
timeOut = null,
startTime = null,
userAgent = null,
ignoreResourceLoadingError = false,
finalResult = 0,
isRunningElevated = false,
tryToFindChrome = false;
startTime = new Date().getTime();;
testFile = process.argv[2];
testMode = process.argv[3] || "execution";
timeOut = parseInt(process.argv[4]) || 5001;
if (process.argv.length > 5) {
isRunningElevated = "true" === process.argv[5].toLowerCase();
}
if (process.argv.length > 6) {
ignoreResourceLoadingError = "true" === process.argv[6].toLowerCase();
}
if (process.argv.length > 8) {
userAgent = process.argv[8];
}
function debugLog(msg) {
chutzpahFunctions.rawLog("!!_!! " + msg);
}
function updateEventTime() {
startTime = new Date().getTime();
}
async function trySetupTestFramework(evaluate) {
debugLog("trySetupTestFramework");
if (!testFrameworkLoaded && !attemptingToSetupTestFramework) {
attemptingToSetupTestFramework = true;
debugLog("checking isFrameworkLoaded ");
var loaded = await evaluate(isFrameworkLoaded);
debugLog("=== loaded:" + JSON.stringify(loaded));
if (loaded && (typeof loaded !== "string" || loaded === "true")) {
testFrameworkLoaded = true;
debugLog("calling onFrameworkLoaded");
await evaluate(onFrameworkLoaded);
}
attemptingToSetupTestFramework = false;
}
}
async function wait(delay) {
return new Promise(function (resolve, reject) {
setTimeout(resolve, delay);
});
}
async function waitFor(testIfDone, timeOutMillis) {
let maxtimeOutMillis = timeOutMillis,
isDone = false,
result = -1;
async function intervalHandler() {
debugLog("intervalHandler");
var now = new Date().getTime();
if (!isDone && ((now - startTime) < maxtimeOutMillis)) {
isDone = await testIfDone();
return -1; // Not done, try again
} else {
if (!isDone) {
return 3; // Timeout
} else {
return 0; // Done succesfully
}
}
}
while (result < 0) {
debugLog("@@@ wait...: " + result);
await wait(100);
result = await intervalHandler();
if (result >= 0) {
debugLog("Positive result, fin! " + result);
return result;
}
}
}
async function pageOpenHandler(evaluate) {
debugLog("pageOpenHandler");
var waitCondition = async () => {
let rawResult = await evaluate(isTestingDone);
let result = rawResult && (typeof rawResult !== "string" || rawResult === "true");
debugLog("@@@ waitCondition result: " + JSON.stringify(result));
return result;
};
debugLog("Promise in pageOpenHandler");
// Initialize startTime, this will get updated every time we receive
// content from the test framework
updateEventTime();
debugLog("First trySetupTestFramework");
await trySetupTestFramework(evaluate);
debugLog("Evaluate onPageLoaded");
await evaluate(onPageLoaded);
debugLog("Calling waitFor...");
return await waitFor(waitCondition, timeOut);
}
function pageInitializedHandler(evaluate) {
debugLog("pageInitializedHandler");
evaluate(onInitialized);
}
function getPageInitializationScript() {
if (testMode === 'discovery') {
return "window.chutzpah = { testMode: 'discovery', phantom: true };";
}
else {
return "window.chutzpah = { testMode: 'execution', phantom: true };";
}
}
function wrapFunctionForEvaluation(func) {
let str = '(' + func.toString() + ')()'
// If the result is an instanceof of Promise, It's resolved in context of nodejs later.
return `
{
let result = ${str};
if (result instanceof Promise) {
result;
}
else {
let json = JSON.stringify(result);
json;
}
}
`.trim()
}
const jsdom = require("jsdom/lib/old-api.js");
const fs = require('fs');
const path = require('path');
function handleError(error) {
var error;
if (typeof (error) === 'object') {
chutzpahFunctions.onError(error.message, error.stack);
}
else {
chutzpahFunctions.onError(error);
}
}
// Capture all uncaught exceptions and wrap before logging
process.on('uncaughtException', handleError);
function captureLog(message) {
//debugLog("captureLog: " + message);
//debugLog("AA" + JSON.stringify(message));
if (message.type === 'error') {
chutzpahFunctions.onError(message, message);
}
else {
chutzpahFunctions.captureLogMessage(message);
}
}
let window = null;
let evaluate = (func) => { return window.eval(wrapFunctionForEvaluation(func)); };
try {
const virtualConsole = jsdom.createVirtualConsole();
virtualConsole.on("error", (message) => { debugLog("ErrorLog: " + message); handleError(message); });
virtualConsole.on("jsdomError", (message) => { debugLog("jsdomError: " + message); handleError(message); });
virtualConsole.on("warn", (message) => { captureLog(message); });
virtualConsole.on("info", (message) => { captureLog(message); });
virtualConsole.on("log", (message) => { captureLog(message); });
const loadPagePromise = new Promise(function (resolve, reject) {
jsdom.env({
url: testFile,
virtualConsole: virtualConsole,
userAgent: userAgent,
resourceLoader: function (resource, callback) {
var href = resource.url.href;
return resource.defaultFetch((err, body) => {
if (err) {
let errorText = error.message;
if (!ignoreResourceLoadingError) {
chutzpahFunctions.onError(errorText);
}
chutzpahFunctions.rawLog("!!_!! Resource Error for " + href + " with error " + errorText);
return callback(err);
}
callback(null, body);
chutzpahFunctions.rawLog("!!_!! Resource Received: " + href);
// TODO: should I synchronize invocations of this?
trySetupTestFramework(evaluate);
});
},
features: {
FetchExternalResources: ["script", "frame", "iframe", "link", "img"],
ProcessExternalResources: ["script"],
SkipExternalResources: false
},
created: function (err, win) {
chutzpahFunctions.rawLog("!!_!! On JsDom ::created");
if (err !== null) {
return;
}
window = win;
// JSDom doesn't define these but we can use the global ones Node gives us.
window.setImmediate = timers.setImmediate;
window.clearImmediate = timers.clearImmediate;
debugLog("Setup stubs for JsDom");
window.eval(`
window.scrollTo = function() {};
HTMLCanvasElement.prototype.getContext = () => {
return {
fillStyle: null,
fillRect: function() {},
drawImage: function() {},
getImageData: function() {},
scale: function() {},
};
}
`);
debugLog("Evaling page initialization script");
window.eval(getPageInitializationScript());
pageInitializedHandler(evaluate);
},
done: function (err, win) {
chutzpahFunctions.rawLog("!!_!! On JsDom::loadDone");
if (err !== null) {
reject(err);
}
resolve();
}
});
});
debugLog("### Navigate...");
await loadPagePromise;
debugLog("### calling pageOpenHandler");
finalResult = await pageOpenHandler(evaluate);
debugLog("Just about done: " + finalResult);
if (window) { window.close(); }
} catch (err) {
chutzpahFunctions.rawLog("!!_!! Error: " + err);
if (window) { window.close(); }
process.exit(2);
}
debugLog("Closed client");
process.exit(finalResult);
};